From 0f9786bc4cb1c70d2477f8d0e238ffbb19aa4b6e Mon Sep 17 00:00:00 2001 From: Ash <71890694+ashhart@users.noreply.github.com> Date: Thu, 12 Nov 2026 15:12:27 +0000 Subject: [PATCH 1/4] metal families: refuse a token id at or past the embedding table before the lookup The embedding kernels read the table at the id they are given and none of them bounds it, so the host check is the only one. Each path now refuses an id at or past the vocabulary before it uploads the ids, and the loaders that took the table as stored refuse one whose rows are not the vocabulary's. --- zig/src/families/flashnext/backend.zig | 9 +++++---- zig/src/families/flashnext/engine_generate.zig | 1 + zig/src/families/flashnext/engine_load.zig | 5 +++++ zig/src/families/flashnext/prefill_metal.zig | 1 + zig/src/families/flashnext/replay_model.zig | 7 +++++++ zig/src/families/flashnext/replay_mtp.zig | 1 + zig/src/families/flashnext/replay_prompt_chunks.zig | 2 ++ zig/src/families/flashnext/replay_prompt_segments.zig | 1 + zig/src/families/flashnext/think.zig | 1 + zig/src/families/gemma4/dflash.zig | 1 + zig/src/families/gemma4/forward.zig | 1 + zig/src/families/gemma4/prompt.zig | 1 + zig/src/families/gemma4/weights.zig | 1 + zig/src/families/glm/backend.zig | 4 +++- zig/src/families/glm/engine.zig | 1 + zig/src/families/glm/mirror.zig | 3 ++- zig/src/families/glm/slots.zig | 11 +++++++++++ zig/src/families/glm/vision_config.zig | 10 ++++++++-- zig/src/families/glm_dsa/engine.zig | 3 +++ zig/src/families/glm_dsa/model.zig | 2 +- zig/src/families/minimax_m3/dflash2.zig | 3 ++- zig/src/families/minimax_m3/dspark.zig | 3 ++- zig/src/families/nemotron/prefill_metal.zig | 1 + zig/src/families/step5/forward.zig | 1 + 24 files changed, 63 insertions(+), 11 deletions(-) diff --git a/zig/src/families/flashnext/backend.zig b/zig/src/families/flashnext/backend.zig index d7f7ad6c241..92c368278e5 100644 --- a/zig/src/families/flashnext/backend.zig +++ b/zig/src/families/flashnext/backend.zig @@ -371,6 +371,7 @@ pub const Backend = struct { for (windows, out, 0..) |w, o, i| { const s = try b.session(w.stream); if (w.parents != null or w.early or w.held > s.held_n) return error.WindowOutOfStep; + if (w.pending >= fz.VOCAB or !fz.Model.inVocab(w.tokens)) return error.TokenOutsideVocabulary; if (w.rows() > fz.MAXR or w.rows() > s.m.cap - s.m.pos or w.positions.len != w.rows() or o.sampled.len != w.rows() or o.drafts.len != w.rows() - 1) return error.WindowOutOfStep; @@ -456,8 +457,8 @@ pub const Backend = struct { .value => |v| v, .handle => |h| @intCast(h), }; - break :blk one[0..]; - } else r.follow; + break :blk if (one[0] < fz.VOCAB) one[0..] else return error.TokenOutsideVocabulary; + } else if (fz.Model.inVocab(r.follow)) r.follow else return error.TokenOutsideVocabulary; const hidden = if (r.rows) |path| blk: { try s.round.draft(r.start, path, follow.len); break :blk b.hidden.at(s.row0 * fz.WIDE * 2); @@ -506,8 +507,8 @@ pub const Backend = struct { .value => |v| v, .handle => |h| @intCast(h), }; - break :blk ones[k][0..]; - } else r.follow; + break :blk if (ones[k][0] < fz.VOCAB) ones[k][0..] else return error.TokenOutsideVocabulary; + } else if (fz.Model.inVocab(r.follow)) r.follow else return error.TokenOutsideVocabulary; if (follows[k].len == 0) return error.DraftOutOfStep; hiddens[k] = if (r.rows) |path| blk: { try s.round.draft(r.start, path, follows[k].len); diff --git a/zig/src/families/flashnext/engine_generate.zig b/zig/src/families/flashnext/engine_generate.zig index 3bbd21ee3bb..d3675fd4020 100644 --- a/zig/src/families/flashnext/engine_generate.zig +++ b/zig/src/families/flashnext/engine_generate.zig @@ -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); diff --git a/zig/src/families/flashnext/engine_load.zig b/zig/src/families/flashnext/engine_load.zig index 1e51ff7b523..2c3aa84594a 100644 --- a/zig/src/families/flashnext/engine_load.zig +++ b/zig/src/families/flashnext/engine_load.zig @@ -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); diff --git a/zig/src/families/flashnext/prefill_metal.zig b/zig/src/families/flashnext/prefill_metal.zig index 47237d7dd18..f68483a3983 100644 --- a/zig/src/families/flashnext/prefill_metal.zig +++ b/zig/src/families/flashnext/prefill_metal.zig @@ -18,6 +18,7 @@ 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)) return error.TokenOutsideVocabulary; // before a slot is taken or a chunk runs 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; diff --git a/zig/src/families/flashnext/replay_model.zig b/zig/src/families/flashnext/replay_model.zig index 6802f3939d8..7602e81950d 100644 --- a/zig/src/families/flashnext/replay_model.zig +++ b/zig/src/families/flashnext/replay_model.zig @@ -158,8 +158,15 @@ 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 { + if (!inVocab(tokens)) return error.TokenOutsideVocabulary; const r = m.r; const t = &m.t; const rows = tokens.len; diff --git a/zig/src/families/flashnext/replay_mtp.zig b/zig/src/families/flashnext/replay_mtp.zig index c229682dc12..7182c23b021 100644 --- a/zig/src/families/flashnext/replay_mtp.zig +++ b/zig/src/families/flashnext/replay_mtp.zig @@ -18,6 +18,7 @@ const Model = fz.Model; const finish = Model.finish; pub fn mtpRun(m: *Model, nexts: []const u32, streams: Buf) !u32 { + if (!Model.inVocab(nexts)) return error.TokenOutsideVocabulary; const r = m.r; const h = &m.mtp; const rows = nexts.len; diff --git a/zig/src/families/flashnext/replay_prompt_chunks.zig b/zig/src/families/flashnext/replay_prompt_chunks.zig index a8de2fb036c..e39134bd2bb 100644 --- a/zig/src/families/flashnext/replay_prompt_chunks.zig +++ b/zig/src/families/flashnext/replay_prompt_chunks.zig @@ -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); @@ -324,6 +325,7 @@ pub fn mtpKeys(p: *Prompt, m: *Model, start: usize, nexts: []const u32, streams: const n = nexts.len; if (n == 0) return; if (n > PMAX) return error.ChunkSize; + if (!Model.inVocab(nexts)) return error.TokenOutsideVocabulary; @memcpy(b.mids.b.slice(u32, n), nexts); for (0..n) |i| b.pos.b.slice(i32, PMAX)[i] = @intCast(start + i); const kvm = b.kvmeta.b.slice(u32, 3); diff --git a/zig/src/families/flashnext/replay_prompt_segments.zig b/zig/src/families/flashnext/replay_prompt_segments.zig index e8102110d99..d8c60bbef3f 100644 --- a/zig/src/families/flashnext/replay_prompt_segments.zig +++ b/zig/src/families/flashnext/replay_prompt_segments.zig @@ -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); diff --git a/zig/src/families/flashnext/think.zig b/zig/src/families/flashnext/think.zig index a1fca2018b7..d5e9ac6a15a 100644 --- a/zig/src/families/flashnext/think.zig +++ b/zig/src/families/flashnext/think.zig @@ -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 }; } diff --git a/zig/src/families/gemma4/dflash.zig b/zig/src/families/gemma4/dflash.zig index 7774b78e150..d21828973b0 100644 --- a/zig/src/families/gemma4/dflash.zig +++ b/zig/src/families/gemma4/dflash.zig @@ -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; diff --git a/zig/src/families/gemma4/forward.zig b/zig/src/families/gemma4/forward.zig index 798cf339f92..ee00c6eaf33 100644 --- a/zig/src/families/gemma4/forward.zig +++ b/zig/src/families/gemma4/forward.zig @@ -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; diff --git a/zig/src/families/gemma4/prompt.zig b/zig/src/families/gemma4/prompt.zig index 6512173e363..5e41b546c9a 100644 --- a/zig/src/families/gemma4/prompt.zig +++ b/zig/src/families/gemma4/prompt.zig @@ -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| { diff --git a/zig/src/families/gemma4/weights.zig b/zig/src/families/gemma4/weights.zig index 365fcacd375..3fa13ddafe9 100644 --- a/zig/src/families/gemma4/weights.zig +++ b/zig/src/families/gemma4/weights.zig @@ -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"); diff --git a/zig/src/families/glm/backend.zig b/zig/src/families/glm/backend.zig index 9c3429cc602..92b4ff58d10 100644 --- a/zig/src/families/glm/backend.zig +++ b/zig/src/families/glm/backend.zig @@ -117,6 +117,7 @@ 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 if (prompt.len + s.max_new + st.max_rows + 1 > pool.capacity(b.sl)) return error.ContextFull; 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; @@ -362,7 +363,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); @@ -400,6 +401,7 @@ pub const Backend = struct { try b.wins.append(b.gpa, .{ .slot = i, .pending = w.pending, .held = w.held, .tokens = w.tokens }); } if (total > st.max_rows) return error.WindowOutOfStep; + try b.sl.checkWindows(b.wins.items); // before rank 1 hears of them const draws = @import("draw_rule.zig").windowDraws(windows, b.sl.e.c.vocab); try mirror.windowWords(&b.words, b.gpa, b.sl.digest, b.wins.items); try mirror.send(b.sl.e, .window, b.words.items); diff --git a/zig/src/families/glm/engine.zig b/zig/src/families/glm/engine.zig index 31b2e21c0f8..1a4c9bc49c4 100644 --- a/zig/src/families/glm/engine.zig +++ b/zig/src/families/glm/engine.zig @@ -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(); diff --git a/zig/src/families/glm/mirror.zig b/zig/src/families/glm/mirror.zig index 02d9d3be7d9..1d96594984a 100644 --- a/zig/src/families/glm/mirror.zig +++ b/zig/src/families/glm/mirror.zig @@ -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), diff --git a/zig/src/families/glm/slots.zig b/zig/src/families/glm/slots.zig index 498894344c2..6374eece700 100644 --- a/zig/src/families/glm/slots.zig +++ b/zig/src/families/glm/slots.zig @@ -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; @@ -282,11 +283,20 @@ pub const Slots = struct { } }; + /// Windows whose host tokens are rows of the embedding; rank 0 asks before rank 1 hears of them. + pub fn checkWindows(sl: *const Slots, wins: []const Win) !void { + for (wins) |w| { + if (w.pending >= sl.e.c.vocab) return error.TokenOutsideVocabulary; + for (w.tokens) |t| if (t >= sl.e.c.vocab) return error.TokenOutsideVocabulary; + } + } + /// One forward over every window, each stream's rows against its own caches; `draws` rules its rows. pub fn window(sl: *Slots, wins: []const Win, draws: ?*const fwd.Draws) !void { const e = sl.e; var segs: [st.max_rows]fwd.Seg = undefined; if (wins.len == 0 or wins.len > segs.len) return error.WindowOutOfStep; + try sl.checkWindows(wins); const t_in = platform.c.mach_absolute_time(); sl.settleAll(); try sl.launch(); // the GPU runs the keeps and drafts while the window encodes @@ -434,6 +444,7 @@ pub const Slots = struct { const n = r.follow.len; if (!slot.mtp or n == 0 or r.depth >= st.max_rows or (r.prompt and n != 1)) return error.DraftOutOfStep; if (!r.prompt and (slot.seen != sl.windows or n > slot.width)) return error.DraftOutOfStep; // this window's + for (r.follow) |t| if (t >= sl.e.c.vocab) return error.TokenOutsideVocabulary; for (reqs[0..k]) |o| if (o.slot == r.slot) return error.DraftOutOfStep; total += n; } diff --git a/zig/src/families/glm/vision_config.zig b/zig/src/families/glm/vision_config.zig index 6b9ce215c12..01ae794010f 100644 --- a/zig/src/families/glm/vision_config.zig +++ b/zig/src/families/glm/vision_config.zig @@ -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, .{}); diff --git a/zig/src/families/glm_dsa/engine.zig b/zig/src/families/glm_dsa/engine.zig index 860c26aa387..5074b4d8b02 100644 --- a/zig/src/families/glm_dsa/engine.zig +++ b/zig/src/families/glm_dsa/engine.zig @@ -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; @@ -204,6 +205,7 @@ pub const Engine = struct { pub fn window(e: *Engine, wins: []const Win, out: []u32) !void { var rows: u32 = 0; var top: u32 = 0; + for (wins) |w| for (w.tokens) |t| if (t >= e.m.c.vocab) return error.TokenOutsideVocabulary; for (wins) |w| { if (w.slot >= e.slots.len) return error.WindowOutOfStep; const s = &e.slots[w.slot]; @@ -263,6 +265,7 @@ pub const Engine = struct { pub fn draft(e: *Engine, reqs: []const Draft) !void { if (!e.hasMtp()) return error.NoMtpHead; if (reqs.len == 0 or reqs.len > R) return error.DraftOutOfStep; + for (reqs) |q| for (q.follow) |t| if (t >= e.m.c.vocab) return error.TokenOutsideVocabulary; var rows: u32 = 0; var depth: u32 = 0; var ends: [R]u32 = undefined; diff --git a/zig/src/families/glm_dsa/model.zig b/zig/src/families/glm_dsa/model.zig index cd9960b0e80..3b1c0c500a7 100644 --- a/zig/src/families/glm_dsa/model.zig +++ b/zig/src/families/glm_dsa/model.zig @@ -85,7 +85,7 @@ pub const Model = struct { var p = pack.Pack.init(gpa); defer p.deinit(); const emb = try ex.dense.Matrix.get(&f, "embed_tokens"); - if (emb.record.format != .fp8_row or emb.record.in != c.hidden) return error.UnsupportedGlmEmbedding; + if (emb.record.format != .fp8_row or emb.record.in != c.hidden or emb.record.out != c.vocab) return error.UnsupportedGlmEmbedding; const part = c.vocabPart(); var v: Vocab = .{ .k = undefined, .embed_fp8 = try p.vector(emb.data[0].bytes), .embed_scale = try p.vector(emb.data[1].bytes), .groups = undefined, .norm = try p.vector((f.get("norm.weight") orelse return error.MissingGlmTensor).bytes), .part = part }; const head = try p.linear(try ex.dense.Matrix.get(&f, "lm_head"), .{ part[0], part[1] }, .{ 0, c.hidden }); diff --git a/zig/src/families/minimax_m3/dflash2.zig b/zig/src/families/minimax_m3/dflash2.zig index 48e838af538..d0f2a741ca3 100644 --- a/zig/src/families/minimax_m3/dflash2.zig +++ b/zig/src/families/minimax_m3/dflash2.zig @@ -196,7 +196,7 @@ pub const Drafter = struct { errdefer gpa.destroy(d); d.* = .{ .gpa = gpa, .target = target, .config = config, .w = try load(&target.checkpoint, &config, target.config.vocab), .pipes = undefined }; const c = &d.config; - if (c.hidden != target.config.hidden) return error.DFlash2ForAnotherTarget; + if (c.hidden != target.config.hidden or c.mask >= target.config.vocab) return error.DFlash2ForAnotherTarget; for (c.taps) |l| if (l >= target.config.layers) return error.DFlash2ForAnotherTarget; { const lib = try mtl.Library.fromSource(target.device, ks.minimax_m3_dflash2, .{ .language = mtl.CompileOptions.mlx().language, .math_functions = .precise }); @@ -515,6 +515,7 @@ pub const Drafter = struct { for (pass, blocks[0..count]) |it, *k| { const l = d.lanes.get(it.stream) orelse return error.DraftStreamUnknown; if (it.depth == 0 or it.depth > c.block - 1 or it.position == 0) return error.DraftDepth; + if (it.pending >= d.target.config.vocab) return error.InvalidMiniMaxToken; // embed reads row id unchecked const anchor = it.position - 1; if (l.end != anchor) return error.DraftContextGap; k.* = .{ .lane = l, .pending = it.pending, .anchor = anchor }; diff --git a/zig/src/families/minimax_m3/dspark.zig b/zig/src/families/minimax_m3/dspark.zig index 2794a42cff2..3eb4c1e2875 100644 --- a/zig/src/families/minimax_m3/dspark.zig +++ b/zig/src/families/minimax_m3/dspark.zig @@ -191,7 +191,7 @@ pub const Drafter = struct { errdefer gpa.destroy(d); d.* = .{ .gpa = gpa, .target = target, .config = config, .w = try load(&target.checkpoint, &config, target.config.vocab), .pipes = undefined }; const c = &d.config; - if (c.hidden != target.config.hidden) return error.DSparkForAnotherTarget; + if (c.hidden != target.config.hidden or c.noise >= target.config.vocab) return error.DSparkForAnotherTarget; for (c.taps) |l| if (l >= target.config.layers) return error.DSparkForAnotherTarget; { const lib = try mtl.Library.fromSource(target.device, ks.minimax_m3_dspark, .{ .language = mtl.CompileOptions.mlx().language, .math_functions = .precise }); @@ -492,6 +492,7 @@ pub const Drafter = struct { for (pass, blocks[0..count]) |it, *k| { const l = d.lanes.get(it.stream) orelse return error.DraftStreamUnknown; if (it.depth == 0 or it.depth > c.block or it.position == 0) return error.DraftDepth; + if (it.pending >= d.target.config.vocab) return error.InvalidMiniMaxToken; // embed reads row id unchecked const anchor = it.position - 1; if (l.end != anchor) return error.DraftContextGap; k.* = .{ .lane = l, .pending = it.pending, .anchor = anchor }; diff --git a/zig/src/families/nemotron/prefill_metal.zig b/zig/src/families/nemotron/prefill_metal.zig index 0490f471b99..f0cd87fe712 100644 --- a/zig/src/families/nemotron/prefill_metal.zig +++ b/zig/src/families/nemotron/prefill_metal.zig @@ -85,6 +85,7 @@ const Ops = struct { const self = o.m; const ids = s.prompt(); try backend.limits.check(ids.len, s.max_new, self.o.capacity); + for (ids) |id| if (id >= self.m.config.vocab) return error.TokenOutsideVocabulary; if (s.isCancelled()) return error.Cancelled; const rows_needed = @min(self.o.capacity, ids.len + s.max_new + backend.max_lanes + 1); // the reply and a widest window past it try self.drain(); diff --git a/zig/src/families/step5/forward.zig b/zig/src/families/step5/forward.zig index 67ae0faf590..9e169278e22 100644 --- a/zig/src/families/step5/forward.zig +++ b/zig/src/families/step5/forward.zig @@ -130,6 +130,7 @@ pub fn mtp(m: *const Model, s: *st.Scratch, cache: *st.Cache, k: usize, hidden: const n = tokens.len; if (n == 0 or n > s.rows or k >= c.mtp) return error.Step5RowsExceeded; if (start + n > cache.capacity) return error.Step5ContextFull; + for (tokens) |id| if (id >= c.vocab) return error.InvalidStep5Token; @memcpy(s.ids.slice(u32, n), tokens); const h: usize = c.hidden; const nr: u32 = @intCast(n); From 382a6c866b95ec9c27dabe2bea49c4e889bbd10b Mon Sep 17 00:00:00 2001 From: Ash <71890694+ashhart@users.noreply.github.com> Date: Thu, 12 Nov 2026 17:48:44 +0000 Subject: [PATCH 2/4] metal drafters: refuse a pending id past the embedding in the Gemma assistant and the tree feed gemma_assist_input clamps an id past the table to its last row, so the Metal assistant drafted from the wrong row for a pending id at or past the vocabulary; its hold now refuses one before any stream's work, as the DFlash drafter does. FZ_FEED's tree guesses become window ids and are refused when the feed is read. test-token-ids-metal-host runs both host tests on the shader-free engine module. --- build.zig | 1 + zig/build/host_ci.zig | 1 + zig/src/families/flashnext/tree.zig | 11 +++++++++++ zig/src/families/gemma4/assistant.zig | 14 ++++++++++++++ zig/src/tensorfold.zig | 1 + 5 files changed, 28 insertions(+) diff --git a/build.zig b/build.zig index b73b401db17..c7d489420fa 100644 --- a/build.zig +++ b/build.zig @@ -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); diff --git a/zig/build/host_ci.zig b/zig/build/host_ci.zig index 90a88709dd6..ef626a3ddfd 100644 --- a/zig/build/host_ci.zig +++ b/zig/build/host_ci.zig @@ -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", }; diff --git a/zig/src/families/flashnext/tree.zig b/zig/src/families/flashnext/tree.zig index 2c7327b0d28..a1a2db4463a 100644 --- a/zig/src/families/flashnext/tree.zig +++ b/zig/src/families/flashnext/tree.zig @@ -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]); diff --git a/zig/src/families/gemma4/assistant.zig b/zig/src/families/gemma4/assistant.zig index 64c56f559e2..e6be066e8d8 100644 --- a/zig/src/families/gemma4/assistant.zig +++ b/zig/src/families/gemma4/assistant.zig @@ -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; @@ -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); } diff --git a/zig/src/tensorfold.zig b/zig/src/tensorfold.zig index 5a29cf3aef1..c325c9e9529 100644 --- a/zig/src/tensorfold.zig +++ b/zig/src/tensorfold.zig @@ -106,6 +106,7 @@ test { _ = @import("families/flashnext/dense.zig"); // The core projection adapter keeps format, cuts and tiles. _ = @import("families/flashnext/marks.zig"); // a call's marks _ = @import("families/flashnext/think.zig"); // a thinking budget's close on the host + _ = @import("families/flashnext/tree.zig"); // a tree feed's guesses, which become window ids _ = @import("families/flashnext/backend.zig"); // shared-session family tests _ = @import("families/flashnext/lone_stream.zig"); // the first commit can relocate the prompt _ = @import("families/flashnext/slots.zig"); // sized shared sessions: the list, a stream's session, when it grows From 91ed6f749cc3dcd16987a7e47654343f19709642 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 17 Nov 2026 22:25:50 +0000 Subject: [PATCH 3/4] metal: admit external ids once and preserve trusted draft rounds --- zig/src/core/lanes/recall.zig | 14 +++++++ zig/src/core/lanes/recall_store.zig | 2 +- zig/src/core/lanes/recall_store_test.zig | 39 +++++++++++++++++++ zig/src/families/flashnext/backend.zig | 9 ++--- zig/src/families/flashnext/prefill_metal.zig | 3 +- zig/src/families/flashnext/replay_model.zig | 1 - zig/src/families/flashnext/replay_mtp.zig | 1 - .../flashnext/replay_prompt_chunks.zig | 1 - zig/src/families/glm/backend.zig | 3 +- zig/src/families/glm/slots.zig | 10 ----- zig/src/families/glm_dsa/backend.zig | 2 + zig/src/families/glm_dsa/engine.zig | 2 - zig/src/families/nemotron/backend.zig | 7 ++-- zig/src/families/nemotron/prefill_metal.zig | 2 + 14 files changed, 70 insertions(+), 26 deletions(-) diff --git a/zig/src/core/lanes/recall.zig b/zig/src/core/lanes/recall.zig index 6634685d3f5..fed27ea0ec2 100644 --- a/zig/src/core/lanes/recall.zig +++ b/zig/src/core/lanes/recall.zig @@ -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 { @@ -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); } diff --git a/zig/src/core/lanes/recall_store.zig b/zig/src/core/lanes/recall_store.zig index 96289064337..fe25e75cc73 100644 --- a/zig/src/core/lanes/recall_store.zig +++ b/zig/src/core/lanes/recall_store.zig @@ -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, diff --git a/zig/src/core/lanes/recall_store_test.zig b/zig/src/core/lanes/recall_store_test.zig index 47828109d65..dbbbdbd3da4 100644 --- a/zig/src/core/lanes/recall_store_test.zig +++ b/zig/src/core/lanes/recall_store_test.zig @@ -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)); +} diff --git a/zig/src/families/flashnext/backend.zig b/zig/src/families/flashnext/backend.zig index 92c368278e5..d7f7ad6c241 100644 --- a/zig/src/families/flashnext/backend.zig +++ b/zig/src/families/flashnext/backend.zig @@ -371,7 +371,6 @@ pub const Backend = struct { for (windows, out, 0..) |w, o, i| { const s = try b.session(w.stream); if (w.parents != null or w.early or w.held > s.held_n) return error.WindowOutOfStep; - if (w.pending >= fz.VOCAB or !fz.Model.inVocab(w.tokens)) return error.TokenOutsideVocabulary; if (w.rows() > fz.MAXR or w.rows() > s.m.cap - s.m.pos or w.positions.len != w.rows() or o.sampled.len != w.rows() or o.drafts.len != w.rows() - 1) return error.WindowOutOfStep; @@ -457,8 +456,8 @@ pub const Backend = struct { .value => |v| v, .handle => |h| @intCast(h), }; - break :blk if (one[0] < fz.VOCAB) one[0..] else return error.TokenOutsideVocabulary; - } else if (fz.Model.inVocab(r.follow)) r.follow else return error.TokenOutsideVocabulary; + break :blk one[0..]; + } else r.follow; const hidden = if (r.rows) |path| blk: { try s.round.draft(r.start, path, follow.len); break :blk b.hidden.at(s.row0 * fz.WIDE * 2); @@ -507,8 +506,8 @@ pub const Backend = struct { .value => |v| v, .handle => |h| @intCast(h), }; - break :blk if (ones[k][0] < fz.VOCAB) ones[k][0..] else return error.TokenOutsideVocabulary; - } else if (fz.Model.inVocab(r.follow)) r.follow else return error.TokenOutsideVocabulary; + break :blk ones[k][0..]; + } else r.follow; if (follows[k].len == 0) return error.DraftOutOfStep; hiddens[k] = if (r.rows) |path| blk: { try s.round.draft(r.start, path, follows[k].len); diff --git a/zig/src/families/flashnext/prefill_metal.zig b/zig/src/families/flashnext/prefill_metal.zig index f68483a3983..4b23e09dc03 100644 --- a/zig/src/families/flashnext/prefill_metal.zig +++ b/zig/src/families/flashnext/prefill_metal.zig @@ -18,7 +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)) return error.TokenOutsideVocabulary; // before a slot is taken or a chunk runs + 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; diff --git a/zig/src/families/flashnext/replay_model.zig b/zig/src/families/flashnext/replay_model.zig index 7602e81950d..c32be2964dd 100644 --- a/zig/src/families/flashnext/replay_model.zig +++ b/zig/src/families/flashnext/replay_model.zig @@ -166,7 +166,6 @@ pub const Model = struct { /// 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 { - if (!inVocab(tokens)) return error.TokenOutsideVocabulary; const r = m.r; const t = &m.t; const rows = tokens.len; diff --git a/zig/src/families/flashnext/replay_mtp.zig b/zig/src/families/flashnext/replay_mtp.zig index 7182c23b021..c229682dc12 100644 --- a/zig/src/families/flashnext/replay_mtp.zig +++ b/zig/src/families/flashnext/replay_mtp.zig @@ -18,7 +18,6 @@ const Model = fz.Model; const finish = Model.finish; pub fn mtpRun(m: *Model, nexts: []const u32, streams: Buf) !u32 { - if (!Model.inVocab(nexts)) return error.TokenOutsideVocabulary; const r = m.r; const h = &m.mtp; const rows = nexts.len; diff --git a/zig/src/families/flashnext/replay_prompt_chunks.zig b/zig/src/families/flashnext/replay_prompt_chunks.zig index e39134bd2bb..666ece07637 100644 --- a/zig/src/families/flashnext/replay_prompt_chunks.zig +++ b/zig/src/families/flashnext/replay_prompt_chunks.zig @@ -325,7 +325,6 @@ pub fn mtpKeys(p: *Prompt, m: *Model, start: usize, nexts: []const u32, streams: const n = nexts.len; if (n == 0) return; if (n > PMAX) return error.ChunkSize; - if (!Model.inVocab(nexts)) return error.TokenOutsideVocabulary; @memcpy(b.mids.b.slice(u32, n), nexts); for (0..n) |i| b.pos.b.slice(i32, PMAX)[i] = @intCast(start + i); const kvm = b.kvmeta.b.slice(u32, 3); diff --git a/zig/src/families/glm/backend.zig b/zig/src/families/glm/backend.zig index 92b4ff58d10..4afd77848f4 100644 --- a/zig/src/families/glm/backend.zig +++ b/zig/src/families/glm/backend.zig @@ -118,7 +118,9 @@ pub const Backend = struct { 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); @@ -401,7 +403,6 @@ pub const Backend = struct { try b.wins.append(b.gpa, .{ .slot = i, .pending = w.pending, .held = w.held, .tokens = w.tokens }); } if (total > st.max_rows) return error.WindowOutOfStep; - try b.sl.checkWindows(b.wins.items); // before rank 1 hears of them const draws = @import("draw_rule.zig").windowDraws(windows, b.sl.e.c.vocab); try mirror.windowWords(&b.words, b.gpa, b.sl.digest, b.wins.items); try mirror.send(b.sl.e, .window, b.words.items); diff --git a/zig/src/families/glm/slots.zig b/zig/src/families/glm/slots.zig index 6374eece700..f07f9ecbf3b 100644 --- a/zig/src/families/glm/slots.zig +++ b/zig/src/families/glm/slots.zig @@ -283,20 +283,11 @@ pub const Slots = struct { } }; - /// Windows whose host tokens are rows of the embedding; rank 0 asks before rank 1 hears of them. - pub fn checkWindows(sl: *const Slots, wins: []const Win) !void { - for (wins) |w| { - if (w.pending >= sl.e.c.vocab) return error.TokenOutsideVocabulary; - for (w.tokens) |t| if (t >= sl.e.c.vocab) return error.TokenOutsideVocabulary; - } - } - /// One forward over every window, each stream's rows against its own caches; `draws` rules its rows. pub fn window(sl: *Slots, wins: []const Win, draws: ?*const fwd.Draws) !void { const e = sl.e; var segs: [st.max_rows]fwd.Seg = undefined; if (wins.len == 0 or wins.len > segs.len) return error.WindowOutOfStep; - try sl.checkWindows(wins); const t_in = platform.c.mach_absolute_time(); sl.settleAll(); try sl.launch(); // the GPU runs the keeps and drafts while the window encodes @@ -444,7 +435,6 @@ pub const Slots = struct { const n = r.follow.len; if (!slot.mtp or n == 0 or r.depth >= st.max_rows or (r.prompt and n != 1)) return error.DraftOutOfStep; if (!r.prompt and (slot.seen != sl.windows or n > slot.width)) return error.DraftOutOfStep; // this window's - for (r.follow) |t| if (t >= sl.e.c.vocab) return error.TokenOutsideVocabulary; for (reqs[0..k]) |o| if (o.slot == r.slot) return error.DraftOutOfStep; total += n; } diff --git a/zig/src/families/glm_dsa/backend.zig b/zig/src/families/glm_dsa/backend.zig index b853f8216f3..b086ae64285 100644 --- a/zig/src/families/glm_dsa/backend.zig +++ b/zig/src/families/glm_dsa/backend.zig @@ -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); diff --git a/zig/src/families/glm_dsa/engine.zig b/zig/src/families/glm_dsa/engine.zig index 5074b4d8b02..a6aa0d97339 100644 --- a/zig/src/families/glm_dsa/engine.zig +++ b/zig/src/families/glm_dsa/engine.zig @@ -205,7 +205,6 @@ pub const Engine = struct { pub fn window(e: *Engine, wins: []const Win, out: []u32) !void { var rows: u32 = 0; var top: u32 = 0; - for (wins) |w| for (w.tokens) |t| if (t >= e.m.c.vocab) return error.TokenOutsideVocabulary; for (wins) |w| { if (w.slot >= e.slots.len) return error.WindowOutOfStep; const s = &e.slots[w.slot]; @@ -265,7 +264,6 @@ pub const Engine = struct { pub fn draft(e: *Engine, reqs: []const Draft) !void { if (!e.hasMtp()) return error.NoMtpHead; if (reqs.len == 0 or reqs.len > R) return error.DraftOutOfStep; - for (reqs) |q| for (q.follow) |t| if (t >= e.m.c.vocab) return error.TokenOutsideVocabulary; var rows: u32 = 0; var depth: u32 = 0; var ends: [R]u32 = undefined; diff --git a/zig/src/families/nemotron/backend.zig b/zig/src/families/nemotron/backend.zig index df9a0f6d3ad..5f9d9c46cb8 100644 --- a/zig/src/families/nemotron/backend.zig +++ b/zig/src/families/nemotron/backend.zig @@ -261,10 +261,11 @@ pub const Metal = struct { } /// A host token into a fresh ring slot (no command in flight reads a fresh slot). - fn feedSlot(self: *Metal, feed: be.Feed) u64 { + fn feedSlot(self: *Metal, feed: be.Feed) !u64 { return switch (feed) { .handle => |h| h, .value => |v| blk: { + if (v >= self.m.config.vocab) return error.TokenOutsideVocabulary; const h = self.take(1); self.tokens.slice(u32, ring)[h % ring] = v; break :blk h; @@ -276,7 +277,7 @@ pub const Metal = struct { const self: *Metal = @ptrCast(@alignCast(ptr)); const c = try self.cacheOf(s); self.settle(c); - const in = self.feedSlot(feed); + const in = try self.feedSlot(feed); const out = self.take(1); if (c.len + 1 > c.kv[0].capacity) return error.ContextFull; try kv_pages.grow(c, c.len + 1); @@ -436,7 +437,7 @@ pub const Metal = struct { jobs[i].path = rows; @memcpy(c.follow.slice(u32, rows.len), r.follow[0..rows.len]); } else { - jobs[i].token = self.feedSlot(r.first orelse return error.NoFirstToken); + jobs[i].token = try self.feedSlot(r.first orelse return error.NoFirstToken); } } const All = struct { diff --git a/zig/src/families/nemotron/prefill_metal.zig b/zig/src/families/nemotron/prefill_metal.zig index f0cd87fe712..151b165f7aa 100644 --- a/zig/src/families/nemotron/prefill_metal.zig +++ b/zig/src/families/nemotron/prefill_metal.zig @@ -86,7 +86,9 @@ const Ops = struct { const ids = s.prompt(); try backend.limits.check(ids.len, s.max_new, self.o.capacity); for (ids) |id| if (id >= self.m.config.vocab) return error.TokenOutsideVocabulary; + for (s.think_close) |id| if (id >= self.m.config.vocab) return error.TokenOutsideVocabulary; if (s.isCancelled()) return error.Cancelled; + if (s.recall) |reader| try reader.checkVocabulary(self.m.config.vocab); const rows_needed = @min(self.o.capacity, ids.len + s.max_new + backend.max_lanes + 1); // the reply and a widest window past it try self.drain(); if (self.caches.get(s)) |old| { From af8990382be09cbd2e3155e90f74ff89e8394e39 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sun, 22 Nov 2026 03:20:30 +0000 Subject: [PATCH 4/4] adapt: check external ids at admission, not on the decode-step path --- zig/src/families/minimax_m3/dflash2.zig | 1 - zig/src/families/minimax_m3/dspark.zig | 1 - zig/src/families/minimax_m3/prompt_pass.zig | 1 + 3 files changed, 1 insertion(+), 2 deletions(-) diff --git a/zig/src/families/minimax_m3/dflash2.zig b/zig/src/families/minimax_m3/dflash2.zig index d0f2a741ca3..f025bd23580 100644 --- a/zig/src/families/minimax_m3/dflash2.zig +++ b/zig/src/families/minimax_m3/dflash2.zig @@ -515,7 +515,6 @@ pub const Drafter = struct { for (pass, blocks[0..count]) |it, *k| { const l = d.lanes.get(it.stream) orelse return error.DraftStreamUnknown; if (it.depth == 0 or it.depth > c.block - 1 or it.position == 0) return error.DraftDepth; - if (it.pending >= d.target.config.vocab) return error.InvalidMiniMaxToken; // embed reads row id unchecked const anchor = it.position - 1; if (l.end != anchor) return error.DraftContextGap; k.* = .{ .lane = l, .pending = it.pending, .anchor = anchor }; diff --git a/zig/src/families/minimax_m3/dspark.zig b/zig/src/families/minimax_m3/dspark.zig index 3eb4c1e2875..428c926b619 100644 --- a/zig/src/families/minimax_m3/dspark.zig +++ b/zig/src/families/minimax_m3/dspark.zig @@ -492,7 +492,6 @@ pub const Drafter = struct { for (pass, blocks[0..count]) |it, *k| { const l = d.lanes.get(it.stream) orelse return error.DraftStreamUnknown; if (it.depth == 0 or it.depth > c.block or it.position == 0) return error.DraftDepth; - if (it.pending >= d.target.config.vocab) return error.InvalidMiniMaxToken; // embed reads row id unchecked const anchor = it.position - 1; if (l.end != anchor) return error.DraftContextGap; k.* = .{ .lane = l, .pending = it.pending, .anchor = anchor }; diff --git a/zig/src/families/minimax_m3/prompt_pass.zig b/zig/src/families/minimax_m3/prompt_pass.zig index a46b9dbec1e..ed6adbf34ea 100644 --- a/zig/src/families/minimax_m3/prompt_pass.zig +++ b/zig/src/families/minimax_m3/prompt_pass.zig @@ -110,6 +110,7 @@ const Run = struct { fn opening(self: *Metal, stream: *lanes.Stream) !*Pass { const ids = stream.prompt(); if (ids.len == 0 or ids.len + stream.max_new > self.options.capacity or self.caches.contains(stream)) return error.InvalidMiniMaxPrompt; + for (ids) |id| if (id >= self.model.config.vocab) return error.InvalidMiniMaxToken; // external ids checked once, before any step const capacity = ids.len + stream.max_new + 1; const need = st.cacheBytes(&self.model.config, capacity); if (self.held + need > self.options.budget) {