Archived
nemotron 3.5 rerank 8b implementation
This commit is contained in:
1 parent
d773992abc
commit
74e7fddd79
35 files changed
+1788
-90
No files matched your search
@@ -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.
|
||||
@@ -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 -%}
|
||||
@@ -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,Line truncated
|
||||
+220
-2
@@ -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<tiny::Tensor> ts;
|
||||
for (auto it = weights.begin(); it != weights.end(); ++it) {
|
||||
auto shape = it.value()["shape"].get<std::vector<int64_t>>();
|
||||
@@ -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<size_t>()]));
|
||||
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<double>(), .01);
|
||||
CHECK_EQ(reply["usage"]["prompt_tokens"].get<size_t>(),
|
||||
c["inputs"][0]["tokens"].size());
|
||||
CHECK_EQ(reply["results"][0]["index"].get<int>(), 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<int>(), i);
|
||||
CHECK_NEAR(many["results"][i]["relevance_score"].get<double>(), 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<std::string> 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<double> 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<size_t>(), c["tokens"].size());
|
||||
fprintf(stderr, " %s native=%.9g actual=%.9g error=%.9g\n",
|
||||
c["name"].get<std::string>().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<std::vector<int>>();
|
||||
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<int64_t>() - before["steps"].get<int64_t>();
|
||||
// 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<int64_t>() -
|
||||
before["total_requests"].get<int64_t>(),
|
||||
(int64_t)indices.size());
|
||||
CHECK_EQ(metric(s.port, "radiance:prefill_tokens_total") - tokens_before,
|
||||
batch["usage"]["prompt_tokens"].get<double>());
|
||||
fprintf(stderr,
|
||||
" %s: %zu pairs completed in %lld whole-input step(s), %lld tokens\n",
|
||||
group["language"].get<std::string>().c_str(), indices.size(), (long long)steps,
|
||||
batch["usage"]["prompt_tokens"].get<long long>());
|
||||
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<double>(), actual[indices[i]], 1e-5);
|
||||
}
|
||||
for (int a : indices)
|
||||
for (int b : indices) {
|
||||
const double margin = fixture["cases"][a]["score"].get<double>() -
|
||||
fixture["cases"][b]["score"].get<double>();
|
||||
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<double>(), 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<double>(), actual[0], 1e-5);
|
||||
}
|
||||
const auto final = stats();
|
||||
if (nemotron_device()) {
|
||||
REQUIRE(final.contains("passes"));
|
||||
CHECK(final["passes"]["recorded"].get<int64_t>() > 0);
|
||||
CHECK(final["passes"]["audited"].get<int64_t>() > 0);
|
||||
CHECK(final["passes"]["played"].get<int64_t>() > 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()
|
||||
@@ -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] <A>", "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)
|
||||
@@ -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)
|
||||
@@ -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<int> 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()
|
||||
+219
-9
@@ -201,8 +201,13 @@ std::map<std::string, std::vector<float>> execute_graph(const Kernels& kernels,
|
||||
return result;
|
||||
}
|
||||
|
||||
std::vector<float> execute(const Kernels& kernels, const json& source, const json& test) {
|
||||
std::vector<float> 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<float> 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<float> execute_multimodal(const Kernels& kernels, const json& test) {
|
||||
std::vector<float> 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<float> 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<float> 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<float>(), .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<float>(), .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<std::vector<uint16_t>>();
|
||||
const auto want = f["expected"].get<std::vector<uint16_t>>();
|
||||
for (const char* name : host_libraries()) {
|
||||
Kernels kernels(name);
|
||||
std::vector<uint16_t> 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<uint8_t>();
|
||||
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<std::string>());
|
||||
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<std::vector<uint16_t>>();
|
||||
for (const char* name : host_libraries()) {
|
||||
Kernels kernels(name);
|
||||
for (const auto& c : f["cases"]) {
|
||||
std::vector<uint16_t> pooled;
|
||||
for (const auto& row : c["pooled"])
|
||||
for (const auto& v : row)
|
||||
pooled.push_back(rad_f32_to_bf16(v.get<float>()));
|
||||
const int64_t M = (int64_t)c["pooled"].size();
|
||||
std::vector<float> 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()
|
||||
@@ -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<Geo> 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")),
|
||||
|
||||
@@ -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 <condition_variable>
|
||||
#include <cstring>
|
||||
#include <deque>
|
||||
#include <limits>
|
||||
#include <random>
|
||||
|
||||
/* ================================================================== 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<bool>());
|
||||
CHECK(!caps["embedding"].get<bool>());
|
||||
CHECK(!caps["chat"].get<bool>());
|
||||
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<int>(), 0);
|
||||
CHECK_EQ(b["results"][1]["index"].get<int>(), 1);
|
||||
CHECK_NEAR(b["results"][0]["relevance_score"].get<float>(), -2.75, 0);
|
||||
CHECK_EQ(b["results"][0]["document"]["text"].get<std::string>(), "short");
|
||||
CHECK_EQ(b["usage"]["prompt_tokens"].get<int>(), 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<int>(), 1);
|
||||
CHECK_EQ(b["results"][0]["relevance_score"].get<int>(), 36);
|
||||
CHECK(!b["results"][0].contains("document"));
|
||||
CHECK_EQ(b["usage"]["total_tokens"].get<int>(), 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<float>::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<std::string>(),
|
||||
"context_length_exceeded");
|
||||
f.sched.join_all();
|
||||
}
|
||||
CHECK_EQ(f.srv->in_flight(), 0);
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
Reference in new issue
Block a user