Skip to content

Commit 8e10577

Browse files
committed
refactor(rerank): declare the reranker in the engine's Info
The review asked that the engine, not a file in the served folder, make a server a reranker, as embedding engines declare .embeddings, and that the label rows not wait for the first request: Info gains rerank (the yes and no tokens), the qwen3 family parses and checks 1_LogitScore and reads both lm_head rows at load, and the server drops its own reader, so no other engine can answer /v1/rerank.
1 parent 8323634 commit 8e10577

10 files changed

Lines changed: 80 additions & 111 deletions

File tree

‎zig/src/core/engine_api.zig‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,6 +171,9 @@ pub const Sink = struct {
171171
event: *const fn (ctx: *anyopaque, id: Id, event: *const Event) void,
172172
};
173173

174+
/// A reranker's label tokens: a prompt's relevance score is sigmoid(yes - no) of their last-row logits.
175+
pub const Rerank = struct { yes: u32, no: u32 };
176+
174177
/// What the engine serves, fixed once it has loaded.
175178
pub const Info = struct {
176179
name: []const u8 = "lanes",
@@ -220,6 +223,8 @@ pub const Info = struct {
220223
decode_share: ?f64 = null,
221224
/// The engine scores decisions (`score`) and writes no text: the server refuses text requests.
222225
decides: bool = false,
226+
/// The engine is a reranker (it scores through `score`): the server answers POST /v1/rerank only when set.
227+
rerank: ?Rerank = null,
223228
/// Decisions may carry pictures (`Decision.pictures`).
224229
pictures: bool = false,
225230
/// Image input (--vision); null: text only.

‎zig/src/families/qwen3/native.zig‎

Lines changed: 52 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,8 @@ pub const Loaded = struct {
4242
window: ?usize = null,
4343
/// A reranker: the engine scores labels (the score hook) and serves no embeddings.
4444
decides: bool = false,
45+
/// The reranker's label tokens, from `1_LogitScore/config.json`.
46+
rerank: ?api.Rerank = null,
4547
};
4648

4749
pub const Refused = error{Refused};
@@ -55,8 +57,8 @@ fn refuse(a: Allocator, problem: *[]const u8, comptime fmt: []const u8, args: an
5557
pub const Head = union(enum) {
5658
/// sentence-transformers last-token pooling, unit-normed when modules.json lists Normalize.
5759
embedding: struct { normalize: bool },
58-
/// A reranker: `1_LogitScore` names the yes and no tokens its last row's logits score (the server reads them).
59-
rerank,
60+
/// A reranker: `1_LogitScore` names the yes and no tokens its last row's logits score.
61+
rerank: api.Rerank,
6062
};
6163

6264
const pooling_modes = [_][]const u8{
@@ -66,7 +68,7 @@ const pooling_modes = [_][]const u8{
6668

6769
/// The head from `1_Pooling/config.json` and `modules.json`, or a refusal naming what the folder lacks.
6870
pub fn headOf(a: Allocator, io: std.Io, dir: []const u8, problem: *[]const u8) (Refused || Allocator.Error)!Head {
69-
if (try readJson(a, io, dir, "1_LogitScore/config.json", problem) != null) return .rerank;
71+
if (try readJson(a, io, dir, "1_LogitScore/config.json", problem)) |v| return .{ .rerank = try labelsOf(a, v, problem) };
7072
const pooling = try readJson(a, io, dir, "1_Pooling/config.json", problem) orelse return refuse(
7173
a,
7274
problem,
@@ -92,6 +94,21 @@ pub fn headOf(a: Allocator, io: std.Io, dir: []const u8, problem: *[]const u8) (
9294
return .{ .embedding = .{ .normalize = normalize } };
9395
}
9496

97+
/// The yes and no tokens `1_LogitScore/config.json` names (the vocabulary bound is checked once the config is read).
98+
fn labelsOf(a: Allocator, v: std.json.Value, problem: *[]const u8) (Refused || Allocator.Error)!api.Rerank {
99+
const name = "1_LogitScore/config.json";
100+
if (v != .object) return refuse(a, problem, "{s} is not a JSON object", .{name});
101+
var ids: [2]u32 = undefined;
102+
for ([_][]const u8{ "true_token_id", "false_token_id" }, &ids) |key, *id| {
103+
const x = v.object.get(key) orelse return refuse(a, problem, "{s} has no {s}", .{ name, key });
104+
if (x != .integer or x.integer < 0 or x.integer > std.math.maxInt(u32))
105+
return refuse(a, problem, "{s}: {s} is not a token id", .{ name, key });
106+
id.* = @intCast(x.integer);
107+
}
108+
if (ids[0] == ids[1]) return refuse(a, problem, "{s} names token {d} for both answers", .{ name, ids[0] });
109+
return .{ .yes = ids[0], .no = ids[1] };
110+
}
111+
95112
/// The folder's JSON file `name`, null when it is absent; unreadable or malformed JSON is refused.
96113
fn readJson(a: Allocator, io: std.Io, dir: []const u8, name: []const u8, problem: *[]const u8) (Refused || Allocator.Error)!?std.json.Value {
97114
const path = try std.fs.path.join(a, &.{ dir, name });
@@ -167,19 +184,29 @@ fn openEngine(a: Allocator, gpa: Allocator, io: std.Io, dev: hip.Device, dir: []
167184
.embedding => |h| h.normalize,
168185
.rerank => false,
169186
};
187+
const labels: ?api.Rerank = switch (head) {
188+
.embedding => null,
189+
.rerank => |l| l,
190+
};
191+
if (labels) |l| if (l.yes >= e.m.spec.vocab or l.no >= e.m.spec.vocab)
192+
return refuse(a, problem, "1_LogitScore/config.json: tokens {d} and {d} are not both in this {d}-token vocabulary", .{ l.yes, l.no, e.m.spec.vocab });
170193
const kept = try gpa.dupe(u8, dir);
171194
errdefer gpa.free(kept);
172195
own.* = .{ .gpa = gpa, .e = e, .p = prompt.Prompt.init(gpa, e, normalize), .startup = undefined, .dir = kept };
173-
if (head == .rerank) {
196+
errdefer own.p.deinit();
197+
if (labels) |l| {
174198
own.p.heads = score.Heads.of(&e.m, io, own.dir);
175199
own.p.table.score = prompt.Prompt.scoreLabels;
200+
// both label rows read at load: a bad head fails startup, and the first request reads nothing
201+
for ([_]u32{ l.yes, l.no }) |id| _ = own.p.heads.?.row(gpa, id) catch |err|
202+
return refuse(a, problem, "the native HIP engine cannot read lm_head row {d} ({s})", .{ id, @errorName(err) });
176203
}
177204
const shrunk: []const u8 = if (window < o.window) " (shrunk from the asked window to fit the budget)" else "";
178205
own.startup = try std.fmt.allocPrint(gpa, "HIP {s} device {d}: qwen3 {s}, model {d:.2} GiB; {d}-token passes{s}, {d:.2} GiB scratch, of {d:.1} GiB left after a {d:.1} GiB reserve; {s}", .{
179206
hip.kernels.arch, dev.index, if (head == .rerank) "reranker" else "embedding", gibs(e.weights), window, shrunk, gibs(e.scratchBytes(window) catch 0), gibs(room), gibs(pool.reserve),
180207
switch (head) {
181208
.embedding => |h| if (h.normalize) "vectors unit-normed" else "vectors as pooled",
182-
.rerank => "label scores from lm_head rows on the host",
209+
.rerank => "label scores from lm_head rows read at load, on the host",
183210
},
184211
});
185212
const spec = e.m.spec;
@@ -195,6 +222,7 @@ fn openEngine(a: Allocator, gpa: Allocator, io: std.Io, dev: hip.Device, dir: []
195222
.embeddings = if (head == .rerank) null else .{ .dimensions = @intCast(spec.hidden), .vocabulary = @intCast(spec.vocab), .max_batch_tokens = @intCast(window), .max_inputs = @intCast(engine.max_inputs), .mrl_min = @min(32, @as(u32, @intCast(spec.hidden))) },
196223
.window = window,
197224
.decides = head == .rerank,
225+
.rerank = labels,
198226
};
199227
}
200228

@@ -266,12 +294,27 @@ test "a 1_LogitScore folder declares the reranker head, before any pooling, and
266294
var problem: []const u8 = "";
267295
try tmp.dir.createDirPath(io, "1_LogitScore");
268296
try tmp.dir.writeFile(io, .{ .sub_path = "1_LogitScore/config.json", .data = "{\"true_token_id\": 9693, \"false_token_id\": 2152}" });
269-
try std.testing.expect(try headOf(a, io, dir, &problem) == .rerank);
297+
const labels = (try headOf(a, io, dir, &problem)).rerank;
298+
try std.testing.expectEqual(api.Rerank{ .yes = 9693, .no = 2152 }, labels);
270299
// the reranker's folder also carries no pooling; one that did would still be a reranker by its scores
271300
try tmp.dir.createDirPath(io, "1_Pooling");
272301
try tmp.dir.writeFile(io, .{ .sub_path = "1_Pooling/config.json", .data = "{\"pooling_mode_lasttoken\": true}" });
273302
try std.testing.expect(try headOf(a, io, dir, &problem) == .rerank);
274-
try tmp.dir.writeFile(io, .{ .sub_path = "1_LogitScore/config.json", .data = "{not json" });
275-
try std.testing.expectError(error.Refused, headOf(a, io, dir, &problem));
276-
try std.testing.expect(std.mem.indexOf(u8, problem, "1_LogitScore/config.json") != null);
303+
const bad = [_][]const u8{
304+
"{not json",
305+
"[9693, 2152]",
306+
"{\"false_token_id\": 2152}",
307+
"{\"true_token_id\": 9693}",
308+
"{\"true_token_id\": \"9693\", \"false_token_id\": 2152}",
309+
"{\"true_token_id\": 9693.5, \"false_token_id\": 2152}",
310+
"{\"true_token_id\": -1, \"false_token_id\": 2152}",
311+
"{\"true_token_id\": 4294967296, \"false_token_id\": 2152}",
312+
"{\"true_token_id\": 2152, \"false_token_id\": 2152}",
313+
};
314+
for (bad) |text| {
315+
problem = "";
316+
try tmp.dir.writeFile(io, .{ .sub_path = "1_LogitScore/config.json", .data = text });
317+
try std.testing.expectError(error.Refused, headOf(a, io, dir, &problem));
318+
try std.testing.expect(std.mem.indexOf(u8, problem, "1_LogitScore/config.json") != null);
319+
}
277320
}

‎zig/src/native/hip.zig‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -289,7 +289,7 @@ fn openWith(comptime F: type, a: Allocator, gpa: Allocator, io: std.Io, o: api.O
289289
h.core = lanes.Engine.init(gpa, &h.cfg, loaded.backend, h.clock.clock());
290290
errdefer h.core.deinit();
291291
const what = Serves.of(loaded, r.options.window);
292-
h.host = api.LaneHost.init(gpa, io, &h.core, .{ .lanes = @intCast(loaded.streams), .context_window = @intCast(what.window), .prefill_step = F.prefill_step, .decode_share = o.decode_share, .policy = h.policy_line, .startup = loaded.startup, .structures = what.text_generation, .text_generation = what.text_generation, .embeddings = what.embeddings, .decides = what.decides, .reasoning = reasoning(F) });
292+
h.host = api.LaneHost.init(gpa, io, &h.core, .{ .lanes = @intCast(loaded.streams), .context_window = @intCast(what.window), .prefill_step = F.prefill_step, .decode_share = o.decode_share, .policy = h.policy_line, .startup = loaded.startup, .structures = what.text_generation, .text_generation = what.text_generation, .embeddings = what.embeddings, .decides = what.decides, .rerank = what.rerank, .reasoning = reasoning(F) });
293293
h.host.memory = .{ .read = readMemory };
294294
try h.host.start();
295295
served = true;
@@ -301,6 +301,7 @@ const Serves = struct {
301301
text_generation: bool = true,
302302
embeddings: ?api.EmbeddingInfo = null,
303303
decides: bool = false,
304+
rerank: ?api.Rerank = null,
304305
window: usize,
305306

306307
fn of(loaded: anytype, asked: usize) Serves {
@@ -309,6 +310,7 @@ const Serves = struct {
309310
if (@hasField(L, "text_generation")) s.text_generation = loaded.text_generation;
310311
if (@hasField(L, "embeddings")) s.embeddings = loaded.embeddings;
311312
if (@hasField(L, "decides")) s.decides = loaded.decides;
313+
if (@hasField(L, "rerank")) s.rerank = loaded.rerank;
312314
if (@hasField(L, "window")) if (loaded.window) |w| {
313315
s.window = w;
314316
};
@@ -489,8 +491,10 @@ test "a family's Loaded names what it serves; one without the fields generates t
489491
try std.testing.expect(!e.text_generation and e.embeddings.?.dimensions == 8 and e.window == 2048);
490492
const Unsized = struct { window: ?usize };
491493
try std.testing.expectEqual(@as(usize, 32768), Serves.of(Unsized{ .window = null }, 32768).window);
492-
const Rerank = struct { text_generation: bool, decides: bool, window: ?usize };
493-
const r = Serves.of(Rerank{ .text_generation = false, .decides = true, .window = 32768 }, 40960);
494+
const Rerank = struct { text_generation: bool, decides: bool, rerank: ?api.Rerank, window: ?usize };
495+
const r = Serves.of(Rerank{ .text_generation = false, .decides = true, .rerank = .{ .yes = 9693, .no = 2152 }, .window = 32768 }, 40960);
494496
try std.testing.expect(!r.text_generation and r.decides and r.embeddings == null and r.window == 32768);
497+
try std.testing.expectEqual(@as(u32, 9693), r.rerank.?.yes);
498+
try std.testing.expect(p.rerank == null and e.rerank == null);
495499
try std.testing.expect(!p.decides and !e.decides);
496500
}

‎zig/src/server/rerank.zig‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ fn sendErr(conn: *Conn, cx: *Cx) void {
9191

9292
/// The ranked documents, or the refusal; `gone` says the client left (checked before each document's pass).
9393
pub fn reply(srv: *Server, cx: *Cx, body: Value, gone: anytype) Failure!Value {
94-
const labels = srv.rerank orelse return cx.refuse("this model is not a reranker");
94+
const labels = srv.info.rerank orelse return cx.refuse("this model is not a reranker");
9595
const ask = try parse(cx, body);
9696
// each prompt is built in a scratch arena and dropped: a small body of many documents keeps no ids alive
9797
var scratch = std.heap.ArenaAllocator.init(srv.gpa);

‎zig/src/server/rerank_ids_test.zig‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ const Echo = struct {
1919
return .{ .ctx = e, .vtable = &.{ .info = info, .submit = submit, .cancel = cancel, .status = status, .memory = memory, .score = score } };
2020
}
2121
fn info(_: *anyopaque) api.Info {
22-
return .{ .text_generation = false, .decides = true };
22+
return .{ .text_generation = false, .decides = true, .rerank = .{ .yes = 9693, .no = 2152 } };
2323
}
2424
fn submit(_: *anyopaque, _: api.Id, _: *const api.Request, _: api.Sink) api.SubmitError!void {}
2525
fn cancel(_: *anyopaque, _: api.Id) void {}
@@ -77,8 +77,6 @@ test "rerank: the checkpoint's template and tokenizer give the oracle's ids, the
7777
defer echo.deinit();
7878
const srv = try Server.init(t.allocator, t.io, echo.engine(), text.text(), .{ .served_name = "m", .model_ids = &.{"m"}, .model_dir = dir }, null);
7979
defer srv.deinit();
80-
try t.expectEqual(@as(u32, 9693), srv.rerank.?.yes);
81-
try t.expectEqual(@as(u32, 2152), srv.rerank.?.no);
8280
const ref_text = try std.Io.Dir.cwd().readFileAlloc(t.io, ref_path, a, .limited(64 << 20));
8381
const ref = (try json.parse(a, ref_text)).ok;
8482
var plain: usize = 0;

‎zig/src/server/rerank_labels.zig‎

Lines changed: 0 additions & 81 deletions
This file was deleted.

0 commit comments

Comments
 (0)