@@ -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
4749pub const Refused = error {Refused };
@@ -55,8 +57,8 @@ fn refuse(a: Allocator, problem: *[]const u8, comptime fmt: []const u8, args: an
5557pub 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
6264const 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.
6870pub 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.
96113fn 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}
0 commit comments