diff --git a/NOTICE b/NOTICE index 3246a429..45a1529b 100644 --- a/NOTICE +++ b/NOTICE @@ -168,3 +168,10 @@ https://huggingface.co/nvidia/Nemotron-3.5-Embed-8B-BF16/tree/781e779ee4ca9c2d2a The checkpoint's governing license is OpenMDW-1.1, retained in tests/data/chat/nemotron35/LICENSE. The tokenizer fixture is a subset preserving source token IDs and the BPE entries needed by the test corpus; it is not the complete serving tokenizer. + +tests/data/chat/nemotron35/rerank-template.jinja comes from NVIDIA's +Nemotron-3.5-Rerank-8B-BF16 checkpoint, revision +f88f8d9104726747791283ab156d2fcdb29e90a7: +https://huggingface.co/nvidia/Nemotron-3.5-Rerank-8B-BF16/tree/f88f8d9104726747791283ab156d2fcdb29e90a7 +It is covered by the same retained OpenMDW-1.1 license. +Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. diff --git a/README.md b/README.md index 8990cedf..41e637f2 100644 --- a/README.md +++ b/README.md @@ -66,6 +66,7 @@ To support the development of radiance: [Patreon](https://patreon.com/StillDeadC | nomic-embed-text-v2-moe bf16: text embeddings, one card | `nomic-embed-v2-moe-bf16.rad` (959 MB) | [convert](#convert-a-checkpoint) | - | | Nemotron 3.5 Embed 1B BF16: text and image embeddings, one card | the checkpoint as it ships | [NVIDIA checkpoint](https://huggingface.co/nvidia/Nemotron-3.5-Embed-1B-BF16) | — | | Nemotron 3.5 Embed 8B BF16: text and image embeddings, one card | the checkpoint as it ships | [NVIDIA checkpoint](https://huggingface.co/nvidia/Nemotron-3.5-Embed-8B-BF16) | — | +| Nemotron 3.5 Rerank 8B BF16: text/image document relevance, one card | the checkpoint as it ships | [NVIDIA checkpoint](https://huggingface.co/nvidia/Nemotron-3.5-Rerank-8B-BF16) | — | | Anima Aesthetic FP8: anime and illustration, text to image, one card (Base and Turbo convert the same way) | `anima-aesthetic-fp8.rad` (3.0 GiB) | [convert](#convert-a-checkpoint) | `anima.yaml` | | Qwen3-ASR 1.7B bf16: speech to text, `/v1/audio/transcriptions` and live over `/v1/realtime`, 30 languages, one card | the checkpoint as it ships (4.1 GiB) | [Qwen/Qwen3-ASR-1.7B-hf](https://huggingface.co/Qwen/Qwen3-ASR-1.7B-hf) | — | diff --git a/arch/nemotron35_embed/nemotron35_embed.cpp b/arch/nemotron35_embed/nemotron35_embed.cpp index 70e55b36..018a4550 100644 --- a/arch/nemotron35_embed/nemotron35_embed.cpp +++ b/arch/nemotron35_embed/nemotron35_embed.cpp @@ -27,11 +27,12 @@ struct Layer { add_ff = 0; }; struct Model { + bool rerank = false; Geom g{}; - Names nm{""}; + Names nm{""}, source{""}; rad_buf x = 0, h = 0, qkv = 0, attn = 0, o = 0, gu = 0, ff = 0, mean = 0, pooled = 0; - rad_weight tok = 0, norm = 0; - rad_op embed = 0, inject = 0, final_norm = 0, final_gain = 0, pool = 0, cast = 0; + rad_weight tok = 0, norm = 0, score = 0; + rad_op embed = 0, inject = 0, final_norm = 0, final_gain = 0, pool = 0, cast = 0, head = 0; std::vector layers; Pixtral vision; }; @@ -117,10 +118,21 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c model = Model{}; Model& m = model; + m.rerank = + !std::strcmp(rad_meta_gets(meta, "architectures", ""), "Mistral3ForSequenceClassification"); + const char* architecture = rad_meta_gets(meta, "architectures", ""); + if (*architecture && !m.rerank && std::strcmp(architecture, "Mistral3Model")) + return RAD_E_UNSUPPORTED; + if (m.rerank && (std::strcmp(rad_meta_gets(meta, "pooling", ""), "avg") || + std::strcmp(rad_meta_gets(meta, "text_config.pooling", ""), "avg"))) + return RAD_E_UNSUPPORTED; m.nm = Names(ctx->scope); + // The classifier wrapper prefixes the backbone with model.; its score head stays at root. + m.source = Names(m.rerank ? "model" : ""); RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16)); Geom& g = m.g; Names& nm = m.nm; + Names& source = m.source; if (g.n_head_kv <= 0 || g.n_head % g.n_head_kv || g.head_dim % 2) return RAD_E_INVAL; RAD_ARCH_TRY(read_rope(g, meta)); const int64_t T = g.max_tok, E = g.n_embd, Q = g.q_dim(), K = g.kv_dim(), F = g.n_ff; @@ -132,7 +144,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c m.gu = decl_b(b, nm.f("gate_up"), RAD_BF16, {T, 2 * F}); m.ff = decl_b(b, nm.f("ff"), RAD_BF16, {T, F}); m.mean = decl_b(b, nm.f("mean"), RAD_BF16, {g.max_seqs, E}); - m.pooled = decl_b(b, nm.f("pooled"), RAD_F32, {g.max_seqs, E}, RAD_BUF_PERSIST); + m.pooled = decl_b(b, nm.f("pooled"), RAD_F32, {g.max_seqs, m.rerank ? 1 : E}, RAD_BUF_PERSIST); RAD_ARCH_TRY(rad_declare_pooled(b, m.pooled)); auto weight = [&](const char* dest, const char* src, std::initializer_list shape, RadWeightGroup group) { @@ -163,11 +175,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c RAD_NOWEIGHTS); }; RAD_ARCH_TRY( - map_copy(b, nm.f("token_embd.weight"), nm.ckpt("language_model.embed_tokens.weight"))); + map_copy(b, nm.f("token_embd.weight"), source.f("language_model.embed_tokens.weight"))); m.tok = decl_w(b, nm.f("token_embd.weight"), RAD_BF16, {g.n_vocab, E}, RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model()); - m.norm = - weight(nm.f("output_norm.weight"), nm.ckpt("language_model.norm.weight"), {E}, grp_model()); + m.norm = weight(nm.f("output_norm.weight"), source.f("language_model.norm.weight"), {E}, + grp_model()); m.embed = rw(b, RAD_OP(b, "embed_lookup", RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n_embd", E), @@ -181,29 +193,29 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c const auto n = (long long)i; l.norm = weight(nm.f("blk.%lld.attn_norm.weight", n), - nm.ckpt("language_model.layers.%lld.input_layernorm.weight", n), {E}, group); - l.ff_norm = weight(nm.f("blk.%lld.ffn_norm.weight", n), - nm.ckpt("language_model.layers.%lld.post_attention_layernorm.weight", n), - {E}, group); + source.f("language_model.layers.%lld.input_layernorm.weight", n), {E}, group); + l.ff_norm = weight( + nm.f("blk.%lld.ffn_norm.weight", n), + source.f("language_model.layers.%lld.post_attention_layernorm.weight", n), {E}, group); RAD_ARCH_TRY(map_concat(b, nm.f("blk.%lld.qkv.weight", n), - {nm.ckpt("language_model.layers.%lld.self_attn.q_proj.weight", n), - nm.ckpt("language_model.layers.%lld.self_attn.k_proj.weight", n), - nm.ckpt("language_model.layers.%lld.self_attn.v_proj.weight", n)}, + {source.f("language_model.layers.%lld.self_attn.q_proj.weight", n), + source.f("language_model.layers.%lld.self_attn.k_proj.weight", n), + source.f("language_model.layers.%lld.self_attn.v_proj.weight", n)}, 0)); l.qkv = decl_w(b, nm.f("blk.%lld.qkv.weight", n), RAD_BF16, {Q + 2 * K, E}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, group); - l.out = - weight(nm.f("blk.%lld.attn_o.weight", n), - nm.ckpt("language_model.layers.%lld.self_attn.o_proj.weight", n), {E, Q}, group); + l.out = weight(nm.f("blk.%lld.attn_o.weight", n), + source.f("language_model.layers.%lld.self_attn.o_proj.weight", n), {E, Q}, + group); RAD_ARCH_TRY(map_concat(b, nm.f("blk.%lld.gate_up.weight", n), - {nm.ckpt("language_model.layers.%lld.mlp.gate_proj.weight", n), - nm.ckpt("language_model.layers.%lld.mlp.up_proj.weight", n)}, + {source.f("language_model.layers.%lld.mlp.gate_proj.weight", n), + source.f("language_model.layers.%lld.mlp.up_proj.weight", n)}, 0)); l.gate_up = decl_w(b, nm.f("blk.%lld.gate_up.weight", n), RAD_BF16, {2 * F, E}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, group); l.down = weight(nm.f("blk.%lld.ffn_down.weight", n), - nm.ckpt("language_model.layers.%lld.mlp.down_proj.weight", n), {E, F}, group); + source.f("language_model.layers.%lld.mlp.down_proj.weight", n), {E, F}, group); l.in_norm = rw(b, rms(), {m.x}, {m.h}); l.in_gain = rw(b, gain(l.norm), {m.h}, {m.h}); l.project = rw(b, gemm(Q + 2 * K, E, l.qkv), {m.h}, {m.qkv}); @@ -254,16 +266,27 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c m.final_norm = rw(b, rms(), {m.x}, {m.h}); m.final_gain = rw(b, gain(m.norm), {m.h}, {m.h}); m.pool = rw(b, - RAD_OP(b, "seg_mean", + RAD_OP(b, m.rerank ? "seg_mean_bf16_sum" : "seg_mean", RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E), RAD_STR("dtype", "bf16")), RAD_NOWEIGHTS), {m.h}, {m.mean}); - m.cast = rw(b, - RAD_OP(b, "cast", - RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("n", E), - RAD_STR("from", "bf16"), RAD_STR("to", "f32")), - RAD_NOWEIGHTS), - {m.mean}, {m.pooled}); + if (m.rerank) { + m.score = weight(nm.f("score.weight"), nm.ckpt("language_model.score.weight"), {1, E}, + grp_model()); + m.head = rw(b, + RAD_OP(b, "logits_gemm", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("n_vocab", 1), + RAD_INT("n_embd", E), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.score)), + {m.mean}, {m.pooled}); + } else { + m.cast = rw(b, + RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("n", E), + RAD_STR("from", "bf16"), RAD_STR("to", "f32")), + RAD_NOWEIGHTS), + {m.mean}, {m.pooled}); + } /* Recipes may quantise weights without changing the architecture descriptor. Do not read an * INT8 plane with a BF16-only graph, even when a container still advertises quant="". */ const RadEncoding plain = rad_enc_plain(RAD_BF16); @@ -281,10 +304,12 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c }; RAD_ARCH_TRY(bf16_only(nm.f("token_embd.weight"))); RAD_ARCH_TRY(bf16_only(nm.f("output_norm.weight"))); + if (m.rerank) + RAD_ARCH_TRY(bf16_only(nm.f("score.weight"))); for (int64_t i = 0; i < g.n_layer; ++i) for (const char* suffix : {"attn_norm", "ffn_norm", "qkv", "attn_o", "gate_up", "ffn_down"}) RAD_ARCH_TRY(bf16_only(nm.f("blk.%lld.%s.weight", (long long)i, suffix))); - RAD_ARCH_TRY(m.vision.declare(b, meta, ctx, nm, E, (int)g.n_layer)); + RAD_ARCH_TRY(m.vision.declare(b, meta, ctx, nm, source, E, (int)g.n_layer)); if (m.vision.on) m.inject = rw(b, @@ -292,10 +317,16 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E), RAD_STR("dtype", "bf16")), RAD_NOWEIGHTS), {m.x}, {m.x}); - rad_note( - b, - "Nemotron-3.5-Embed: BF16 bidirectional embeddings, TP1; mean-pooled to %lld; Pixtral encoder %s", - (long long)E, m.vision.on ? "on" : "off"); + if (m.rerank) + rad_note(b, + "Nemotron-3.5-Rerank: BF16 bidirectional query/document scoring, TP1; " + "BF16 sum/division, FP32 score; Pixtral encoder %s", + m.vision.on ? "on" : "off"); + else + rad_note( + b, + "Nemotron-3.5-Embed: BF16 bidirectional embeddings, TP1; mean-pooled to %lld; Pixtral encoder %s", + (long long)E, m.vision.on ? "on" : "off"); return RAD_OK; } @@ -360,12 +391,15 @@ static void step(RadCtx* c, const RadBatch* batch) { RAD_ISSUE(c, m.final_norm, brows(m.x, T), brows(m.h, T)); RAD_ISSUE(c, m.final_gain, brows(m.h, T), RAD_W(m.norm), brows(m.h, T)); RAD_ISSUE(c, m.pool, brows(m.h, T), cu, brows(m.mean, S)); - RAD_ISSUE_N(c, m.cast, S, brows(m.mean, S), brows(m.pooled, S)); + if (m.rerank) + RAD_ISSUE_N(c, m.head, S, brows(m.mean, S), RAD_W(m.score), brows(m.pooled, S)); + else + RAD_ISSUE_N(c, m.cast, S, brows(m.mean, S), brows(m.pooled, S)); } } // namespace nemotron35_embed #ifndef RAD_ARCH_NO_EXPORTS -RAD_ARCH_PLUGIN(nemotron35_embed, "mistral3", "", "0.4.0", - "Nemotron-3.5-Embed: experimental BF16 text/image embeddings, TP1") +RAD_ARCH_PLUGIN(nemotron35_embed, "mistral3", "", "0.5.0", + "Nemotron-3.5-Embed/Rerank: experimental BF16 text/image retrieval, TP1") RAD_ARCH_PROBE(nemotron35_embed) #endif diff --git a/arch/nemotron35_embed/pixtral.h b/arch/nemotron35_embed/pixtral.h index c28e3cca..27933878 100644 --- a/arch/nemotron35_embed/pixtral.h +++ b/arch/nemotron35_embed/pixtral.h @@ -29,7 +29,7 @@ struct Pixtral { std::vector layers; int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx, Names& nm, - int64_t output_width, int first_group) { + Names& source, int64_t output_width, int first_group) { on = false; if (ctx->max_enc_patches <= 0) return RAD_OK; auto vi = [&](const char* k) { @@ -117,44 +117,44 @@ struct Pixtral { RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width), RAD_STR("dtype", "bf16")), RAD_NOWEIGHTS); }; - patch = weight(nm.f("v.patch.weight"), nm.ckpt("vision_tower.patch_conv.weight"), + patch = weight(nm.f("v.patch.weight"), source.f("vision_tower.patch_conv.weight"), {width, patch_dim}, grp_model()); stem = rw(b, gemm(P, width, patch_dim, patch), {}, {x}); - norm(pre, nm.f("v.pre.weight"), nm.ckpt("vision_tower.ln_pre.weight"), grp_model(), 1e-5, x, - x); + norm(pre, nm.f("v.pre.weight"), source.f("vision_tower.ln_pre.weight"), grp_model(), 1e-5, + x, x); layers.resize((size_t)depth); for (int64_t i = 0; i < depth; ++i) { auto& l = layers[(size_t)i]; const long long li = i; const auto group = grp_layer(first_group + (int)i); norm(l.n1, nm.f("v.blk.%lld.n1.weight", li), - nm.ckpt("vision_tower.transformer.layers.%lld.attention_norm.weight", li), group, + source.f("vision_tower.transformer.layers.%lld.attention_norm.weight", li), group, 1e-5, x, h); norm(l.n2, nm.f("v.blk.%lld.n2.weight", li), - nm.ckpt("vision_tower.transformer.layers.%lld.ffn_norm.weight", li), group, 1e-5, + source.f("vision_tower.transformer.layers.%lld.ffn_norm.weight", li), group, 1e-5, x, h); RAD_ARCH_TRY(map_concat( b, nm.f("v.blk.%lld.qkv.weight", li), - {nm.ckpt("vision_tower.transformer.layers.%lld.attention.q_proj.weight", li), - nm.ckpt("vision_tower.transformer.layers.%lld.attention.k_proj.weight", li), - nm.ckpt("vision_tower.transformer.layers.%lld.attention.v_proj.weight", li)}, + {source.f("vision_tower.transformer.layers.%lld.attention.q_proj.weight", li), + source.f("vision_tower.transformer.layers.%lld.attention.k_proj.weight", li), + source.f("vision_tower.transformer.layers.%lld.attention.v_proj.weight", li)}, 0)); l.qkv = decl_w(b, nm.f("v.blk.%lld.qkv.weight", li), RAD_BF16, {3 * width, width}, RAD_ACCESS_PER_REQUEST, RAD_SHARD_NONE, group); l.out = weight(nm.f("v.blk.%lld.out.weight", li), - nm.ckpt("vision_tower.transformer.layers.%lld.attention.o_proj.weight", li), + source.f("vision_tower.transformer.layers.%lld.attention.o_proj.weight", li), {width, width}, group); RAD_ARCH_TRY(map_concat( b, nm.f("v.blk.%lld.gate_up.weight", li), - {nm.ckpt("vision_tower.transformer.layers.%lld.feed_forward.gate_proj.weight", li), - nm.ckpt("vision_tower.transformer.layers.%lld.feed_forward.up_proj.weight", li)}, + {source.f("vision_tower.transformer.layers.%lld.feed_forward.gate_proj.weight", li), + source.f("vision_tower.transformer.layers.%lld.feed_forward.up_proj.weight", li)}, 0)); l.gu = decl_w(b, nm.f("v.blk.%lld.gate_up.weight", li), RAD_BF16, {2 * ff, width}, RAD_ACCESS_PER_REQUEST, RAD_SHARD_NONE, group); l.down = weight( nm.f("v.blk.%lld.down.weight", li), - nm.ckpt("vision_tower.transformer.layers.%lld.feed_forward.down_proj.weight", li), + source.f("vision_tower.transformer.layers.%lld.feed_forward.down_proj.weight", li), {width, ff}, group); l.project = rw(b, gemm(P, 3 * width, width, l.qkv), {h}, {qkv}); l.rope = rw(b, @@ -191,15 +191,17 @@ struct Pixtral { l.ffn = rw(b, gemm(P, width, ff, l.down), {ffn}, {o}); l.add2 = rw(b, add(), {x, o}, {x}); } - norm(post, nm.f("v.post.weight"), nm.ckpt("multi_modal_projector.norm.weight"), grp_model(), - eps, x, h); + norm(post, nm.f("v.post.weight"), source.f("multi_modal_projector.norm.weight"), + grp_model(), eps, x, h); merger = weight(nm.f("v.merger.weight"), - nm.ckpt("multi_modal_projector.patch_merger.merging_layer.weight"), + source.f("multi_modal_projector.patch_merger.merging_layer.weight"), {width, mm * width}, grp_model()); - linear1 = weight(nm.f("v.linear1.weight"), nm.ckpt("multi_modal_projector.linear_1.weight"), - {embd, width}, grp_model()); - linear2 = weight(nm.f("v.linear2.weight"), nm.ckpt("multi_modal_projector.linear_2.weight"), - {embd, embd}, grp_model()); + linear1 = + weight(nm.f("v.linear1.weight"), source.f("multi_modal_projector.linear_1.weight"), + {embd, width}, grp_model()); + linear2 = + weight(nm.f("v.linear2.weight"), source.f("multi_modal_projector.linear_2.weight"), + {embd, embd}, grp_model()); pack = rw(b, RAD_OP(b, "pixtral_merge", RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width), diff --git a/core/server/admin.cpp b/core/server/admin.cpp index 8c607716..dc8a8be5 100644 --- a/core/server/admin.cpp +++ b/core/server/admin.cpp @@ -6,8 +6,8 @@ * None of these touch the step path (no admission, no Sink, no cancellation); each is answered on * the HTTP thread before it returns, so they are kept out of server.cpp. * - * Deliberately absent, answering 404: vLLM's /pooling, /classify, /score and /rerank (no - * classifier or cross-encoder head), /sleep, /wake_up and /is_sleeping (no sleep mode; weights + * Deliberately absent, answering 404: vLLM's /pooling, /classify and /score, + * /sleep, /wake_up and /is_sleeping (no sleep mode; weights * are placed once, spec §5), /invocations (a SageMaker envelope), stored Responses-API responses * (would need a conversation store), and llama-server's /slots and /lora-adapters (a runtime LoRA * adapter is chosen per request by `model`; vLLM's load and unload routes are in server.cpp). @@ -383,14 +383,16 @@ HttpResponse Server::handle_tokenizer_info(const HttpRequest& req) { /* ================================================================== capabilities */ json Server::capabilities() const { json caps; - caps["chat"] = deps_.chat != nullptr; - caps["tools"] = deps_.chat && deps_.chat->supports_tools(); - caps["reasoning"] = deps_.chat && deps_.chat->supports_reasoning(); + const bool rerank = is_reranker(deps_.embed); + caps["chat"] = !rerank && deps_.chat != nullptr; + caps["tools"] = !rerank && deps_.chat && deps_.chat->supports_tools(); + caps["reasoning"] = !rerank && deps_.chat && deps_.chat->supports_reasoning(); /* An image model reads pictures only for edits and writes no text a grammar could constrain, * whatever its conditioning network's processor would take. */ const bool img = opt_.image_model || opt_.video_model; - caps["grammar"] = !img && deps_.grammar != nullptr; - caps["embedding"] = deps_.embed != nullptr; + caps["grammar"] = !img && !rerank && deps_.grammar != nullptr; + caps["embedding"] = deps_.embed != nullptr && !rerank; + if (rerank) caps["rerank"] = true; caps["image"] = deps_.mm && deps_.mm->accepts(MediaKind::Image); caps["video"] = !img && deps_.mm && deps_.mm->accepts(MediaKind::Video); caps["audio"] = !img && deps_.mm && deps_.mm->accepts(MediaKind::Audio); diff --git a/core/server/nemotron35.cpp b/core/server/nemotron35.cpp index 31770c79..81dd5d56 100644 --- a/core/server/nemotron35.cpp +++ b/core/server/nemotron35.cpp @@ -1,9 +1,10 @@ #include "server/nemotron35.h" #include "rad_plugin.h" +#include "llama/src/unicode.h" #include namespace rad::server { -bool nemotron35_retrieval_meta(const RadModelMeta* meta) { +static bool nemotron35_meta(const RadModelMeta* meta) { if (!meta) return false; const auto is = [&](const char* key, const char* value) { return !std::strcmp(rad_meta_gets(meta, key, ""), value); @@ -14,6 +15,92 @@ bool nemotron35_retrieval_meta(const RadModelMeta* meta) { noncausal("text_config.is_causal"); } +bool nemotron35_rerank_meta(const RadModelMeta* meta) { + return nemotron35_meta(meta) && !std::strcmp(rad_meta_gets(meta, "architectures", ""), + "Mistral3ForSequenceClassification"); +} + +bool nemotron35_retrieval_meta(const RadModelMeta* meta) { + return nemotron35_meta(meta) && !nemotron35_rerank_meta(meta); +} + +int nemotron35_rerank_format(const json& messages, std::vector* pieces, + std::string* why) { + if (!pieces) + return RAD_E_INVAL; + pieces->clear(); + auto no = [&](const char* message) { + if (why) + *why = message; + pieces->clear(); + return RAD_E_INVAL; + }; + if (!messages.is_array() || messages.size() != 2 || !messages[0].is_object() || + !messages[1].is_object() || messages[0].value("role", json()) != "query" || + messages[1].value("role", json()) != "document" || !messages[0].contains("content") || + !messages[1].contains("content")) + return no("reranking requires one text query followed by one document"); + std::string texts[2]; + json image; + for (int i = 0; i < 2; ++i) { + const auto& content = messages[i]["content"]; + if (content.is_string()) + texts[i] = content.get(); + else if (content.is_array()) { + bool first = true; + for (const auto& block : content) { + if (!block.is_object()) + return no("content must contain typed text/image blocks"); + const json type = block.value("type", json()); + if (type == "text") { + if (!block.contains("text") || !block["text"].is_string()) + return no("text blocks require string text"); + if (!first) + texts[i] += "\n\n"; + texts[i] += block["text"].get(); + first = false; + } else if (i == 1 && (type == "image" || type == "image_url")) { + if (!image.is_null()) + return no("at most one image per document is supported"); + image = block; + } else + return no("queries must be text; documents support text and one image"); + } + } else + return no("content must be a string or a list of text/image blocks"); + } + const auto escape = [](const std::string& s) { + std::string out; + for (char c : s) { + out += c; + if (c == '[' || c == '<') + out += "\xe2\x80\x8c"; + } + return out; + }; + std::string rendered = "query: " + escape(texts[0]) + "\n\npassage: " + escape(texts[1]); + if (!image.is_null()) { + /* Jinja's Python trim includes Unicode whitespace. The fixed image/query prefix has + * no leading whitespace; only the rendered text's trailing edge can be trimmed. */ + auto cps = unicode_cpts_from_utf8(rendered); + while (!cps.empty() && (unicode_cpt_flags_from_cpt(cps.back()).is_whitespace || + (cps.back() >= 0x1c && cps.back() <= 0x1f))) + cps.pop_back(); + rendered.clear(); + for (auto cp : cps) + rendered += unicode_cpt_to_utf8(cp); + Nemotron35Piece p; + p.image = true; + p.content = std::move(image); + pieces->push_back(std::move(p)); + rendered.insert(0, " "); + } + Nemotron35Piece p; + p.text = std::move(rendered); + pieces->push_back(std::move(p)); + return RAD_OK; +} + int nemotron35_format(const json& messages, std::vector* pieces, std::string* why) { if (!pieces) return RAD_E_INVAL; diff --git a/core/server/nemotron35.h b/core/server/nemotron35.h index 7c82e887..c3afeb36 100644 --- a/core/server/nemotron35.h +++ b/core/server/nemotron35.h @@ -14,5 +14,8 @@ struct Nemotron35Piece { }; bool nemotron35_retrieval_meta(const RadModelMeta* meta); +bool nemotron35_rerank_meta(const RadModelMeta* meta); int nemotron35_format(const json& messages, std::vector* pieces, std::string* why); +int nemotron35_rerank_format(const json& messages, std::vector* pieces, + std::string* why); } // namespace rad::server diff --git a/core/server/oai.cpp b/core/server/oai.cpp index 8c74f9ab..061fbfd9 100644 --- a/core/server/oai.cpp +++ b/core/server/oai.cpp @@ -10,6 +10,7 @@ #include #include #include +#include #include #include #include @@ -2392,10 +2393,12 @@ static int embedding_input(const std::string& text, * boundaries, and no implicit BOS/EOS is added to the retrieval template's output. */ static int nemotron35_embedding_input(const json& messages, const OaiDeps& d, const OaiLimits& lim, int32_t image_tokens, const char* field, OaiRequest* out, - ApiError* err) { + ApiError* err, bool rerank = false) { std::vector pieces; std::string why; - if (nemotron35_format(messages, &pieces, &why) < 0) { + const int formatted = rerank ? nemotron35_rerank_format(messages, &pieces, &why) + : nemotron35_format(messages, &pieces, &why); + if (formatted < 0) { *err = err_bad(field, why); return RAD_E_INVAL; } @@ -2416,8 +2419,9 @@ static int nemotron35_embedding_input(const json& messages, const OaiDeps& d, co std::string type = piece.content["type"].get(); if (type == "image") type = "image_url"; // template spelling; transport still requires a data URL - const char* part_field = - !std::strcmp(field, "messages") ? "messages[].content[]" : "input[]"; + const char* part_field = rerank ? "documents[].content[]" + : !std::strcmp(field, "messages") ? "messages[].content[]" + : "input[]"; const int rc = read_media_part(piece.content, type, part_field, d, lim, &kind, &bytes, err); if (rc < 0) return rc; if (rc == 0 || kind != MediaKind::Image) { @@ -2451,7 +2455,8 @@ static int nemotron35_embedding_input(const json& messages, const OaiDeps& d, co } int check_embedding_template(const IEmbedder* embed, bool overridden, std::string* why) { - if (overridden && embed && nemotron35_retrieval_meta(embed->metadata())) { + if (overridden && embed && + (nemotron35_retrieval_meta(embed->metadata()) || is_reranker(embed))) { if (why) *why = "Nemotron 3.5 uses its reference retrieval formatter; " "--override-chat-template is not supported for this model. " @@ -2463,6 +2468,10 @@ int check_embedding_template(const IEmbedder* embed, bool overridden, std::strin int parse_embeddings_request(const std::string& body, const OaiDeps& d, const OaiLimits& lim, OaiRequest* out, ApiError* err) { + if (is_reranker(d.embed)) { + *err = err_unsupported("model", "this is a reranker; use /rerank with query and documents"); + return RAD_E_UNSUPPORTED; + } json b; RAD_TRY(parse_request_object(body, lim, &b, err)); RAD_TRY(vet_keys(b, Endpoint::Embedding, err)); @@ -2701,6 +2710,89 @@ int parse_embeddings_request(const std::string& body, const OaiDeps& d, const Oa return finish_inputs(); } +bool is_reranker(const IEmbedder* embed) { + return embed && nemotron35_rerank_meta(embed->metadata()); +} + +int parse_rerank_request(const std::string& body, const OaiDeps& d, const OaiLimits& lim, + OaiRequest* out, ApiError* err) { + if (!is_reranker(d.embed) || d.embed->dim() != 1) { + *err = err_unsupported("model", "/rerank requires a reranking model"); + return RAD_E_UNSUPPORTED; + } + json b; + RAD_TRY(parse_request_object(body, lim, &b, err)); + for (auto it = b.begin(); it != b.end(); ++it) + if (it.key() != "model" && it.key() != "query" && it.key() != "documents" && + it.key() != "top_n" && it.key() != "return_documents" && it.key() != "use_activation") { + *err = err_unsupported(it.key(), "this reranker serves query, documents and top_n " + "without truncation, instructions or activation"); + return RAD_E_UNSUPPORTED; + } + out->endpoint = Endpoint::Rerank; + out->id = random_id("rerank-"); + out->created = unix_now(); + out->model = lim.model_id; + bool activation = false; + if (!get_str(b, "model", &out->model, err) || !get_int(b, "top_n", &out->top_n, err) || + !get_bool(b, "return_documents", &out->return_documents, err) || + !get_bool(b, "use_activation", &activation, err)) + return RAD_E_INVAL; + if (out->model.empty()) + out->model = lim.model_id; + if (activation) { + *err = err_unsupported("use_activation", "this model returns raw relevance logits"); + return RAD_E_UNSUPPORTED; + } + if (out->top_n < 0) { + *err = err_bad("top_n", "must be zero (all documents) or positive"); + return RAD_E_INVAL; + } + if (!b.contains("query") || !b["query"].is_string()) { + *err = err_bad("query", "expected a text string"); + return RAD_E_INVAL; + } + if (!b.contains("documents") || !b["documents"].is_array() || b["documents"].empty() || + b["documents"].size() > (size_t)INT_MAX) { + *err = err_bad("documents", "expected a nonempty array of strings or content objects"); + return RAD_E_INVAL; + } + int64_t cap = lim.max_ctx > 0 ? std::min(lim.max_ctx, 32768) : 32768; + if (d.embed->max_input() > 0) + cap = std::min(cap, d.embed->max_input()); + for (const auto& doc : b["documents"]) { + json content, echo; + if (doc.is_string()) { + content = doc; + echo = {{"text", doc}}; + } else if (doc.is_object() && doc.size() == 1 && doc.contains("content") && + doc["content"].is_array()) { + content = doc["content"]; + echo = {{"multi_modal", content}}; + } else { + *err = + err_bad("documents", "each document must be a string or {content: [typed blocks]}"); + return RAD_E_INVAL; + } + const json messages = json::array({{{"role", "query"}, {"content", b["query"]}}, + {{"role", "document"}, {"content", content}}}); + RAD_TRY(nemotron35_embedding_input(messages, d, lim, 0, "documents", out, err, true)); + const int64_t n = (int64_t)out->prompts.back().tokens.size(); + if (n <= 0 || n > cap) { + *err = err_bad("documents", + "query/document pair " + std::to_string(out->prompts.size() - 1) + + " has " + std::to_string(n) + + " tokens; this deployment accepts 1 through " + std::to_string(cap)); + err->code = "context_length_exceeded"; + err->n_prompt_tokens = n; + err->n_ctx = cap; + return RAD_E_INVAL; + } + out->rerank_documents.push_back(std::move(echo)); + } + return RAD_OK; +} + /* ================================================================== responses */ static json tool_calls_json(const std::vector& tcs) { @@ -2924,6 +3016,29 @@ std::string embeddings_body(const OaiRequest& r, const std::vector>& scores, + const UsageOut& u) { + std::vector order(scores.size()); + for (size_t i = 0; i < order.size(); ++i) + order[i] = i; + std::stable_sort(order.begin(), order.end(), + [&](size_t a, size_t b) { return scores[a][0] > scores[b][0]; }); + if (r.top_n > 0 && (uint64_t)r.top_n < order.size()) + order.resize((size_t)r.top_n); + json results = json::array(); + for (size_t i : order) { + json row = {{"index", i}, {"relevance_score", scores[i][0]}}; + if (r.return_documents) + row["document"] = r.rerank_documents[i]; + results.push_back(std::move(row)); + } + return json({{"id", r.id}, + {"model", r.model}, + {"results", std::move(results)}, + {"usage", {{"prompt_tokens", u.prompt}, {"total_tokens", u.prompt}}}}) + .dump(); +} + static json model_card(const ModelCard& c) { json m; m["id"] = c.id; diff --git a/core/server/oai.h b/core/server/oai.h index ae57281f..8ceacf2e 100644 --- a/core/server/oai.h +++ b/core/server/oai.h @@ -59,7 +59,7 @@ std::string json_dump(const json& j); /* ================================================================== a parsed request */ -enum class Endpoint { Chat, Completion, Embedding }; +enum class Endpoint { Chat, Completion, Embedding, Rerank }; /* The API a chat request came in through, which decides the shape of its answer. Every shape is * parsed into the same chat request (Anthropic's is translated first, anthropic_to_chat) and @@ -160,6 +160,10 @@ struct OaiRequest { int64_t dimensions = 0; /* /v1/embeddings: a soft-token budget for the request's images, 0 the server's. */ int32_t image_tokens = 0; + /* /rerank: original document order is retained through scheduler batching. */ + std::vector rerank_documents; + int64_t top_n = 0; + bool return_documents = true; /* `images_config`: which of the checkpoint's picture modes a request's pictures get, and the * sizes it states (Unlimited-OCR's gundam and base modes). 0 keeps the processor's choice @@ -308,6 +312,9 @@ int check_embedding_template(const IEmbedder* embed, bool overridden, std::strin /* Embeddings: fills `out->prompts` with one entry per input. */ int parse_embeddings_request(const std::string& body, const OaiDeps& d, const OaiLimits& lim, OaiRequest* out, ApiError* err); +bool is_reranker(const IEmbedder* embed); +int parse_rerank_request(const std::string& body, const OaiDeps& d, const OaiLimits& lim, + OaiRequest* out, ApiError* err); /* ================================================================== responses */ @@ -392,6 +399,8 @@ std::string text_completion_body(const OaiRequest& r, const std::vector>& vecs, const UsageOut& u); +std::string rerank_body(const OaiRequest& r, const std::vector>& scores, + const UsageOut& u); /* One model entry: what /v1/models lists and /v1/models/:id returns. */ struct ModelCard { std::string id; diff --git a/core/server/server.cpp b/core/server/server.cpp index 2dbab68c..5d8b8171 100644 --- a/core/server/server.cpp +++ b/core/server/server.cpp @@ -92,6 +92,8 @@ void Server::register_routes() { router_.post("/v1/chat/completions", [this](const HttpRequest& q) { return handle_chat(q); }); router_.post("/v1/completions", [this](const HttpRequest& q) { return handle_completion(q); }); router_.post("/v1/embeddings", [this](const HttpRequest& q) { return handle_embeddings(q); }); + router_.post("/rerank", [this](const HttpRequest& q) { return handle_rerank(q); }); + router_.post("/v1/rerank", [this](const HttpRequest& q) { return handle_rerank(q); }); router_.post("/v1/images/generations", [this](const HttpRequest& q) { return handle_images(q, false); }); router_.post("/v1/images/edits", [this](const HttpRequest& q) { return handle_images(q, true); }); router_.post("/v1/systemone", [this](const HttpRequest& q) { return handle_systemone(q); }); @@ -420,7 +422,9 @@ HttpResponse Server::error_response(const ApiError& e, const std::string& peer, void Server::log_admitted(const OaiRequest& r) const { int64_t n_prompt = 0; for (const auto& p : r.prompts) n_prompt += (int64_t)p.tokens.size(); - const char* kind = r.endpoint == Endpoint::Chat ? "chat" : "completion"; + const char* kind = r.endpoint == Endpoint::Chat ? "chat" + : r.endpoint == Endpoint::Rerank ? "rerank" + : "completion"; if (r.endpoint == Endpoint::Chat) RAD_INFO("req %s %s%s%s model=%s msgs=%d tools=%d prompt=%lld tok n=%d max_tokens=%lld", r.id.c_str(), kind, r.stream ? " stream" : "", from_peer(r.peer).c_str(), @@ -1346,6 +1350,7 @@ HttpResponse Server::streaming_completion(const HttpRequest& req, OaiRequest& r) std::optional Server::refuse_text(const std::string& peer, ApiShape shape) { const char* why = !deps_.sched || !deps_.tok ? "the server has no engine attached" + : is_reranker(deps_.embed) ? "this is a reranker: it serves /rerank and generates no text" : opt_.embedding_model ? "this is an embedding model: it serves /v1/embeddings and " "generates no text" : opt_.image_model ? "this is an image model: it serves /v1/images/generations " @@ -1616,10 +1621,20 @@ HttpResponse Server::handle_completion(const HttpRequest& req) { return serve(req, r); } -HttpResponse Server::handle_embeddings(const HttpRequest& req) { +HttpResponse Server::handle_embeddings(const HttpRequest& req) { return serve_pooled(req, false); } + +HttpResponse Server::handle_rerank(const HttpRequest& req) { return serve_pooled(req, true); } + +/* Embedding and reranking programs both return one pooled row per whole input. Share their + * admission, batching and cancellation; only embeddings truncate and normalize that row. */ +HttpResponse Server::serve_pooled(const HttpRequest& req, bool rerank) { if (!deps_.sched || !deps_.tok) return error_response(err_not_implemented("the server has no engine attached"), req.peer); + if (rerank && (!is_reranker(deps_.embed) || deps_.embed->dim() != 1)) + return error_response(err_not_implemented("/rerank requires a reranking model"), req.peer); + if (!rerank && is_reranker(deps_.embed)) + return error_response(err_not_implemented("this is a reranker; use /rerank"), req.peer); if (!deps_.embed) return error_response(err_not_implemented( opt_.image_model ? "/v1/embeddings requires an embedding model; this one makes images" @@ -1630,7 +1645,9 @@ HttpResponse Server::handle_embeddings(const HttpRequest& req) { OaiRequest r; ApiError err; - if (parse_embeddings_request(req.body, odeps_, lim_, &r, &err) < 0) + const int parsed = rerank ? parse_rerank_request(req.body, odeps_, lim_, &r, &err) + : parse_embeddings_request(req.body, odeps_, lim_, &r, &err); + if (parsed < 0) return error_response(err, req.peer); r.peer = req.peer; @@ -1720,17 +1737,29 @@ HttpResponse Server::handle_embeddings(const HttpRequest& req) { return error_response(err_internal(why), req.peer); } std::vector out(v.begin(), v.begin() + keep); - double ss = 0.0; - for (float x : out) ss += (double)x * x; - const float inv = ss > 0.0 ? (float)(1.0 / std::sqrt(ss)) : 0.0f; - for (float& x : out) x *= inv; + if (rerank) { + if (out.size() != 1 || !std::isfinite(out[0])) { + retire(gens); + release(n_in); + return error_response(err_internal("the reranker returned a non-finite score"), + req.peer); + } + } else { + double ss = 0.0; + for (float x : out) + ss += (double)x * x; + const float inv = ss > 0.0 ? (float)(1.0 / std::sqrt(ss)) : 0.0f; + for (float& x : out) + x *= inv; + } u.prompt += (int64_t)r.prompts[(size_t)g.prompt_index].tokens.size(); vecs.push_back(std::move(out)); } retire(gens); release(n_in); metrics_.observe_http(200); - return HttpResponse::json_body(200, embeddings_body(r, vecs, u)); + return HttpResponse::json_body(200, + rerank ? rerank_body(r, vecs, u) : embeddings_body(r, vecs, u)); } /* /v1/systemone (systemone.h): one engine request per question, each reading its answer diff --git a/core/server/server.h b/core/server/server.h index 7200e80f..860579ed 100644 --- a/core/server/server.h +++ b/core/server/server.h @@ -243,6 +243,8 @@ private: HttpResponse handle_native_completion(const HttpRequest& req); HttpResponse handle_infill(const HttpRequest& req); HttpResponse handle_embeddings(const HttpRequest& req); + HttpResponse handle_rerank(const HttpRequest& req); + HttpResponse serve_pooled(const HttpRequest& req, bool rerank); HttpResponse handle_systemone(const HttpRequest& req); HttpResponse handle_apply_template(const HttpRequest& req); using ToChat = int (*)(const std::string& body, const OaiLimits& lim, std::string* chat, diff --git a/docs/ARCHITECTURES.md b/docs/ARCHITECTURES.md index 0c0afd0c..2ad671da 100644 --- a/docs/ARCHITECTURES.md +++ b/docs/ARCHITECTURES.md @@ -21,7 +21,7 @@ plugin claims. | `arch/lfm2_bf16` | `lfm2` | *(empty)* | LiquidAI's LFM2 and LFM2-VL, bf16, one rank | | `arch/embgemma2` | `embeddinggemma2` | *(empty)* | EmbeddingGemma 2: a bidirectional encoder with Gemma 4's vision tower and audio conformer, pooled to one vector | | `arch/nomicbert` | `nomicbert` | *(empty)* | nomic-embed-text-v2-moe: a bidirectional post-norm encoder, 12 layers with 8 experts at top 2 on every second layer, mean-pooled to one vector an input | -| `arch/nemotron35_embed` | `mistral3` | *(empty)* | Nemotron 3.5 Embed 1B and 8B: native BF16 bidirectional text/image encoders with a Pixtral tower, retrieval formatting and normalized mean pooling, TP1 ([geometry and contracts](#nemotron35_embed-embedding-models)) | +| `arch/nemotron35_embed` | `mistral3` | *(empty)* | Nemotron 3.5 Embed 1B/8B and Rerank 8B: native BF16 bidirectional text/image retrieval with a Pixtral tower, TP1 ([geometry and contracts](#nemotron35_embed-embedding-models)) | | `arch/gemma4_bf16` | `gemma4` | `compressed-tensors` | Gemma 4 31B dense, and the E2B/E4B form at one rank, with its vision tower: sliding-window and proportional-RoPE global (`attention_k_eq_v`) attention, GELU ffn, softcapped logits; int4 codes with an f16 scale per 128 from Google's CT-INT4 (QAT) release or from bf16, served w4a8, or int8 codes on the same grid from bf16 (w8a8, the Q8 container). Optional draft model (`rad-convert --draft-model`): Google's assistant, with no cache of its own (`rad_drafter_shared_kv`), or z-lab's DFlash drafter, the block `arch/gemma4` serves (`arch/common/rad_gemma4_dflash.h`), or RedHatAI's DFlash2 speculator (`arch/common/rad_block_dflash2.h`) | | `arch/gemma3` | `gemma3` | *(empty)* | Gemma 3 dense text (TranslateGemma 27B) from the bf16 checkpoint: sliding-window and global attention at one head geometry, GemmaRMSNorm, GELU ffn; linears bf16, or int8, MXFP4 or asymmetric int4 over an activation scaled per (row, 128), as the recipe stores them. Optional DFlash2 drafter (`rad-convert --draft-model`) | | `arch/gemma4` | `gemma4` | *(empty)* | Gemma 4 text from Google's bf16 checkpoint (the 26B-A4B MoE and the dense sizes without per-layer embeddings) with z-lab's DFlash drafter; routed experts bf16 or block fp8 | @@ -935,6 +935,39 @@ English/Spanish/Japanese retrieval groups. Separate synthetic capacity checks co They do not establish native accuracy at maximum context/resolution. Native INT8/Q8, GGUF and TP2 remain unimplemented. +**Nemotron 3.5 Rerank 8B.** The same plugin recognizes the native +`Mistral3ForSequenceClassification` checkpoint, pinned at +`f88f8d9104726747791283ab156d2fcdb29e90a7`. It uses its own weights, the 8B text/vision +geometry above under `model.*`, and a bias-free `language_model.score.weight` [1,4096] head. Native +pooling stores the masked sum in BF16 before division, then stores the mean in BF16. +The separate `seg_mean_bf16_sum` operation preserves this seam without changing +embedding pooling. `logits_gemm` projects the mean and BF16 head to an FP32 scalar; +this is pooled output, with no generation sampler or KV cache. The endpoints return +raw logits, including negative values, rather than normalized embeddings. + +The supported per-pair context remains 32768, including query/document prefixes and +images. The native training template requires text queries and at most one image +per document. The image, context and configured capacity distinctions above apply. +Stored tiny reranker fixtures and the opt-in native reference generator are +`tests/mknemotron35rerankgolden.py` and `tests/mknemotron35rerankrealreference.py`. +Both are offline tools; runtime/build/tests never download a checkpoint or execute +remote model code. CPU component gates include exact BF16 pool results and scalar +error <=.01 for the tiny text/image graphs. Native validation uses raw-score error +and ranking gates rather than embedding cosine tolerances. + +```sh +python3 tests/mknemotron35rerankrealreference.py /models/Nemotron-3.5-Rerank-8B-BF16 /tmp/rerank-reference.json --sdpa-audit +RAD_NEMOTRON_RERANK_REAL_FIXTURE=/tmp/rerank-reference.json \ + RAD_NEMOTRON_DEVICE=1 RADIANCE_HOME="$PWD/build/radiance_home" \ + build/tests/engine_e2e_test nemotron35_rerank_real +``` + +Download the pinned revision above; an optional local `asset-manifest.json` is verified +when present. Standard Hugging Face revision metadata is also recognized; absent metadata +is recorded as unknown. The full-model gates are raw-score maximum absolute error <=.05, +RMSE <=.02, individual/batched difference <=1e-5 and preserved ranking for native margins +>.10. Omit `RAD_NEMOTRON_DEVICE` for CPU execution, as above. + --- # `nomicbert`: an embedding model diff --git a/docs/GUIDE.md b/docs/GUIDE.md index 84d1c0d8..8b34585e 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -304,7 +304,7 @@ and runs. | `lfm2_bf16` | LiquidAI LFM2 and LFM2-VL in bf16, including d1 (§5.13) | | `embgemma2` | EmbeddingGemma 2, an embedding model (§5.6) | | `nomicbert` | nomic-embed-text-v2-moe, an embedding model (§5.6) | -| `nemotron35_embed` | Nemotron 3.5 Embed 1B and 8B, BF16 text/image embeddings at TP1 (§5.6) | +| `nemotron35_embed` | Nemotron 3.5 Embed 1B/8B and Rerank 8B, BF16 text/image retrieval at TP1 (§5.6) | | `qwenimage21` | Qwen-Image 2.1 and 2.1-Turbo, an image model (§5.6) | | `krea2` | Krea 2 Raw and Turbo, an image model from text (§5.6) | | `anima` | Anima Base, Aesthetic and Turbo, an anime and illustration image model from text (§5.6) | @@ -2450,6 +2450,31 @@ attention sequences and existing arithmetic; unsupported multi-launch chains are [ARCHITECTURES.md](ARCHITECTURES.md#nemotron35_embed-embedding-models) for geometry, numerical contracts and validation limits. +**Nemotron 3.5 Rerank 8B BF16** uses the same architecture plugin with its own native +checkpoint and learned scalar head. Serve it with `--max-model-len 32768` and enough +`--max-num-batched-tokens` for each whole query/document pair. It serves `POST /rerank` +and `/v1/rerank`, using the vLLM/Jina-style request and result fields: + +```sh +curl -s http://localhost:8000/rerank -H 'Content-Type: application/json' \ + -d '{"query":"Where can I borrow books?","documents":["A public library lends books.","A football match."],"top_n":2}' +``` + +Each result has the original document `index`, a raw `relevance_score` (higher is more +relevant), and `document`. Scores may be negative; no sigmoid, L2 normalization or +dimensional truncation applies. Results are sorted descending, with ties retaining +input order. `top_n` omitted or zero returns all documents; `return_documents:false` +omits document contents. Token usage includes all scored pairs, even with `top_n`. + +Queries are text strings. A document is a string, or `{"content":[...]}` containing +typed `text` and `image_url` blocks, with an image data URL as for embeddings. At most +one image is allowed per document. The checkpoint's exact `query`/`document` template +places its image first, escapes literal controls and adds no BOS/EOS. The 32768-token +limit covers query, document, prefixes and image tokens together. Overlong pairs are +rejected, never truncated. Custom instructions, template overrides and activation +options that change the native score are refused. This model does not serve +`/v1/embeddings`; the embedding checkpoints continue to use that endpoint unchanged. + ```sh # text, a batch of texts, or token ids curl -s http://localhost:8000/v1/embeddings -H 'Content-Type: application/json' \ diff --git a/docs/OPS.md b/docs/OPS.md index 7b559771..1a7c1859 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -212,6 +212,7 @@ at once. Run it before adding a kernel plugin; the loader names only the first c | `mul_weight` | `M`(range) `n` `dtype` `scalar`/opt | `x`, `w`w → `y` (w one element or one row) | | `act_mul` | `M`(range) `n` `act` `dtype` | `a`, `b` → `y` (act(a)·b, two operands) | | `seg_mean` | `M`(range) `n` `dtype` | `x`, `cu_seqlens` → `y` (one mean row a segment) | +| `seg_mean_bf16_sum` | `M`(range) `n` `dtype` | `x`, `cu_seqlens` → `y` (BF16 sum, then BF16 quotient) | | `pool_rows` | `M`(range) `n` `k` `mult`:f64/opt `dtype` | `x` → `y` (one mean row a window of k rows) | | `pool_cols` | `M`(range) `n` `k` `mult`:f64/opt `dtype` | `x` → `y` (one mean column a window of k columns) | | `relu` | `M`(range) `n` `dtype` | `x` → `y` | @@ -291,6 +292,13 @@ rounded to `y`'s dtype before the product, as the unfused pair stores it. `[cu[s], cu[s+1])`, summed in double and rounded once. `M` is the step's token count and bands the op; the segment count is `cu_seqlens`' length less one. An empty segment is a zero row. +**`seg_mean_bf16_sum`** preserves the two BF16 stores of Nemotron 3.5 Rerank's masked +mean: sum the segment in f32, round the sum to BF16, divide by its valid-token count, +then round the quotient to BF16. Input and output are BF16; cumulative lengths are +int32, begin at zero, end at the active input row count and describe nonempty segments. +Pitched rows are supported. This is a separate operation so `seg_mean` and existing +embedding models keep their one-rounding contract. + **`pool_rows`** is a vision pooler over windows laid out consecutively: row `r` of `y` is the mean of `x`'s rows `[r*k, r*k + k)`, summed in f32 and rounded to `y`'s dtype, then times `mult` and rounded again (the unfused pair stores the mean). `M` is the input row count, a multiple of `k`. diff --git a/libavx/avx_cases.cpp b/libavx/avx_cases.cpp index 81ee275b..916a18f2 100644 --- a/libavx/avx_cases.cpp +++ b/libavx/avx_cases.cpp @@ -65,6 +65,9 @@ std::vector build_cases() { add("mul_weight", { HI("M", 9), HI("n", 645), HS("dtype", dt), HI("scalar", 1) }, EB(9, 645, w, 2)); add("seg_mean", { HI("M", 23), HI("n", 645), HS("dtype", dt) }, EB(23, 645, w, 1)); + if (!std::strcmp(dt, "bf16")) + add("seg_mean_bf16_sum", { HI("M", 23), HI("n", 645), HS("dtype", dt) }, + EB(23, 645, w, 1)); add("relu", { HI("M", 7), HI("n", 645), HS("dtype", dt) }, EB(7, 645, w, 2)); add("clamp", { HI("M", 7), HI("n", 645), HS("dtype", dt) }, EB(7, 645, w, 2)); add("rmsnorm", { HI("M", 5), HI("n", 645), HF("eps", 1e-6), HS("dtype", dt), diff --git a/libavx/avx_isa.h b/libavx/avx_isa.h index aa1f7c95..74df99e4 100644 --- a/libavx/avx_isa.h +++ b/libavx/avx_isa.h @@ -87,6 +87,7 @@ int avx_par_force(int threads); X(scatter_rows) X(ngram_ids) \ X(ple_gate) X(ple_conv) X(cast) X(softmax) \ X(scale_rows) X(scale) X(fill) X(act_mul) \ + X(seg_mean_bf16_sum) \ X(seg_mean) X(mul_weight) X(pool_rows) X(pool_cols) \ X(relu) X(clamp) X(conv2d) X(conv1d_dw) \ X(rel_sinusoid) X(seg_sinusoid) X(conv2d_unfold) \ diff --git a/libavx/avx_pixtral.cpp b/libavx/avx_pixtral.cpp index 47483807..501b0156 100644 --- a/libavx/avx_pixtral.cpp +++ b/libavx/avx_pixtral.cpp @@ -188,3 +188,44 @@ AVX_KERNEL(embed_attn) { } return RAD_OK; } + +/* Native masked mean: the sum is stored in BF16 before dividing, then stored in BF16 again. + * Keep this separate from seg_mean's one-rounding sentence-embedding contract. */ +AVX_KERNEL(seg_mean_bf16_sum) { + if (!rad_args_have(a, 3)) + return RAD_E_INVAL; + const RadTensor *x = &a->t[0], *cu = &a->t[1], *y = &a->t[2]; + if (x->dtype != RAD_BF16 || y->dtype != RAD_BF16 || cu->dtype != RAD_I32) + return RAD_E_DTYPE; + if (!x->data || !cu->data || !y->data) + return RAD_E_INVAL; + const int64_t M = x->rank == 2 ? x->shape[0] : 0, N = p_int(a, "n", 0); + const int64_t S = cu->rank == 1 && cu->shape[0] > 1 ? cu->shape[0] - 1 : 0; + const auto matrix = [](const RadTensor& t, int64_t rows, int64_t cols) { + constexpr int64_t limit = INT64_MAX / 2; + if (t.rank != 2 || t.shape[0] != rows || t.shape[1] != cols || t.stride[0] <= 0 || + t.stride[1] <= 0 || cols - 1 > limit / t.stride[1]) + return false; + const int64_t columns = (cols - 1) * t.stride[1]; + return t.stride[0] > columns && rows - 1 <= (limit - columns) / t.stride[0]; + }; + if (M <= 0 || M > INT32_MAX || M > p_int(a, "M", 0) || N <= 0 || S <= 0 || S > M || + cu->stride[0] <= 0 || cu->stride[0] > (INT64_MAX / 4) / S || !matrix(*x, M, N) || + !matrix(*y, S, N)) + return RAD_E_SHAPE; + const auto at = [&](int64_t s) { return ldi(cu, s * cu->stride[0]); }; + if (at(0) != 0 || at(S) != M) + return RAD_E_INVAL; + for (int64_t s = 0; s < S; ++s) + if (at(s) < 0 || at(s + 1) <= at(s) || at(s + 1) > M) + return RAD_E_INVAL; + for (int64_t s = 0; s < S; ++s) + for (int64_t c = 0; c < N; ++c) { + float sum = 0; + for (int64_t r = at(s); r < at(s + 1); ++r) + sum += ldt(x, r * x->stride[0] + c * x->stride[1]); + stt(y, s * y->stride[0] + c * y->stride[1], + narrow1(RAD_BF16, sum) / (float)(at(s + 1) - at(s))); + } + return RAD_OK; +} diff --git a/libavx/avx_registry.cpp b/libavx/avx_registry.cpp index 682eb201..7668323c 100644 --- a/libavx/avx_registry.cpp +++ b/libavx/avx_registry.cpp @@ -961,6 +961,8 @@ static const RadOpSchema kSchemas[] = { "y = x * w, `w` a weight of one element or one row, broadcast; f32 product rounded once." }, { "act_mul", ARR(pActMul), ARR(oBinary), "y = act(a) * b, act silu / gelu / gelu_tanh, the activation rounded to y's dtype first." }, +{ "seg_mean_bf16_sum", ARR(pSegMean), ARR(oSegMean), + "BF16 masked mean: f32 segment sum rounded to BF16 before division, then BF16 output." }, { "seg_mean", ARR(pSegMean), ARR(oSegMean), "y[s] = the mean of x's rows in cu_seqlens segment s, summed in double, rounded once." }, { "relu", ARR(pMnD), ARR(oUnary), "y = max(x, 0)." }, @@ -1580,6 +1582,8 @@ SIMPLE("avx_mul", "mul", "elem", "elementwise product, broadcasting b", DT_FLOAT SIMPLE("avx_act_mul", "act_mul", "elem", "act(a) * b over two operands", DT_FLOAT, L(act_mul)), SIMPLE("avx_mul_weight", "mul_weight", "elem", "x * a scalar or one-row weight", DT_FLOAT, L(mul_weight)), +SIMPLE("avx_seg_mean_bf16_sum", "seg_mean_bf16_sum", "elem", "BF16 sum/division mean pooling", + "bf16 in and out; f32 sum, BF16 sum and quotient", L(seg_mean_bf16_sum)), SIMPLE("avx_seg_mean", "seg_mean", "elem", "mean of each cu_seqlens segment's rows", DT_FLOAT, L(seg_mean)), SIMPLE("avx_pool_rows", "pool_rows", "elem", "mean of every k consecutive rows, then a multiplier", diff --git a/libr4d/r4d_nemotron_bf16.hip b/libr4d/r4d_nemotron_bf16.hip index 8935d04f..3d259d89 100644 --- a/libr4d/r4d_nemotron_bf16.hip +++ b/libr4d/r4d_nemotron_bf16.hip @@ -54,6 +54,22 @@ __global__ void validate(const int* x, int64_t stride, int64_t plane, int M, int *valid = 1; } +__global__ void pooled_mean(const uint16_t* x, int64_t xl, int64_t xs, const int* cu, int64_t cs, + uint16_t* y, int64_t yl, int64_t ys, int S, int N, const int* valid) { + if (*valid != 1) + return; + const int64_t c = (int64_t)blockIdx.x * NT + threadIdx.x; + if (c >= N) + return; + for (int64_t s = blockIdx.y; s < S; s += gridDim.y) { + const int begin = cu[s * cs], end = cu[(s + 1) * cs]; + float sum = 0; + for (int r = begin; r < end; ++r) + sum += bf2f(x[(int64_t)r * xl + c * xs]); + y[s * yl + c * ys] = f32_to_bf16(narrow(sum) / (float)(end - begin)); + } +} + __global__ void scale(uint16_t* x, int64_t ld, int64_t cs, const int* pos, int64_t ps, int M, int n, int original, float beta, const int* valid) { if (*valid != 1) return; @@ -286,6 +302,24 @@ extern "C" void r4d_rotary_fini(void* p) { extern "C" int64_t r4d_nemotron_scratch(const RadArgs*) { return 4; } +extern "C" int r4d_rad_seg_mean_bf16_sum(const RadArgs* a, RadStream stream) { + if (!rad_args_have(a, 3)) + return RAD_E_INVAL; + const auto &x = a->t[0], &cu = a->t[1], &y = a->t[2]; + const int64_t M = x.rank == 2 ? x.shape[0] : 0, N = r4d_geti_or(a, "n", 0), + S = cu.rank == 1 && cu.shape[0] > 1 ? cu.shape[0] - 1 : 0; + if (M <= 0 || M > INT_MAX || M > r4d_geti_or(a, "M", 0) || N <= 0 || N > INT_MAX || S <= 0 || + S > INT_MAX || !matrix(x, M, N) || !matrix(y, S, N) || !indices(cu, S + 1)) + return RAD_E_SHAPE; + int rc = prepare(a, stream, cu, (int)M, 2, (int)S, INT_MAX); + if (rc < 0) + return rc; + hipLaunchKernelGGL(pooled_mean, dim3((N + NT - 1) / NT, std::min(S, 65535)), dim3(NT), 0, + (hipStream_t)stream, (const uint16_t*)x.data, x.stride[0], x.stride[1], + (const int*)cu.data, cu.stride[0], (uint16_t*)y.data, y.stride[0], y.stride[1], + (int)S, (int)N, (const int*)a->scratch); + return finish(); +} extern "C" int r4d_rad_position_scale(const RadArgs* a, RadStream stream) { if (!rad_args_have(a, 2)) return RAD_E_INVAL; const auto &x = a->t[0], &p = a->t[1]; diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index 33e8e047..5fb680fa 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -765,6 +765,7 @@ int r4d_rad_mul (const RadArgs*, RadStream); int r4d_rad_mul_weight (const RadArgs*, RadStream); int r4d_rad_act_mul (const RadArgs*, RadStream); int r4d_rad_seg_mean (const RadArgs*, RadStream); +int r4d_rad_seg_mean_bf16_sum(const RadArgs*, RadStream); int r4d_rad_qk_norm_rope (const RadArgs*, RadStream); int r4d_rad_cast_widen (const RadArgs*, RadStream); int r4d_rad_cast_f16 (const RadArgs*, RadStream); diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index b04a9115..23d0b254 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -2999,6 +2999,8 @@ static const RadOpSchema kSchemas[] = { SCHEMA("seg_mean", pSegMean, oSegMean, "Row s of y is the mean of x's rows [cu_seqlens[s], cu_seqlens[s+1]), summed in f64 " "and rounded once; an empty segment is zeros."), + SCHEMA("seg_mean_bf16_sum", pSegMean, oSegMean, + "BF16 masked mean: f32 segment sum rounded to BF16 before division, then BF16 output."), SCHEMA("qk_norm_rope", pQkNormRope, oQkNormRope, "In place over a fused [q | k | v] row: each q and k head RMS-normed against its gain " "(plus wadd) and rounded, then rotated (neox or gptj, rotary_dim of head_dim); with " @@ -5808,6 +5810,14 @@ static const RadKernelInfo kKernels[] = { nullptr, nullptr, r4d_rad_act_mul, nullptr, nullptr, nullptr, r4d_shape_binary }, +{ "seg_mean_bf16_sum", "seg_mean_bf16_sum", "elem", + "native BF16 sum/division mean pooling over whole nonempty segments", + "M and segment count fit int32; pitched BF16 rows and int32 cumulative lengths", + "f32 sum, BF16 sum rounding, BF16 quotient", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cBf16Row), NOTUNE, + nullptr, nullptr, r4d_rad_seg_mean_bf16_sum, r4d_nemotron_scratch }, + { "seg_mean_bf16", "seg_mean", "elem", "mean pooling: one row a cu_seqlens segment", "any n; 32 columns by 8 row lanes a workgroup, one workgroup row a segment", @@ -10281,6 +10291,7 @@ extern "C" int rad_kernel_concurrent(int i) { "kv_resolve", // Each model-local entry validates metadata before its dependent data launch. "position_scale_", "ministral_rope_", "pixtral_rope_", "pixtral_merge_", "embed_attn_", + "seg_mean_bf16_sum", }; for (const char* p : kStateful) if (std::strncmp(k->name, p, std::strlen(p)) == 0) return 0; diff --git a/libref/ref_ops.h b/libref/ref_ops.h index 862ae8fd..4d447f53 100644 --- a/libref/ref_ops.h +++ b/libref/ref_ops.h @@ -86,6 +86,7 @@ int ref_mla_attn(const RadArgs*, RadStream); int ref_gelu_mul (const RadArgs*, RadStream); int ref_act_mul (const RadArgs*, RadStream); int ref_mul_weight (const RadArgs*, RadStream); +int ref_seg_mean_bf16_sum (const RadArgs*, RadStream); int ref_seg_mean (const RadArgs*, RadStream); int ref_pool_rows (const RadArgs*, RadStream); int ref_pool_cols (const RadArgs*, RadStream); @@ -362,6 +363,7 @@ REF_SHAPE_FN(ref_gelu_mul); REF_SHAPE_FN(ref_act_mul); REF_SHAPE_FN(ref_mul_weight); REF_SHAPE_FN(ref_seg_mean); +REF_SHAPE_FN(ref_seg_mean_bf16_sum); REF_SHAPE_FN(ref_pool_rows); REF_SHAPE_FN(ref_pool_cols); REF_SHAPE_FN(ref_relu); diff --git a/libref/ref_pixtral.cpp b/libref/ref_pixtral.cpp index 2f0455ce..83e93afc 100644 --- a/libref/ref_pixtral.cpp +++ b/libref/ref_pixtral.cpp @@ -191,3 +191,44 @@ int ref_embed_attn(const RadArgs* a, RadStream) { } return RAD_OK; } + +/* Native masked mean: the sum is stored in BF16 before dividing, then stored in BF16 again. + * Keep this separate from seg_mean's one-rounding sentence-embedding contract. */ +int ref_seg_mean_bf16_sum(const RadArgs* a, RadStream) { + if (!have(a, 3)) + return RAD_E_INVAL; + const RadTensor *x = &a->t[0], *cu = &a->t[1], *y = &a->t[2]; + if (x->dtype != RAD_BF16 || y->dtype != RAD_BF16 || cu->dtype != RAD_I32) + return RAD_E_DTYPE; + if (!x->data || !cu->data || !y->data) + return RAD_E_INVAL; + const int64_t M = x->rank == 2 ? x->shape[0] : 0, N = p_int(a, "n", 0); + const int64_t S = cu->rank == 1 && cu->shape[0] > 1 ? cu->shape[0] - 1 : 0; + const auto matrix = [](const RadTensor& t, int64_t rows, int64_t cols) { + constexpr int64_t limit = INT64_MAX / 2; + if (t.rank != 2 || t.shape[0] != rows || t.shape[1] != cols || t.stride[0] <= 0 || + t.stride[1] <= 0 || cols - 1 > limit / t.stride[1]) + return false; + const int64_t columns = (cols - 1) * t.stride[1]; + return t.stride[0] > columns && rows - 1 <= (limit - columns) / t.stride[0]; + }; + if (M <= 0 || M > INT32_MAX || M > p_int(a, "M", 0) || N <= 0 || S <= 0 || S > M || + cu->stride[0] <= 0 || cu->stride[0] > (INT64_MAX / 4) / S || !matrix(*x, M, N) || + !matrix(*y, S, N)) + return RAD_E_SHAPE; + const auto at = [&](int64_t s) { return ld_int(cu->dtype, cu->data, s * cu->stride[0]); }; + if (at(0) != 0 || at(S) != M) + return RAD_E_INVAL; + for (int64_t s = 0; s < S; ++s) + if (at(s) < 0 || at(s + 1) <= at(s) || at(s + 1) > M) + return RAD_E_INVAL; + for (int64_t s = 0; s < S; ++s) + for (int64_t c = 0; c < N; ++c) { + float sum = 0; + for (int64_t r = at(s); r < at(s + 1); ++r) + sum += ldt(x, r * x->stride[0] + c * x->stride[1]); + stt(y, s * y->stride[0] + c * y->stride[1], + round_dt(RAD_BF16, sum) / (float)(at(s + 1) - at(s))); + } + return RAD_OK; +} diff --git a/libref/ref_registry.cpp b/libref/ref_registry.cpp index 23050ef8..ad673927 100644 --- a/libref/ref_registry.cpp +++ b/libref/ref_registry.cpp @@ -1179,6 +1179,8 @@ static const RadOpSchema kSchemas[] = { "y = act(a) * b, `act` \"silu\", \"gelu\" (exact erf), \"gelu_tanh\" or \"sigmoid\". The activation is " "rounded to y's dtype before the product, which is the unfused pair. `a` and `b` may be column " "slices of one fused row." }, +{ "seg_mean_bf16_sum", ARR(pSegMean), ARR(oSegMean), + "BF16 masked mean: f32 segment sum rounded to BF16 before division, then BF16 output." }, { "seg_mean", ARR(pSegMean), ARR(oSegMean), "y[s] = mean of x's rows [cu[s], cu[s+1]): one row a segment, summed in double and rounded " "once to y's dtype. An empty segment is a zero row." }, @@ -2256,6 +2258,8 @@ SIMPLE("ref_mix_rows", "mix_rows", "elem", "a weighted sum of k consecutive rows ref_mix_rows), SIMPLE("ref_chan_stats", "chan_stats", "elem", "per-channel statistics held as weights", DT_FLOAT, ref_chan_stats), +SIMPLE("ref_seg_mean_bf16_sum", "seg_mean_bf16_sum", "elem", "BF16 sum/division mean pooling", + "bf16 in and out; f32 sum, BF16 sum and quotient", ref_seg_mean_bf16_sum), SIMPLE("ref_seg_mean", "seg_mean", "elem", "mean of each cu_seqlens segment's rows", DT_FLOAT, ref_seg_mean), SIMPLE("ref_pool_rows", "pool_rows", "elem", "mean of every k consecutive rows, then a multiplier", diff --git a/libref/ref_shapes.cpp b/libref/ref_shapes.cpp index 6dbea3b9..cbe32fed 100644 --- a/libref/ref_shapes.cpp +++ b/libref/ref_shapes.cpp @@ -592,6 +592,12 @@ int ref_seg_mean_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) return o.finish("seg_mean", operand, out); } +int ref_seg_mean_bf16_sum_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + if (act_dt(p, n_p) != RAD_BF16) + return RAD_E_UNSUPPORTED; + return ref_seg_mean_shape(p, n_p, operand, out); +} + int ref_pool_rows_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const uint32_t D = act_dt(p, n_p); const int64_t n = gi(p, n_p, "n", 0), k = gi(p, n_p, "k", 0); diff --git a/tests/data/chat/nemotron35/README.md b/tests/data/chat/nemotron35/README.md index 9e4875f8..7e244e1a 100644 --- a/tests/data/chat/nemotron35/README.md +++ b/tests/data/chat/nemotron35/README.md @@ -23,3 +23,10 @@ python3 tests/mknemotron35inputgolden.py --tokenizer /path/to/checkpoint/tokeniz The generator needs Jinja2, Hugging Face tokenizers, and the checked-in vision fixture. The golden records the source template, full tokenizer, and subset SHA-256 hashes. It runs no model weights and is never called by CMake or CTest. + +`rerank-template.jinja` is the unchanged template from +`nvidia/Nemotron-3.5-Rerank-8B-BF16` revision +`f88f8d9104726747791283ab156d2fcdb29e90a7`, under the same retained OpenMDW-1.1 +license. It supplies the independent query/document rendering oracle to the +manually run `tests/mknemotron35rerankgolden.py`; the engine does not execute +remote model code. The tiny scoring head is seeded synthetic test data. diff --git a/tests/data/chat/nemotron35/rerank-template.jinja b/tests/data/chat/nemotron35/rerank-template.jinja new file mode 100644 index 00000000..d00a04c3 --- /dev/null +++ b/tests/data/chat/nemotron35/rerank-template.jinja @@ -0,0 +1,105 @@ +{%- if messages | length == 2 and messages[0]['role'] == 'query' and messages[1]['role'] == 'document' -%} +{# Render the checkpoint's query/document training format without BOS/EOS. #} +{%- macro text_content(content) -%} + {%- if content is string -%} + {{- content | replace('[', '[‌') | replace('<', '<‌') -}} + {%- else -%} + {%- set ns = namespace(first=true) -%} + {%- for block in content -%} + {%- if block['type'] == 'text' -%} + {%- if not ns.first -%}{{- '\n\n' -}}{%- endif -%} + {{- block['text'] | replace('[', '[‌') | replace('<', '<‌') -}} + {%- set ns.first = false -%} + {%- elif block['type'] not in ['image', 'image_url'] -%} + {{- raise_exception('Only text and image documents are supported') -}} + {%- endif -%} + {%- endfor -%} + {%- endif -%} +{%- endmacro -%} +{%- if messages | length != 2 or messages[0]['role'] != 'query' or messages[1]['role'] != 'document' -%} + {{- raise_exception('Reranking requires a query followed by a document') -}} +{%- endif -%} +{%- set ns = namespace(images=0) -%} +{%- if messages[0]['content'] is not string -%} + {%- for block in messages[0]['content'] -%} + {%- if block['type'] != 'text' -%}{{- raise_exception('Queries must be text') -}}{%- endif -%} + {%- endfor -%} +{%- endif -%} +{%- if messages[1]['content'] is not string -%} + {%- for block in messages[1]['content'] -%} + {%- if block['type'] in ['image', 'image_url'] -%}{%- set ns.images = ns.images + 1 -%}{%- endif -%} + {%- endfor -%} +{%- endif -%} +{%- if ns.images > 1 -%}{{- raise_exception('At most one image per document is supported') -}}{%- endif -%} +{%- set rendered -%} + {%- if ns.images -%}{{- '[IMG] ' -}}{%- endif -%} + {{- 'query: ' -}}{{- text_content(messages[0]['content']) -}} + {{- '\n\npassage: ' -}}{{- text_content(messages[1]['content']) -}} +{%- endset -%} +{{- rendered | trim if ns.images else rendered -}} + +{%- else -%} +{# nemo-mistral-retrieval-v1 + Derived from the Mistral Ministral-3 instruct chat template render_content + macro and its image-before-text canonicalization. Retrieval adaptation: + system content is the retrieval prefix; generation wrappers and BOS/EOS are + deliberately omitted so message inference matches training token for token. +#} +{%- macro mark_user_text(text) -%} +{{- text | replace("[", "[‌") | replace("<", "<‌") -}} +{%- endmacro -%} +{%- macro render_text_content(content, context_name) -%} +{%- if content is string -%} + {{- content -}} +{%- elif content is sequence -%} + {%- set ns = namespace(has_output=false) -%} + {%- for block in content -%} + {%- if block["type"] == "text" -%} + {%- if ns.has_output %}{{ "\n\n" }}{% endif -%} + {{- block["text"] -}} + {%- set ns.has_output = true -%} + {%- else -%} + {{- raise_exception(context_name + " may contain only text blocks") -}} + {%- endif -%} + {%- endfor -%} +{%- else -%} + {{- raise_exception(context_name + " must be a string or a list of text blocks") -}} +{%- endif -%} +{%- endmacro -%} +{%- macro render_user_content(content) -%} +{%- if content is string -%} + {{- mark_user_text(content) -}} +{%- elif content is sequence -%} + {%- set ns = namespace(has_output=false) -%} + {%- for block in content -%} + {%- if block["type"] in ["image", "image_url"] -%} + {%- if ns.has_output %}{{ " " }}{% endif -%} + {{- "[IMG]" -}} + {%- set ns.has_output = true -%} + {%- endif -%} + {%- endfor -%} + {%- for block in content -%} + {%- if block["type"] == "text" -%} + {%- if ns.has_output %}{{ " " }}{% endif -%} + {{- mark_user_text(block["text"]) -}} + {%- set ns.has_output = true -%} + {%- elif block["type"] not in ["image", "image_url"] -%} + {{- raise_exception("User content supports only text and image blocks") -}} + {%- endif -%} + {%- endfor -%} +{%- else -%} + {{- raise_exception("User content must be a string or a list of text and image blocks") -}} +{%- endif -%} +{%- endmacro -%} +{%- if messages | length == 1 and messages[0]["role"] == "user" -%} + {{- render_user_content(messages[0]["content"]) -}} +{%- elif messages | length == 2 + and messages[0]["role"] == "system" + and messages[1]["role"] == "user" -%} + {{- render_text_content(messages[0]["content"], "System content") -}} + {{- " " -}} + {{- render_user_content(messages[1]["content"]) -}} +{%- else -%} + {{- raise_exception("Retrieval inputs require one user message with an optional leading system prefix") -}} +{%- endif -%} +{%- endif -%} diff --git a/tests/data/golden/nemotron35_rerank.json b/tests/data/golden/nemotron35_rerank.json new file mode 100644 index 00000000..e96ac131 --- /dev/null +++ b/tests/data/golden/nemotron35_rerank.json @@ -0,0 +1 @@ +{"provenance":{"transformers":"5.20.0","torch":"2.14.1+cpu","seed":3508,"attention":"eager","dtype":"bfloat16","head_arithmetic":"float32","template_revision":"f88f8d9104726747791283ab156d2fcdb29e90a7"},"head":{"shape":[1,16],"bf16":[48599,16068,15923,15757,48680,15518,48674,15855,48551,48633,15760,47978,15920,48837,48538,48654]},"cases":[{"name":"short","inputs":[[3,4,7,12,6]],"offsets":[0],"pooled":[[-0.2314453125,0.25,0.10009765625,0.02734375,1.75,0.63671875,0.232421875,-0.1533203125,0.0247802734375,1.6484375,-0.0027313232421875,0.75390625,-0.5703125,-0.9453125,-1.484375,2.09375]],"scores":[-0.308460533618927],"head_only_scores":[-0.308460533618927]},{"name":"ragged","inputs":[[3,4,7],[12,6,2,8,9]],"offsets":[0,0],"pooled":[[-0.119140625,-0.17578125,0.1396484375,-0.326171875,1.8125,0.435546875,0.0498046875,-0.318359375,-0.26953125,1.6796875,0.004852294921875,0.396484375,-0.2119140625,-1.234375,-1.40625,2.078125],[0.0260009765625,-0.400390625,0.46875,-0.040771484375,0.88671875,0.51171875,0.10400390625,0.228515625,1.046875,1.5,-0.1767578125,0.89453125,0.412109375,-0.35546875,-0.91796875,1.5625]],"scores":[-0.3140508532524109,-0.425670325756073],"head_only_scores":[-0.3140508532524109,-0.425670325756073]},{"name":"q_scale_boundary","inputs":[[3,4,7,12]],"offsets":[16382],"pooled":[[-0.2158203125,0.267578125,0.1533203125,-0.107421875,1.578125,0.71875,0.306640625,-0.1123046875,0.1416015625,1.953125,-0.1630859375,0.48046875,-0.34375,-1.265625,-1.34375,1.8984375]],"scores":[-0.15869462490081787],"head_only_scores":[-0.15869462490081787]}],"multimodal":[{"name":"image_only","inputs":[{"tokens":[10,10,13],"placements":[{"image":1,"tok":0}]}],"pooled":[[-0.78125,-0.099609375,0.55859375,0.306640625,0.51953125,0.58203125,0.2470703125,-2.140625,1.5,-0.435546875,0.1474609375,0.412109375,-2.25,-0.3671875,0.431640625,-1.2578125]],"hidden":[[[-0.76171875,-0.15234375,0.9921875,0.2197265625,0.34375,1.1015625,0.2431640625,-2.09375,1.546875,-0.66015625,-0.026123046875,0.3515625,-2.28125,-0.44140625,0.392578125,-0.96875],[-0.69921875,-0.2392578125,0.98046875,0.3828125,0.390625,0.953125,0.18359375,-2.234375,1.5546875,-0.72265625,0.07568359375,0.25,-2.234375,-0.392578125,0.330078125,-0.84375],[-0.875,0.0927734375,-0.294921875,0.318359375,0.8203125,-0.302734375,0.314453125,-2.109375,1.390625,0.07666015625,0.392578125,0.6328125,-2.21875,-0.26953125,0.578125,-1.96875]]],"scores":[-0.36420053243637085]},{"name":"image_text","inputs":[{"tokens":[3,4,10,10,10,12,10,10,10,13,5,7,8,6],"placements":[{"image":2,"tok":2}]}],"pooled":[[-0.11181640625,0.26171875,0.5859375,0.5078125,1.7890625,1.0546875,0.35546875,-0.79296875,0.94140625,1.1484375,0.349609375,1.109375,-1.3984375,-0.5703125,-0.89453125,1.375]],"hidden":[[[0.17578125,-0.43359375,0.453125,-0.28515625,1.6796875,0.859375,0.34765625,-0.9296875,1.1796875,1.3515625,-0.333984375,0.9375,-1.2734375,-0.61328125,-0.392578125,2.59375],[-0.53125,0.314453125,0.39453125,0.59765625,1.0859375,1.125,0.75390625,-1.296875,1.3046875,0.48046875,0.2041015625,1.015625,-2.03125,-0.77734375,-1.4375,0.9921875],[0.0791015625,0.455078125,0.78515625,0.427734375,1.8671875,1.3984375,0.314453125,-0.71484375,1.15625,1.1796875,0.099609375,1.1875,-1.6953125,-0.486328125,-0.8359375,1.3125],[0.109375,0.46875,0.75,0.439453125,1.796875,1.375,0.314453125,-0.76953125,1.21875,1.1953125,0.24609375,1.1328125,-1.7421875,-0.5078125,-0.8359375,1.296875],[0.11474609375,0.337890625,0.79296875,0.58203125,2.03125,1.1953125,0.29296875,-0.7421875,1.1328125,1.109375,0.1103515625,1.2265625,-1.6484375,-0.375,-0.82421875,1.4453125],[-0.061767578125,0.578125,0.45703125,-0.1796875,1.953125,1.5234375,0.2734375,-0.61328125,1.1953125,1.0859375,0.66796875,0.69140625,-1.40625,-0.9375,-1.3828125,1.09375],[0.048583984375,0.318359375,0.77734375,0.53515625,2.015625,1.265625,0.302734375,-0.7578125,1.1171875,1.171875,0.1708984375,1.1875,-1.6875,-0.41796875,-0.76171875,1.421875],[0.1953125,0.279296875,0.703125,0.578125,1.96875,1.21875,0.27734375,-0.84375,1.140625,1.1640625,0.2275390625,1.171875,-1.6484375,-0.416015625,-0.87109375,1.4453125],[0.10546875,0.384765625,0.8046875,0.53515625,1.859375,1.2890625,0.2392578125,-0.8359375,1.21875,1.15625,0.177734375,1.1015625,-1.609375,-0.498046875,-0.94921875,1.4453125],[-0.1513671875,0.6015625,-0.61328125,0.5703125,2.15625,-0.296875,0.376953125,-0.84375,0.97265625,1.703125,0.53515625,1.3828125,-1.5625,-0.220703125,-0.44921875,0.01153564453125],[0.359375,0.39453125,0.3359375,1.1015625,1.4609375,1.9375,-0.427734375,-0.85546875,0.296875,1.3828125,0.54296875,0.79296875,0.033447265625,-1.1328125,-0.5703125,2.046875],[-0.330078125,-0.1416015625,0.6796875,0.55859375,1.984375,-0.369140625,1.40625,-0.4453125,0.87109375,0.7421875,0.69921875,0.69140625,-1.0703125,-0.41015625,-1.1328125,2.40625],[-0.59375,0.52734375,1.03125,1.421875,1.734375,1.375,0.400390625,-0.8984375,0.32421875,1.2421875,0.341796875,1.2109375,-1.3984375,-0.60546875,-0.90234375,0.21484375],[-1.078125,-0.41015625,0.8359375,0.220703125,1.375,0.84765625,0.08154296875,-0.546875,0.048828125,1.2109375,1.21875,1.8359375,-0.9375,-0.5859375,-1.1796875,1.5703125]]],"scores":[-0.512739896774292]},{"name":"text_and_image_batch","inputs":[{"tokens":[3,4,7,8],"placements":[]},{"tokens":[10,10,13],"placements":[{"image":1,"tok":0}]}],"pooled":[[-0.119140625,-0.234375,0.25390625,0.0032958984375,2.3125,0.7265625,-0.0458984375,-0.67578125,0.40625,0.83203125,0.337890625,0.96875,-0.369140625,-0.71875,-1.7265625,1.328125],[-0.78125,-0.099609375,0.55859375,0.306640625,0.51953125,0.58203125,0.2470703125,-2.140625,1.5,-0.435546875,0.1474609375,0.412109375,-2.25,-0.3671875,0.431640625,-1.2578125]],"hidden":[[[0.388671875,-0.734375,0.0277099609375,-0.87890625,2.34375,0.79296875,-0.47265625,-0.66015625,0.58203125,1.171875,-0.2099609375,0.89453125,-0.09716796875,-0.70703125,-1.1640625,2.28125],[-0.328125,-0.00836181640625,-0.00506591796875,-0.003692626953125,1.875,1.1484375,-0.044921875,-1.1171875,0.828125,0.384765625,0.3203125,1.0625,-0.94140625,-0.9375,-2.296875,0.8203125],[-0.12255859375,-0.45703125,0.2734375,-0.030029296875,2.6875,-0.416015625,0.61328125,-0.228515625,0.3515625,0.61328125,0.796875,0.6875,0.02685546875,-0.52734375,-1.8671875,2.171875],[-0.4140625,0.263671875,0.71875,0.92578125,2.375,1.375,-0.279296875,-0.703125,-0.1357421875,1.1640625,0.44140625,1.2265625,-0.462890625,-0.7109375,-1.5703125,0.03857421875]],[[-0.76171875,-0.15234375,0.9921875,0.2197265625,0.34375,1.1015625,0.2431640625,-2.09375,1.546875,-0.66015625,-0.026123046875,0.3515625,-2.28125,-0.44140625,0.392578125,-0.96875],[-0.69921875,-0.2392578125,0.98046875,0.3828125,0.390625,0.953125,0.18359375,-2.234375,1.5546875,-0.72265625,0.07568359375,0.25,-2.234375,-0.392578125,0.330078125,-0.84375],[-0.875,0.0927734375,-0.294921875,0.318359375,0.8203125,-0.302734375,0.314453125,-2.109375,1.390625,0.07666015625,0.392578125,0.6328125,-2.21875,-0.26953125,0.578125,-1.96875]]],"scores":[-0.42481428384780884,-0.36420053243637085]}],"http":[{"name":"text","query":"C","document":"A","image":null,"rendered":"query: C\n\npassage: A","inputs":[{"tokens":[145,149,133,146,153,90,5,7,42,42,144,129,147,147,129,135,133,90,5,3],"placements":[]}],"scores":[0.15410879254341125]},{"name":"controls","query":"[IMG] ","document":"CDF","image":null,"rendered":"query: [\u200cIMG] <\u200cA>\n\npassage: CDF","inputs":[{"tokens":[145,149,133,146,153,90,5,123,258,160,172,105,109,103,125,5,92,258,160,172,3,94,42,42,144,129,147,147,129,135,133,90,5,7,8,6],"placements":[]}],"scores":[0.0697583258152008]},{"name":"image","query":"C","document":null,"image":1,"rendered":"[IMG] query: C\n\npassage:","inputs":[{"tokens":[10,10,13,5,145,149,133,146,153,90,5,7,42,42,144,129,147,147,129,135,133,90],"placements":[{"image":1,"tok":0}]}],"scores":[0.05630895495414734]},{"name":"image_text","query":"C","document":"CDF","image":2,"rendered":"[IMG] query: C\n\npassage: CDF","inputs":[{"tokens":[10,10,10,12,10,10,10,13,5,145,149,133,146,153,90,5,7,42,42,144,129,147,147,129,135,133,90,5,7,8,6],"placements":[{"image":2,"tok":0}]}],"scores":[-0.15939390659332275]},{"name":"image_unicode_whitespace","query":"C","document":"CDF\u00a0\t\u3000","image":2,"rendered":"[IMG] query: C\n\npassage: CDF","inputs":[{"tokens":[10,10,10,12,10,10,10,13,5,145,149,133,146,153,90,5,7,42,42,144,129,147,147,129,135,133,90,5,7,8,6],"placements":[{"image":2,"tok":0}]}],"scores":[-0.15939390659332275]}],"pool":{"shape":[10,7],"bf16":[48719,16059,16230,16220,16228,48673,48935,49033,16006,48908,16147,16062,49073,48884,15526,48806,49103,16288,49024,15717,49092,16244,16293,16276,16107,48780,48929,16363,15881,48815,16287,16065,48909,16296,48953,48907,48579,49021,49100,16320,48517,49037,16268,48823,16312,48976,16266,16248,48841,16249,49118,15979,49013,16261,16386,16218,49030,49048,16273,49134,16236,15904,16355,49086,16300,15888,48938,48884,48805,16074],"cu":[0,3,10],"expected":[48853,15823,48856,16229,15795,48893,48995,15417,48671,16159,48953,16109,16125,16065]}} diff --git a/tests/engine_e2e_test.cpp b/tests/engine_e2e_test.cpp index 62269b50..280eb60b 100644 --- a/tests/engine_e2e_test.cpp +++ b/tests/engine_e2e_test.cpp @@ -2349,9 +2349,11 @@ json nemotron_fixture(const char* name) { /* The same BF16 parameters as the component oracle, now read by the real checkpoint loader. * Extra vocabulary rows only make the byte tokenizer usable for HTTP input; the oracle cases * use the original 32 rows. No test executor or media adapter participates in these tests. */ -bool write_nemotron(const std::string& dir) { +bool write_nemotron(const std::string& dir, bool rerank = false) { json weights = nemotron_fixture("nemotron35.json")["weights"]; weights.update(nemotron_fixture("nemotron35_vision.json")["weights"]); + if (rerank) + weights["language_model.score.weight"] = nemotron_fixture("nemotron35_rerank.json")["head"]; std::vector ts; for (auto it = weights.begin(); it != weights.end(); ++it) { auto shape = it.value()["shape"].get>(); @@ -2363,7 +2365,9 @@ bool write_nemotron(const std::string& dir) { bits.insert(bits.end(), original.begin() + row % 32 * 16, original.begin() + (row % 32 + 1) * 16); } - tiny::Tensor t{it.key(), "BF16", shape, {}}; + const std::string key = + (rerank && it.key() != "language_model.score.weight" ? "model." : "") + it.key(); + tiny::Tensor t{key, "BF16", shape, {}}; t.bytes.resize(bits.size() * 2); std::memcpy(t.bytes.data(), bits.data(), t.bytes.size()); ts.push_back(std::move(t)); @@ -2416,6 +2420,11 @@ bool write_nemotron(const std::string& dir) { {"multimodal_projector_bias", false}, {"projector_hidden_act", "gelu"}, {"vision_feature_layer", -1}}; + if (rerank) { + config["architectures"] = {"Mistral3ForSequenceClassification"}; + config["pooling"] = "avg"; + config["text_config"]["pooling"] = "avg"; + } json tok = json::parse(tiny::tokenizer_json()); json vocab = json::object(); for (int c = 0; c < 256; ++c) @@ -2862,4 +2871,213 @@ TEST(nemotron35_real_weights_match_the_offline_transformers_reference) { REQUIRE(tiny::write_text(output, s.output())); } +TEST(nemotron35_rerank_endpoint_loads_the_native_head_and_returns_text_image_scores) { + tiny::TempDir d("e2e_nemotron_rerank"); + REQUIRE(d.ok()); + REQUIRE(write_nemotron(d.path, true)); + const auto fixture = nemotron_fixture("nemotron35_rerank.json"); + const auto vision = nemotron_fixture("nemotron35_vision.json"); + for (const char* kernels : nemotron_kernels()) { +#if !defined(__x86_64__) + if (std::string(kernels) == "libavx") + continue; +#endif + Server s; + auto args = nemotron_args; + args.insert(args.end(), {"--kernels", kernels}); + if (!s.start(d.path, args, nemotron_env())) { + fprintf(stderr, " reranker startup log:\n%s\n", s.output().c_str()); + REQUIRE(false); + } + for (const auto& c : fixture["http"]) { + const bool image = !c["image"].is_null(); + if (image && !rad::mm::decoder_available()) + continue; + json doc = c["document"]; + if (image) { + json parts = json::array(); + if (!doc.is_null()) + parts.push_back({{"type", "text"}, {"text", doc}}); + parts.push_back(nemotron_image(vision["images"][c["image"].get()])); + doc = {{"content", parts}}; + } + const json body = {{"query", c["query"]}, {"documents", json::array({doc})}}; + int status = 0; + const auto reply = post(s.port, "/rerank", body, &status); + if (status != 200) + fprintf(stderr, " rerank HTTP %d: %s\n", status, reply.dump().c_str()); + REQUIRE_EQ(status, 200); + REQUIRE_EQ(reply["results"].size(), (size_t)1); + const double actual = reply["results"][0]["relevance_score"]; + CHECK_NEAR(actual, c["scores"][0].get(), .01); + CHECK_EQ(reply["usage"]["prompt_tokens"].get(), + c["inputs"][0]["tokens"].size()); + CHECK_EQ(reply["results"][0]["index"].get(), 0); + json batch = body; + batch["documents"] = json::array({doc, doc, doc}); + const auto many = post(s.port, "/v1/rerank", batch, &status); + REQUIRE_EQ(status, 200); + REQUIRE_EQ(many["results"].size(), (size_t)3); + for (int i = 0; i < 3; ++i) { + CHECK_EQ(many["results"][i]["index"].get(), i); + CHECK_NEAR(many["results"][i]["relevance_score"].get(), actual, 1e-5); + } + } + int status = 0; + post(s.port, "/v1/embeddings", {{"input", "A"}}, &status); + CHECK_EQ(status, 501); + const auto valid = json({{"query", "C"}, {"documents", {"A"}}}); + post(s.port, "/rerank", {{"query", "C"}, {"documents", {"A"}}, {"use_activation", true}}, + &status); + CHECK_EQ(status, 400); + post(s.port, "/rerank", valid, &status); + CHECK_EQ(status, 200); + REQUIRE_EQ(s.stop(), 0); + } +} + +TEST(nemotron35_rerank_real_weights_match_native_scores_and_rankings) { + const char* path = std::getenv("RAD_NEMOTRON_RERANK_REAL_FIXTURE"); + if (!path || !*path) + SKIP("set RAD_NEMOTRON_RERANK_REAL_FIXTURE for pinned native weights"); + const auto fixture = json::parse(tiny::read_text(path)); + const auto validation = fixture["validation"]; + for (const char* kernels : nemotron_kernels()) { +#if !defined(__x86_64__) + if (std::string(kernels) == "libavx") + continue; +#endif + if (!nemotron_device() && std::string(kernels) != "libavx") + continue; + std::vector args = {"--max-model-len", + validation["context"].dump(), + "--max-num-batched-tokens", + validation["batch_tokens"].dump(), + "--max-num-seqs", + "4", + "--mm-max-patches", + validation["patches"].dump(), + "--kernels", + kernels}; + Server s; + const std::string checkpoint = fixture["checkpoint"]; + auto env = nemotron_env(); + env.insert(env.end(), {"RADIANCE_HOST_VRAM_MIB=24576", "OMP_NUM_THREADS=4"}); + if (!s.start(checkpoint, args, env)) { + fprintf(stderr, " real reranker startup log:\n%s\n", s.output().c_str()); + REQUIRE(false); + } + std::vector actual; + double maximum = 0, squared = 0; + for (const auto& c : fixture["cases"]) { + int status = 0; + const auto reply = post(s.port, "/rerank", c["request"], &status); + if (status != 200) + fprintf(stderr, " rerank HTTP %d: %s\n", status, reply.dump().c_str()); + REQUIRE_EQ(status, 200); + REQUIRE_EQ(reply["results"].size(), (size_t)1); + const double score = reply["results"][0]["relevance_score"]; + const double expected = c["score"]; + actual.push_back(score); + const double delta = std::abs(score - expected); + maximum = std::max(maximum, delta); + squared += delta * delta; + CHECK(std::isfinite(score)); + CHECK(delta <= .05); + CHECK_EQ(reply["usage"]["prompt_tokens"].get(), c["tokens"].size()); + fprintf(stderr, " %s native=%.9g actual=%.9g error=%.9g\n", + c["name"].get().c_str(), expected, score, delta); + } + CHECK(std::sqrt(squared / actual.size()) <= .02); + const auto stats = [&]() { + Call c; + std::string body; + if (!c.send(s.port, "GET", "/stats", "") || c.read(&body) != 200) + return json(); + return json::parse(body); + }; + for (const auto& group : fixture["ranking_groups"]) { + const auto indices = group["cases"].get>(); + json body = fixture["cases"][indices[0]]["request"]; + body["documents"] = json::array(); + for (int i : indices) + body["documents"].push_back(fixture["cases"][i]["request"]["documents"][0]); + int status = 0; + const auto before = stats(); + const double tokens_before = metric(s.port, "radiance:prefill_tokens_total"); + const auto batch = post(s.port, "/v1/rerank", body, &status); + REQUIRE_EQ(status, 200); + REQUIRE_EQ(batch["results"].size(), indices.size()); + const auto after = stats(); + REQUIRE(before.is_object() && after.is_object()); + const int64_t steps = after["steps"].get() - before["steps"].get(); + // Ready text can run while image documents wait for their encoder pass. + CHECK_EQ(steps, group.value("steps", (int64_t)1)); + CHECK_EQ(after["total_requests"].get() - + before["total_requests"].get(), + (int64_t)indices.size()); + CHECK_EQ(metric(s.port, "radiance:prefill_tokens_total") - tokens_before, + batch["usage"]["prompt_tokens"].get()); + fprintf(stderr, + " %s: %zu pairs completed in %lld whole-input step(s), %lld tokens\n", + group["language"].get().c_str(), indices.size(), (long long)steps, + batch["usage"]["prompt_tokens"].get()); + for (const auto& row : batch["results"]) { + const int i = row["index"]; + REQUIRE(i >= 0 && (size_t)i < indices.size()); + CHECK_NEAR(row["relevance_score"].get(), actual[indices[i]], 1e-5); + } + for (int a : indices) + for (int b : indices) { + const double margin = fixture["cases"][a]["score"].get() - + fixture["cases"][b]["score"].get(); + if (margin > .10) + CHECK(actual[a] > actual[b]); + } + } + if (nemotron_device()) { + // Repeated geometries with changed contents exercise recording, audit and playback; + // no model-specific replay disable or debug synchronization changes the pass. + for (int repeat = 0; repeat < 6; ++repeat) + for (int i : {0, 1, 12, 13}) { + int status = 0; + const auto reply = + post(s.port, "/rerank", fixture["cases"][i]["request"], &status); + REQUIRE_EQ(status, 200); + CHECK_NEAR(reply["results"][0]["relevance_score"].get(), actual[i], + 1e-5); + } + Call abandoned; + REQUIRE( + abandoned.send(s.port, "POST", "/rerank", fixture["cases"][11]["request"].dump())); + ::close(abandoned.fd); + abandoned.fd = -1; + int status = 0; + const auto recovered = post(s.port, "/rerank", fixture["cases"][0]["request"], &status); + REQUIRE_EQ(status, 200); + CHECK_NEAR(recovered["results"][0]["relevance_score"].get(), actual[0], 1e-5); + } + const auto final = stats(); + if (nemotron_device()) { + REQUIRE(final.contains("passes")); + CHECK(final["passes"]["recorded"].get() > 0); + CHECK(final["passes"]["audited"].get() > 0); + CHECK(final["passes"]["played"].get() > 0); + fprintf(stderr, " replay counters: %s\n", final["passes"].dump().c_str()); + } + if (const char* output = std::getenv("RAD_NEMOTRON_RERANK_OUTPUT")) + REQUIRE(tiny::write_text(output, json({{"scores", actual}, + {"stats", final}, + {"max_abs_error", maximum}, + {"RMSE", std::sqrt(squared / actual.size())}}) + .dump(2) + + "\n")); + fprintf(stderr, " native rerank maxAbs=%.9g RMSE=%.9g\n", maximum, + std::sqrt(squared / actual.size())); + REQUIRE_EQ(s.stop(), 0); + if (const char* output = std::getenv("RAD_NEMOTRON_RERANK_SERVER_LOG")) + REQUIRE(tiny::write_text(output, s.output())); + } +} + RAD_TEST_MAIN() diff --git a/tests/mknemotron35rerankgolden.py b/tests/mknemotron35rerankgolden.py new file mode 100644 index 00000000..5f93b736 --- /dev/null +++ b/tests/mknemotron35rerankgolden.py @@ -0,0 +1,243 @@ +"""Offline tiny reranker oracle; never run by CMake/CTest. + +CPU torch, transformers==5.20.0 and Jinja2. Reuses the independently stored text/vision +weights and the pinned native reranker template; only the new tiny head is generated. +""" + +import json +from pathlib import Path + +import jinja2 +import torch +import transformers +from transformers import ( + Ministral3Config, + Mistral3Config, + Mistral3Model, + PixtralVisionConfig, +) + +root = Path(__file__).parent / "data/golden" +text = json.loads((root / "nemotron35.json").read_text()) +vision = json.loads((root / "nemotron35_vision.json").read_text()) +mm = json.loads((root / "nemotron35_multimodal.json").read_text()) +torch.set_num_threads(1) +tc = Ministral3Config( + hidden_size=16, + intermediate_size=32, + num_hidden_layers=2, + num_attention_heads=4, + num_key_value_heads=1, + head_dim=128, + vocab_size=320, + rms_norm_eps=1e-5, + is_causal=False, + use_cache=False, + rope_parameters={ + "rope_type": "yarn", + "rope_theta": 1e6, + "factor": 16.0, + "original_max_position_embeddings": 16384, + "beta_fast": 32.0, + "beta_slow": 1.0, + "mscale": 1.0, + "mscale_all_dim": 1.0, + "llama_4_scaling_beta": 0.1, + }, +) +vc = PixtralVisionConfig( + hidden_size=64, + intermediate_size=96, + num_hidden_layers=2, + num_attention_heads=1, + patch_size=14, + image_size=1540, + hidden_act="silu", + rope_parameters={"rope_type": "axial", "rope_theta": 10000.0}, +) +config = Mistral3Config( + text_config=tc, + vision_config=vc, + spatial_merge_size=2, + image_token_index=10, + multimodal_projector_bias=False, + projector_hidden_act="gelu", + vision_feature_layer=-1, + is_causal=False, +) +model = Mistral3Model(config).eval() +frequencies = {n: b.clone() for n, b in model.named_buffers()} +model.to(torch.bfloat16) +for n, b in frequencies.items(): + parent, attr = n.rsplit(".", 1) + setattr(model.get_submodule(parent), attr, b) +model.set_attn_implementation("eager") +state = { + n: torch.tensor(w["bf16"], dtype=torch.uint16) + .view(torch.bfloat16) + .reshape(w["shape"]) + for n, w in (text["weights"] | vision["weights"]).items() +} +state["language_model.embed_tokens.weight"] = state[ + "language_model.embed_tokens.weight" +].repeat(10, 1) +model.load_state_dict(state, strict=True) +torch.manual_seed(3508) +head = (torch.randn(1, 16) * 0.2).to(torch.bfloat16) + + +def pixels(index): + image = vision["images"][index] + h, w = image["size"] + patches = torch.tensor(image["patches"], dtype=torch.uint16).view(torch.bfloat16) + return ( + patches.reshape(h // 14, w // 14, 3, 14, 14) + .permute(2, 0, 3, 1, 4) + .reshape(3, h, w) + ) + + +def score(inputs, offsets=None): + length = max(len(x["tokens"]) for x in inputs) + ids = torch.full((len(inputs), length), 11, dtype=torch.long) + mask = torch.zeros_like(ids) + positions = torch.arange(length)[None].expand(len(inputs), -1).clone() + images = [] + for i, x in enumerate(inputs): + ids[i, : len(x["tokens"])] = torch.tensor(x["tokens"]) + mask[i, : len(x["tokens"])] = 1 + if offsets: + positions[i] += offsets[i] + images.extend(pixels(p["image"]) for p in x["placements"]) + kw = {} + if images: + sizes = torch.tensor([list(x.shape[1:]) for x in images]) + h, w = sizes.max(0).values.tolist() + kw = { + "pixel_values": torch.stack( + [ + torch.nn.functional.pad(x, (0, w - x.shape[2], 0, h - x.shape[1])) + for x in images + ] + ), + "image_sizes": sizes, + } + with torch.inference_mode(): + hidden = model( + input_ids=ids, + attention_mask=mask, + position_ids=positions, + use_cache=False, + **kw, + ).last_hidden_state + pooled = ( + hidden.masked_fill(~mask[..., None].bool(), 0).sum(1) / mask.sum(1)[:, None] + ) + return ( + torch.nn.functional.linear(pooled.float(), head.float()).flatten().tolist() + ) + + +cases = [] +for c in text["cases"]: + inputs = [{"tokens": x, "placements": []} for x in c["inputs"]] + cases.append( + { + **c, + "scores": score(inputs, c["offsets"]), + "head_only_scores": torch.nn.functional.linear( + torch.tensor(c["pooled"]), head.float() + ) + .flatten() + .tolist(), + } + ) +multimodal = [] +for c in mm["cases"]: + if c["name"] in ["image_only", "image_text", "text_and_image_batch"]: + multimodal.append({**c, "scores": score(c["inputs"])}) +env = jinja2.Environment() + + +def fail(s): + raise ValueError(s) + + +env.globals["raise_exception"] = fail +template = env.from_string( + (root.parent / "chat/nemotron35/rerank-template.jinja").read_text() +) +letter_ids = dict(zip("ABCDEF", [3, 4, 7, 8, 9, 6])) + + +def encode(s): + return [5 if b == 32 else letter_ids.get(chr(b), 32 + b) for b in s.encode("utf-8")] + + +http = [] +for name, q, doc, image in [ + ("text", "C", "A", None), + ("controls", "[IMG] ", "CDF", None), + ("image", "C", None, 1), + ("image_text", "C", "CDF", 2), + ("image_unicode_whitespace", "C", "CDF\u00a0\t\u3000", 2), +]: + content = ( + doc + if image is None + else ([{"type": "text", "text": doc}] if doc else []) + [{"type": "image"}] + ) + rendered = template.render( + messages=[ + {"role": "query", "content": q}, + {"role": "document", "content": content}, + ] + ) + tokens = [] + placements = [] + parts = rendered.split("[IMG]") if image is not None else [rendered] + for i, part in enumerate(parts): + if i: + placements.append({"image": image, "tok": len(tokens)}) + tokens.extend(vision["images"][image]["expand"]) + tokens.extend(encode(part)) + x = {"tokens": tokens, "placements": placements} + http.append( + { + "name": name, + "query": q, + "document": doc, + "image": image, + "rendered": rendered, + "inputs": [x], + "scores": score([x]), + } + ) +# Independent component data explicitly exercises the two BF16 roundings, including pitches/tails. +h = torch.randn(10, 7).to(torch.bfloat16) +cu = [0, 3, 10] +means = torch.stack([(h[b:e].sum(0) / (e - b)) for b, e in zip(cu, cu[1:])]) +result = { + "provenance": { + "transformers": transformers.__version__, + "torch": torch.__version__, + "seed": 3508, + "attention": "eager", + "dtype": "bfloat16", + "head_arithmetic": "float32", + "template_revision": "f88f8d9104726747791283ab156d2fcdb29e90a7", + }, + "head": {"shape": [1, 16], "bf16": head.flatten().view(torch.uint16).tolist()}, + "cases": cases, + "multimodal": multimodal, + "http": http, + "pool": { + "shape": [10, 7], + "bf16": h.flatten().view(torch.uint16).tolist(), + "cu": cu, + "expected": means.flatten().view(torch.uint16).tolist(), + }, +} +path = root / "nemotron35_rerank.json" +path.write_text(json.dumps(result, separators=(",", ":")) + "\n") +print(path, path.stat().st_size) diff --git a/tests/mknemotron35rerankrealreference.py b/tests/mknemotron35rerankrealreference.py new file mode 100644 index 00000000..b52edacf --- /dev/null +++ b/tests/mknemotron35rerankrealreference.py @@ -0,0 +1,269 @@ +"""Offline pinned-native reranker CPU oracle; never run by CMake or CTest. + +Usage: python tests/mknemotron35rerankrealreference.py CHECKPOINT OUTPUT_JSON +Requires CPU torch 2.14.1, transformers 5.20.0 and Pillow 13. No network or remote code. +The built-in Mistral3Model loads the native backbone; the audited 8 KiB native score +head is read separately and applied exactly as NVIDIA's model.py specifies. Download +revision f88f8d9104726747791283ab156d2fcdb29e90a7. A local asset-manifest.json is +optional; otherwise standard Hugging Face metadata records the revision when available. +""" + +import argparse +import base64 +import hashlib +import importlib +import io +import json +from pathlib import Path + +import PIL +import torch +import transformers +from PIL import Image +from safetensors import safe_open +from transformers import AutoModel, AutoTokenizer, PixtralProcessor +from transformers.models.pixtral.image_processing_pil_pixtral import ( + PixtralImageProcessorPil, +) + +p = argparse.ArgumentParser(description=__doc__) +p.add_argument("checkpoint", type=Path) +p.add_argument("output", type=Path) +p.add_argument("--threads", type=int, default=4) +p.add_argument("--sdpa-audit", action="store_true") +a = p.parse_args() +torch.set_num_threads(a.threads) +checkpoint = a.checkpoint.resolve() +metadata = (checkpoint / ".cache/huggingface/download").glob( + "model-*.safetensors.metadata" +) +revisions = {path.read_text().splitlines()[0] for path in metadata} +if checkpoint.parent.name == "snapshots": + revisions.add(checkpoint.name) +asset_manifest = checkpoint / "asset-manifest.json" +if asset_manifest.exists(): + assets = json.loads(asset_manifest.read_text()) + for name, entry in assets["files"].items(): + digest = hashlib.file_digest( + (checkpoint / name).open("rb"), "sha256" + ).hexdigest() + if digest != entry["sha256"]: + raise ValueError("Asset hash mismatch: " + name) + revisions.add(assets["revision"]) +if revisions and revisions != {"f88f8d9104726747791283ab156d2fcdb29e90a7"}: + raise ValueError("Expected the pinned reranker revision, found: " + str(revisions)) +tokenizer = AutoTokenizer.from_pretrained( + checkpoint, local_files_only=True, trust_remote_code=False +) +processor = PixtralProcessor( + tokenizer=tokenizer, + image_processor=PixtralImageProcessorPil( + patch_size=14, size={"longest_edge": 1120} + ), + patch_size=14, + spatial_merge_size=2, + chat_template=(checkpoint / "chat_template.jinja").read_text(), +) +index = json.loads((checkpoint / "model.safetensors.index.json").read_text())[ + "weight_map" +] +with safe_open(checkpoint / index["language_model.score.weight"], framework="pt") as f: + head = f.get_tensor("language_model.score.weight").float() +assert head.shape == (1, 4096) +print("Loading pinned local backbone; remote code disabled", flush=True) +model, loading = AutoModel.from_pretrained( + checkpoint, + local_files_only=True, + dtype=torch.bfloat16, + trust_remote_code=False, + attn_implementation="eager", + output_loading_info=True, +) +assert not loading.get("missing_keys"), loading +assert not loading.get("mismatched_keys"), loading +assert all("score.weight" in k for k in loading.get("unexpected_keys", [])), loading +loading = json.loads(json.dumps(loading, default=list)) +model.eval() + + +def picture(w, h, seed): + data = bytes( + (x * 17 + y * 31 + c * 71 + seed) % 256 + for y in range(h) + for x in range(w) + for c in range(3) + ) + im = Image.frombytes("RGB", (w, h), data) + out = io.BytesIO() + im.save(out, format="PNG") + return im, { + "type": "image_url", + "image_url": { + "url": "data:image/png;base64," + base64.b64encode(out.getvalue()).decode() + }, + } + + +cases = [] +groups = [] +for language, q, docs in [ + ( + "en", + "Where can I borrow books for free?", + [ + "A public library lends books to readers without charging a fee.", + "The football team won its match with two goals.", + "A bookshop sells novels and maps to paying customers.", + ], + ), + ( + "es", + "¿Dónde puedo tomar libros prestados gratis?", + [ + "La biblioteca pública presta libros a los lectores sin cobrar.", + "El equipo de fútbol ganó el partido con dos goles.", + "Una librería vende novelas y mapas a sus clientes.", + ], + ), + ( + "ja", + "無料で本を借りられる場所はどこですか?", + [ + "公共図書館では、読者は無料で本を借りることができます。", + "サッカーチームは二得点で試合に勝ちました。", + "書店では小説や地図を購入できます。", + ], + ), +]: + indices = [] + for j, doc in enumerate(docs): + indices.append(len(cases)) + cases.append((f"{language}_{j}", q, doc, None, None)) + groups.append({"language": language, "cases": indices}) +cases.extend( + [ + ( + "literal_controls", + "What does [IMG] <__media__> mean?", + "Documento en español: [IMG] <__media__> 東京", + None, + None, + ), + ("empty_document", "What does this document describe?", "", None, None), + ( + "longer_text", + "Where can I borrow books for free?", + "The public library contains science books and historical maps. " * 48, + None, + None, + ), + ] +) +image_cases = [] +for name, w, h, seed, doc in [ + ("image_only", 56, 28, 19, None), + ("image_text", 113, 81, 37, "A coloured pattern."), + ("medium_image_text", 224, 112, 59, "A colourful document page."), +]: + im, part = picture(w, h, seed) + image_cases.append(len(cases)) + cases.append((name, "What does this document describe?", doc, im, part)) +groups.extend( + [ + {"language": "images", "cases": image_cases}, + {"language": "mixed", "cases": [10, *image_cases[:2]], "steps": 2}, + ] +) +results = [] +for name, query, doc, im, part in cases: + content = ( + doc + if im is None + else ([{"type": "text", "text": doc}] if doc is not None else []) + + [{"type": "image", "image": im}] + ) + messages = [ + {"role": "query", "content": [{"type": "text", "text": query}]}, + {"role": "document", "content": content}, + ] + inputs = processor.apply_chat_template( + messages, + tokenize=True, + add_generation_prompt=False, + return_dict=True, + return_tensors="pt", + ) + if "pixel_values" in inputs: + inputs["pixel_values"] = inputs["pixel_values"].to(torch.bfloat16) + scores = {} + for attention in ["eager", "sdpa"] if a.sdpa_audit else ["eager"]: + model.set_attn_implementation(attention) + with torch.inference_mode(): + hidden = model(**inputs, use_cache=False).last_hidden_state + mask = inputs["attention_mask"] + pooled = ( + hidden.masked_fill(~mask[..., None].bool(), 0).sum(1) + / mask.sum(1)[:, None] + ) + scores[attention] = torch.nn.functional.linear(pooled.float(), head).item() + wire = ( + doc + if im is None + else { + "content": ([{"type": "text", "text": doc}] if doc is not None else []) + + [part] + } + ) + results.append( + { + "name": name, + "request": {"query": query, "documents": [wire]}, + "tokens": inputs["input_ids"][0].tolist(), + "score": scores["eager"], + "native_attention_scores": scores, + } + ) + print(name, len(results[-1]["tokens"]), "tokens", scores, flush=True) + a.output.write_text( + json.dumps( + { + "checkpoint": str(checkpoint), + "provenance": { + "model_revision": next(iter(revisions)) if revisions else None, + "torch": torch.__version__, + "transformers": transformers.__version__, + "pillow": PIL.__version__, + "dtype": "bfloat16", + "head_arithmetic": "float32", + "attention": "eager", + "processor": "PIL", + "loading_info": loading, + }, + "ranking_groups": groups, + "cases": results, + }, + indent=2, + ) + + "\n" + ) +sources = {} +for name in [ + "transformers.models.ministral3.modeling_ministral3", + "transformers.models.mistral3.modeling_mistral3", + "transformers.models.pixtral.modeling_pixtral", + "transformers.models.pixtral.image_processing_pil_pixtral", +]: + path = Path(importlib.import_module(name).__file__) + sources[name] = hashlib.sha256(path.read_bytes()).hexdigest() +out = json.loads(a.output.read_text()) +out["provenance"]["sources"] = sources +out["provenance"]["asset_manifest_sha256"] = ( + hashlib.sha256(asset_manifest.read_bytes()).hexdigest() + if asset_manifest.exists() + else None +) +maximum = max(len(c["tokens"]) for c in results) +context = max(128, 1 << (maximum - 1).bit_length()) +out["validation"] = {"context": context, "batch_tokens": 2 * context, "patches": 128} +a.output.write_text(json.dumps(out, indent=2) + "\n") +print(a.output, flush=True) diff --git a/tests/nemotron35_device_test.cpp b/tests/nemotron35_device_test.cpp index d2a184c7..1cd03718 100644 --- a/tests/nemotron35_device_test.cpp +++ b/tests/nemotron35_device_test.cpp @@ -329,4 +329,36 @@ TEST(nemotron35_device_patch_projection_588_tail_and_pitched_rows) { {pi("M", 128), pi("N", N), pi("K", 588), ps("dtype", "bf16")}, 2, 128, true); } } + +TEST(nemotron35_device_rerank_pool_bf16_sum_rounding_ragged_strides_and_tails) { + if (!device()) + SKIP("explicit R9700 card run required"); + for (int N : {7, 37, 257, 4096}) { + Buffer x(RAD_BF16, 10, N, 2 * N + 3, 2), y(RAD_BF16, 3, N, 2 * N + 7, 2); + x.fill(3508); + auto cu = Buffer::ids({0, 3, 9, 10}); + compare("seg_mean_bf16_sum", {&x, cu.get(), &y}, + {pi("M", 64), pi("n", N), ps("dtype", "bf16")}, 2, 0, true); + } +} + +TEST(nemotron35_device_rerank_pool_full_context_and_sequence_grid_boundary) { + if (!device()) + SKIP("explicit R9700 card run required"); + for (bool many : {false, true}) { + const int M = many ? 65539 : 32768, S = many ? M : 3, N = 7; + Buffer x(RAD_BF16, M, N, 11), y(RAD_BF16, S, N, 13); + x.fill(3509); + std::vector lengths = {0, 257, 16384, M}; + if (many) { + lengths.resize(M + 1); + for (int i = 0; i <= M; ++i) + lengths[i] = i; + } + auto cu = Buffer::ids(lengths); + compare("seg_mean_bf16_sum", {&x, cu.get(), &y}, + {pi("M", M), pi("n", N), ps("dtype", "bf16")}, 2, 0, true); + } +} + RAD_TEST_MAIN() diff --git a/tests/nemotron35_test.cpp b/tests/nemotron35_test.cpp index 38e004f9..68f6584c 100644 --- a/tests/nemotron35_test.cpp +++ b/tests/nemotron35_test.cpp @@ -201,8 +201,13 @@ std::map> execute_graph(const Kernels& kernels, return result; } -std::vector execute(const Kernels& kernels, const json& source, const json& test) { +std::vector execute(const Kernels& kernels, const json& source, const json& test, + bool rerank = false) { auto mk = meta(); + if (rerank) + mk.set("architectures", "Mistral3ForSequenceClassification") + .set("pooling", "avg") + .set("text_config.pooling", "avg"); auto ctx = build_ctx(); ctx.max_tok = 32; ctx.max_seqs = 4; @@ -230,8 +235,12 @@ std::vector execute(const Kernels& kernels, const json& source, const jso RadCtx c{.b = &b, .batch = &batch}; nemotron35_embed::step(&c, &batch); if (!c.step_fail.empty()) throw std::runtime_error(c.step_fail); - auto result = execute_graph(kernels, source, b, c, batch).at(b.bufs[b.pooled - 1].name); - result.resize((size_t)batch.n_seq * 16); + json mapped = json::object(); + for (const auto& entry : source.items()) + mapped[(rerank && entry.key() != "language_model.score.weight" ? "model." : "") + + entry.key()] = entry.value(); + auto result = execute_graph(kernels, mapped, b, c, batch).at(b.bufs[b.pooled - 1].name); + result.resize((size_t)batch.n_seq * (rerank ? 1 : 16)); return result; } @@ -399,10 +408,10 @@ struct InputTokenizer final : rad::server::ITokenizer { } }; struct InputEmbedder final : rad::server::IEmbedder { - bool selected = true; + bool selected = true, rerank = false; int64_t limit = 32768; mutable MetaKV config = vision_meta(); - int64_t dim() const override { return 16; } + int64_t dim() const override { return rerank ? 1 : 16; } int64_t max_input() const override { return limit; } const RadModelMeta* metadata() const override { return selected ? config.meta() : nullptr; } bool prompt(const std::string& name, std::string* out) const override { @@ -434,7 +443,8 @@ struct InputImages final : rad::server::IMultimodal { } }; -std::vector execute_multimodal(const Kernels& kernels, const json& test) { +std::vector execute_multimodal(const Kernels& kernels, const json& test, + bool rerank = false) { const auto vision = golden("nemotron35_vision.json"); auto processor = image_processor(); json indices = json::array(); @@ -462,6 +472,10 @@ std::vector execute_multimodal(const Kernels& kernels, const json& test) prompts.push_back(std::move(media)); } auto mk = vision_meta(); + if (rerank) + mk.set("architectures", "Mistral3ForSequenceClassification") + .set("pooling", "avg") + .set("text_config.pooling", "avg"); auto ctx = build_ctx(); ctx.max_tok = 64; ctx.max_seqs = 4; @@ -507,8 +521,14 @@ std::vector execute_multimodal(const Kernels& kernels, const json& test) auto weights = golden().at("weights"); for (const auto& entry : vision["weights"].items()) weights[entry.key()] = entry.value(); - auto out = execute_graph(kernels, weights, b, c, batch).at("pooled"); - out.resize((size_t)batch.n_seq * 16); + if (rerank) + weights["language_model.score.weight"] = golden("nemotron35_rerank.json")["head"]; + json mapped = json::object(); + for (const auto& entry : weights.items()) + mapped[(rerank && entry.key() != "language_model.score.weight" ? "model." : "") + + entry.key()] = entry.value(); + auto out = execute_graph(kernels, mapped, b, c, batch).at("pooled"); + out.resize((size_t)batch.n_seq * (rerank ? 1 : 16)); return out; } } // namespace @@ -976,7 +996,7 @@ TEST(nemotron35_pixtral_rejects_incomplete_encoder_passes_and_unsupported_proces nemotron35_embed::Pixtral vision; rad::arch::Names nm(""); RadBuilder b; - REQUIRE_EQ(vision.declare(&b, mk.meta(), &ctx, nm, 16, 2), RAD_OK); + REQUIRE_EQ(vision.declare(&b, mk.meta(), &ctx, nm, nm, 16, 2), RAD_OK); int32_t hh = 2, ww = 3; uint16_t pixel = 0; int32_t coord[16]{}, cu[] = {0, 4}; @@ -1276,4 +1296,194 @@ TEST(nemotron35_image_injection_rejects_missing_or_out_of_bounds_batch_fields_be } } +TEST(nemotron35_reranker_declares_a_scalar_head_without_changing_embedding_pooling) { + auto mk = vision_meta(true); + mk.set("architectures", "Mistral3ForSequenceClassification") + .set("pooling", "avg") + .set("text_config.pooling", "avg"); + auto ctx = build_ctx(); + ctx.max_seqs = 16; + ctx.max_tok = 131072; + ctx.max_enc_patches = 64; + RadBuilder b; + CHECK_OK(nemotron35_embed::declare(&b, mk.meta(), &ctx)); + REQUIRE(b.pooled); + CHECK_EQ(b.bufs[b.pooled - 1].d.shape[1], 1); + CHECK_EQ(b.logits, (rad_buf)0); + CHECK(b.kv_groups.empty()); + CHECK_EQ(count_op(b, "seg_mean_bf16_sum"), 1); + CHECK_EQ(count_op(b, "seg_mean"), 0); + CHECK_EQ(count_op(b, "logits_gemm"), 1); + const auto* map = find_map(b, "score.weight"); + REQUIRE(map); + CHECK_EQ(map->src[0], std::string("language_model.score.weight")); + REQUIRE(find_map(b, "token_embd.weight")); + CHECK_EQ(find_map(b, "token_embd.weight")->src[0], + std::string("model.language_model.embed_tokens.weight")); + REQUIRE(find_map(b, "v.patch.weight")); + CHECK_EQ(find_map(b, "v.patch.weight")->src[0], + std::string("model.vision_tower.patch_conv.weight")); + CHECK(rad::server::nemotron35_rerank_meta(mk.meta())); + CHECK(!rad::server::nemotron35_retrieval_meta(mk.meta())); + RadBuilder quantized; + quantized.encs.emplace_back("score.weight", rad_enc_plain(RAD_I8)); + CHECK_EQ(nemotron35_embed::declare(&quantized, mk.meta(), &ctx), RAD_E_UNSUPPORTED); + auto plain = vision_meta(true); + RadBuilder embedding; + CHECK_OK(nemotron35_embed::declare(&embedding, plain.meta(), &ctx)); + CHECK_EQ(embedding.bufs[embedding.pooled - 1].d.shape[1], 4096); + CHECK_EQ(count_op(embedding, "seg_mean"), 1); + CHECK_EQ(count_op(embedding, "seg_mean_bf16_sum"), 0); + CHECK_EQ(count_op(embedding, "logits_gemm"), 0); + mk.set("pooling", "last"); + RadBuilder bad; + CHECK_EQ(nemotron35_embed::declare(&bad, mk.meta(), &ctx), RAD_E_UNSUPPORTED); +} + +TEST(nemotron35_reranker_scores_match_independent_native_text_and_image_oracles) { + const auto fixture = golden("nemotron35_rerank.json"); + auto weights = golden()["weights"]; + weights["language_model.score.weight"] = fixture["head"]; + for (const char* name : host_libraries()) { + Kernels kernels(name); + for (const auto& c : fixture["cases"]) { + const auto actual = execute(kernels, weights, c, true); + REQUIRE_EQ(actual.size(), c["scores"].size()); + for (size_t i = 0; i < actual.size(); ++i) + CHECK_NEAR(actual[i], c["scores"][i].get(), .01); + } + for (const auto& c : fixture["multimodal"]) { + const auto actual = execute_multimodal(kernels, c, true); + REQUIRE_EQ(actual.size(), c["scores"].size()); + for (size_t i = 0; i < actual.size(); ++i) + CHECK_NEAR(actual[i], c["scores"][i].get(), .01); + } + } +} + +TEST(nemotron35_reranker_pool_rounds_the_sum_before_dividing_and_preserves_pitches) { + const auto f = golden("nemotron35_rerank.json")["pool"]; + const auto bits = f["bf16"].get>(); + const auto want = f["expected"].get>(); + for (const char* name : host_libraries()) { + Kernels kernels(name); + std::vector x(10 * 9, 0x4321), y(2 * 10, 0x4321); + for (int r = 0; r < 10; ++r) + std::copy_n(bits.data() + r * 7, 7, x.data() + r * 9); + auto tx = tensor(x.data(), RAD_BF16, {10, 9}); + tx.shape[1] = 7; + auto ty = tensor(y.data(), RAD_BF16, {2, 10}); + ty.shape[1] = 7; + int32_t cu[] = {0, 3, 10}; + RadTensor ts[] = {tx, tensor(cu, RAD_I32, {3}), ty}; + RadParam ps[] = {RAD_INT("M", 64), RAD_INT("n", 7), RAD_STR("dtype", "bf16")}; + RadArgs a{}; + a.t = ts; + a.n_t = 3; + a.p = ps; + a.n_p = 3; + const auto* op = kernels.get("seg_mean_bf16_sum"); + CHECK_OK(op->launch(&a, nullptr)); + for (int r = 0; r < 2; ++r) + for (int i = 0; i < 10; ++i) + CHECK_EQ(y[r * 10 + i], i < 7 ? want[r * 7 + i] : (uint16_t)0x4321); + const auto before = y; + cu[1] = 0; + CHECK_EQ(op->launch(&a, nullptr), RAD_E_INVAL); + CHECK(y == before); + cu[1] = 11; + CHECK_EQ(op->launch(&a, nullptr), RAD_E_INVAL); + CHECK(y == before); + cu[1] = 3; + ts[0].stride[0] = INT64_MAX; + CHECK_EQ(op->launch(&a, nullptr), RAD_E_SHAPE); + CHECK(y == before); + ts[0] = tx; + ts[0].data = nullptr; + CHECK_EQ(op->launch(&a, nullptr), RAD_E_INVAL); + CHECK(y == before); + } +} + +TEST(nemotron35_reranker_parser_matches_the_native_pair_template_and_context_boundary) { + InputTokenizer tok; + InputEmbedder embed; + embed.rerank = true; + embed.config.set("architectures", "Mistral3ForSequenceClassification"); + InputImages images; + rad::server::OaiDeps deps; + deps.tok = &tok; + deps.embed = &embed; + deps.mm = &images; + rad::server::OaiLimits lim; + lim.max_ctx = 32768; + lim.allow_image = true; + for (const auto& c : golden("nemotron35_rerank.json")["http"]) { + json doc = c["document"]; + if (!c["image"].is_null()) { + json parts = json::array(); + if (!doc.is_null()) + parts.push_back({{"type", "text"}, {"text", doc}}); + const uint8_t byte = c["image"].get(); + parts.push_back( + {{"type", "image_url"}, + {"image_url", + {{"url", "data:image/png;base64," + rad::server::base64_encode(&byte, 1)}}}}); + doc = {{"content", parts}}; + } + const auto body = json({{"query", c["query"]}, {"documents", json::array({doc})}}).dump(); + rad::server::OaiRequest out; + rad::server::ApiError err; + CHECK_OK(rad::server::parse_rerank_request(body, deps, lim, &out, &err)); + REQUIRE_EQ(out.prompts.size(), (size_t)1); + CHECK_EQ(out.prompts[0].text, c["rendered"].get()); + CHECK(!tok.added); + const int64_t length = (int64_t)out.prompts[0].tokens.size(); + for (int delta : {-1, 0, 1}) { + auto bounded = lim; + bounded.max_ctx = length + delta; + rad::server::OaiRequest r; + const int rc = rad::server::parse_rerank_request(body, deps, bounded, &r, &err); + if (delta < 0) + CHECK_EQ(rc, RAD_E_INVAL); + else + CHECK_OK(rc); + } + rad::server::OaiRequest wrong; + CHECK_EQ(rad::server::parse_embeddings_request(R"({"input":"x"})", deps, lim, &wrong, &err), + RAD_E_UNSUPPORTED); + } +} + +TEST(nemotron35_reranker_head_keeps_the_native_fp32_score) { + const auto f = golden("nemotron35_rerank.json"); + auto head = f["head"]["bf16"].get>(); + for (const char* name : host_libraries()) { + Kernels kernels(name); + for (const auto& c : f["cases"]) { + std::vector pooled; + for (const auto& row : c["pooled"]) + for (const auto& v : row) + pooled.push_back(rad_f32_to_bf16(v.get())); + const int64_t M = (int64_t)c["pooled"].size(); + std::vector output((size_t)M, 0); + RadTensor ts[] = {tensor(pooled.data(), RAD_BF16, {M, 16}), + tensor(head.data(), RAD_BF16, {1, 16}), + tensor(output.data(), RAD_F32, {M, 1})}; + RadParam ps[] = {RAD_INT("M", M), RAD_INT("n_embd", 16), RAD_INT("n_vocab", 1), + RAD_STR("dtype", "bf16")}; + RadArgs a{}; + a.t = ts; + a.n_t = 3; + a.p = ps; + a.n_p = 4; + CHECK_OK(kernels.get("logits_gemm")->launch(&a, nullptr)); + for (int64_t i = 0; i < M; ++i) { + const double want = c["head_only_scores"][i]; + CHECK_NEAR(output[(size_t)i], want, 1e-5 + 1e-5 * std::abs(want)); + } + } + } +} + RAD_TEST_MAIN() diff --git a/tests/ref_test.cpp b/tests/ref_test.cpp index 31e97e0d..244314a4 100644 --- a/tests/ref_test.cpp +++ b/tests/ref_test.cpp @@ -968,6 +968,7 @@ TEST(op_vocabulary) { "mhc_pre", "mhc_pre_partial", "mhc_pre_finish", "mhc_post", "mhc_contract", "swiglu_clamped", "router_sigmoid_topk", "dsa_pool", "dsa_query", "dsa_score", "mla_attn", "mla_project", "gemm_nt_f32", "kda_update", "layernorm", "add", "mul", "mul_weight", "silu_mul", "gelu_mul", "act_mul", "seg_mean", + "seg_mean_bf16_sum", "pool_rows", "pool_cols", "relu", "clamp", "conv2d", "conv2d_unfold", "conv1d_dw", "rel_sinusoid", "seg_sinusoid", "attn_local_rel", "gelu", "silu", "sigmoid", "logit_softcap", "scale", @@ -9631,6 +9632,7 @@ std::vector geometries() { G("mul_weight", "M", 3, a.i("M", R).i("n", 8).s("dtype", "f32")), G("act_mul", "M", 3, a.i("M", R).i("n", 8).s("act", "silu").s("dtype", "f32")), G("seg_mean", "M", 6, a.i("M", R).i("n", 8).s("dtype", "f32").i("n_seq", 2)), + G("seg_mean_bf16_sum", "M", 6, a.i("M", R).i("n", 8).s("dtype", "bf16").i("n_seq", 2)), G("pool_rows", "M", 6, a.i("M", R).i("n", 8).i("k", 2).s("dtype", "f32")), G("pool_cols", "M", 6, a.i("M", R).i("n", 8).i("k", 2).s("dtype", "f32")), G("relu", "M", 3, a.i("M", R).i("n", 8).s("dtype", "f32")), diff --git a/tests/server_test.cpp b/tests/server_test.cpp index cf1f13f6..e184f40b 100644 --- a/tests/server_test.cpp +++ b/tests/server_test.cpp @@ -5,6 +5,7 @@ * streaming wire format deterministic. No port is bound; transport_test.cpp covers the socket. */ #include "server_fakes.h" +#include "rad_plugin.h" #include "lora/slots.h" #include "server/liveview.h" @@ -14,6 +15,7 @@ #include #include #include +#include #include /* ================================================================== parsing */ @@ -6159,4 +6161,108 @@ TEST(a_fault_in_a_realtime_session_ends_the_session_not_the_server) { CHECK_EQ(r.rig.srv->router().call("GET", "/health").status, 200); } +namespace { +struct RerankInfo final : IEmbedder { + const char* keys[6] = {"model_type", "text_config.model_type", "vision_config.model_type", + "is_causal", "text_config.is_causal", "architectures"}; + const char* values[6] = {"mistral3", "ministral3", "pixtral", + "0", "0", "Mistral3ForSequenceClassification"}; + RadModelMeta meta{}; + int64_t width = 1; + RerankInfo() { + meta.n_kv = 6; + meta.kv_key = keys; + meta.kv_val = values; + } + int64_t dim() const override { return width; } + int64_t max_input() const override { return 32768; } + const RadModelMeta* metadata() const override { return &meta; } +}; +} // namespace + +TEST(rerank_returns_raw_logits_stable_indices_top_n_and_all_pair_token_usage) { + RerankInfo info; + Fixture f(Fixture::Tweak{[&](ServerOptions& o, Deps& d) { + d.embed = &info; + o.max_ctx = 32768; + }}); + const auto caps = json::parse(f.get("/server_info").body)["capabilities"]; + CHECK(caps["rerank"].get()); + CHECK(!caps["embedding"].get()); + CHECK(!caps["chat"].get()); + f.sched.embedding = {-2.75f}; + for (const char* route : {"/rerank", "/v1/rerank"}) { + auto r = f.post(route, R"({"query":"q","documents":["short","a longer document"]})"); + f.sched.join_all(); + REQUIRE_EQ(r.status, 200); + const auto b = json::parse(r.body); + REQUIRE_EQ(b["results"].size(), (size_t)2); + CHECK_EQ(b["results"][0]["index"].get(), 0); + CHECK_EQ(b["results"][1]["index"].get(), 1); + CHECK_NEAR(b["results"][0]["relevance_score"].get(), -2.75, 0); + CHECK_EQ(b["results"][0]["document"]["text"].get(), "short"); + CHECK_EQ(b["usage"]["prompt_tokens"].get(), 2 * 19 + 5 + 17); + CHECK_EQ(f.srv->in_flight(), 0); + } + f.sched.embed_mark_length = true; + auto r = f.post("/rerank", R"({"query":"q","documents":["short","a longer document"], + "top_n":1,"return_documents":false,"use_activation":false})"); + f.sched.join_all(); + REQUIRE_EQ(r.status, 200); + const auto b = json::parse(r.body); + REQUIRE_EQ(b["results"].size(), (size_t)1); + CHECK_EQ(b["results"][0]["index"].get(), 1); + CHECK_EQ(b["results"][0]["relevance_score"].get(), 36); + CHECK(!b["results"][0].contains("document")); + CHECK_EQ(b["usage"]["total_tokens"].get(), 60); + CHECK_EQ(f.post("/v1/embeddings", R"({"input":"q"})").status, 501); +} + +TEST(rerank_refuses_invalid_pairs_unsupported_options_and_nonfinite_scores) { + RerankInfo info; + Fixture f(Fixture::Tweak{[&](ServerOptions&, Deps& d) { d.embed = &info; }}); + for (const std::string& body : + {R"({"query":"q","documents":[]})", R"({"query":1,"documents":["d"]})", + R"({"query":"q","documents":[1]})", R"({"query":"q","documents":["d"],"top_n":-1})", + R"({"query":"q","documents":["d"],"top_n":1.5})", + R"({"query":"q","documents":["d"],"top_n":18446744073709551615})", + R"({"query":"q","documents":["d"],"use_activation":true})", + R"({"query":"q","documents":["d"],"truncate_prompt_tokens":16})", + R"({"query":"q","documents":["d"],"instruction":"new instruction"})", + R"({"query":"q","documents":[{"content":[{"type":"image"},{"type":"image"}]}]})"}) + CHECK_EQ(f.post("/rerank", body).status, 400); + CHECK(f.sched.submitted.empty()); + f.sched.embedding = {std::numeric_limits::quiet_NaN()}; + CHECK_EQ(f.post("/rerank", R"({"query":"q","documents":["d"]})").status, 500); + f.sched.join_all(); + CHECK_EQ(f.srv->in_flight(), 0); + f.sched.embedding = {-3.25f}; + CHECK_EQ(f.post("/rerank", R"({"query":"q","documents":["d"]})").status, 200); + f.sched.join_all(); + info.width = 2; + CHECK_EQ(f.post("/rerank", R"({"query":"q","documents":["d"]})").status, 501); + Fixture generation; + CHECK_EQ(generation.post("/rerank", R"({"query":"q","documents":["d"]})").status, 501); +} + +TEST(rerank_pair_context_includes_prefixes_and_accepts_the_exact_boundary) { + RerankInfo info; + Fixture f(Fixture::Tweak{[&](ServerOptions& o, Deps& d) { + d.embed = &info; + o.max_ctx = 64; + }}); + f.sched.embedding = {.125f}; + for (int n : {44, 45, 46}) { + const std::string body = + json({{"query", "q"}, {"documents", {std::string(n, 'a')}}}).dump(); + auto r = f.post("/rerank", body); + CHECK_EQ(r.status, n <= 45 ? 200 : 400); + if (n > 45) + CHECK_EQ(json::parse(r.body)["error"]["code"].get(), + "context_length_exceeded"); + f.sched.join_all(); + } + CHECK_EQ(f.srv->in_flight(), 0); +} + RAD_TEST_MAIN()