diff --git a/core/server/admin.cpp b/core/server/admin.cpp index 85ad6ce1..87ed461f 100644 --- a/core/server/admin.cpp +++ b/core/server/admin.cpp @@ -399,6 +399,9 @@ json Server::capabilities() const { caps["image_edit"] = deps_.images != nullptr && deps_.images->info().max_refs > 0; caps["audio_generation"] = deps_.audio != nullptr; caps["video_generation"] = deps_.videos != nullptr; + /* The decision protocol /v1/systemone serves (ServerOptions::decision_type), so a proxy can + * route to a decision model without trying a generation; null when it serves none. */ + caps["decision"] = opt_.decision_type.empty() ? json(nullptr) : json(opt_.decision_type); /* What a video request may carry. */ if (deps_.videos) video_caps(caps, deps_.videos); /* The efforts a chat request may send, probed from the template at startup; null when it diff --git a/core/server/clef.cpp b/core/server/clef.cpp new file mode 100644 index 00000000..2da1c75a --- /dev/null +++ b/core/server/clef.cpp @@ -0,0 +1,261 @@ +/* clef.cpp -- clef's prompt, spans and answer (clef.h). + * + * Every string below is the release's own, from joint_schema_model.py: the system prompt, the + * state and schema framing, the field and option lines, and the noul defaults. The prompt is + * tokenised piece by piece and the ids concatenated, as encode_record does, because each span is + * the ids of one piece: BPE over the joined text could merge across a span's edge. + */ +#include "clef.h" + +#include + +#include +#include +#include + +namespace rad { +namespace server { + +namespace { + +const char* const kSystemPrompt = + "Read the complete state and schema. Decide every field jointly. Each answer " + "must be exactly one of that field's allowed options."; + +bool only_keys(const json& o, std::initializer_list allowed, const std::string& path, + ApiError* err) { + for (const auto& kv : o.items()) { + bool ok = false; + for (const char* k : allowed) ok = ok || kv.key() == k; + if (!ok) { + *err = err_unsupported(path + kv.key(), "not a field of a System One request"); + return false; + } + } + return true; +} + +/* question_options: each allowed option and its description (null for none). */ +int question_options(const std::string& path, const std::string& type, const json& criteria, + ClefQuestion* q, std::vector* descs, ApiError* err) { + if (type == "noul") { + json c = { { "true", "The proposition is true or the answer is yes." }, + { "false", "The proposition is false or the answer is no." } }; + if (!criteria.is_null()) { + if (!criteria.is_object()) { + *err = err_bad(path + ".criteria", "must be an object with `true` and `false`, or absent"); + return RAD_E_INVAL; + } + if (!only_keys(criteria, { "true", "false" }, path + ".criteria.", err)) return RAD_E_INVAL; + for (const auto& kv : criteria.items()) c[kv.key()] = kv.value(); + } + q->options = { "true", "false" }; + *descs = { c["true"], c["false"] }; + q->response_order = q->options; + return RAD_OK; + } + if (type == "choice") { + if (!criteria.is_object() || criteria.empty()) { + *err = err_bad(path + ".criteria", "must be a non-empty object of option names to descriptions"); + return RAD_E_INVAL; + } + std::vector> o; + for (const auto& kv : criteria.items()) { + o.emplace_back(kv.key(), kv.value()); + q->response_order.push_back(kv.key()); + } + /* Python sorts str keys by code point, which UTF-8 byte order preserves. */ + std::sort(o.begin(), o.end(), [](const auto& a, const auto& b) { return a.first < b.first; }); + for (auto& p : o) { + q->options.push_back(p.first); + descs->push_back(std::move(p.second)); + } + return RAD_OK; + } + if (!criteria.is_array() || criteria.empty()) { + *err = err_bad(path + ".criteria", "must be a non-empty array of level descriptions, lowest first"); + return RAD_E_INVAL; + } + for (size_t i = 0; i < criteria.size(); ++i) { + q->options.push_back(std::to_string(i)); + descs->push_back(criteria[i]); + } + q->response_order = q->options; + for (const json& c : criteria) q->legend.push_back(c.dump()); + return RAD_OK; +} + +double round4(double v) { return std::round(v * 10000.0) / 10000.0; } + +} /* namespace */ + +std::string clef_render(const json& v) { + if (v.is_string()) return v.get(); + /* json.dumps(sort_keys=True, separators=(",", ":"), ensure_ascii=False): nlohmann's unordered + * json keeps its keys sorted by bytes, which is code point order for UTF-8. */ + return nlohmann::json::parse(v.dump()).dump(-1, ' ', false, nlohmann::json::error_handler_t::replace); +} + +int parse_clef_request(const std::string& body, const OaiDeps& d, const OaiLimits& lim, + const std::string& model_id, ClefRequest* out, ApiError* err) { + *out = ClefRequest{}; + json b; + RAD_TRY(parse_request_object(body, lim, &b, err)); + if (!only_keys(b, { "model", "state", "questions", "images" }, "", err)) return RAD_E_INVAL; + if (b.contains("model") && (!b["model"].is_string() || b["model"] != model_id)) { + *err = err_bad("model", "must name the loaded model, " + model_id); + return RAD_E_INVAL; + } + if (!b.contains("state") || (b["state"].is_string() && b["state"].get().empty())) { + *err = err_bad("state", "required: a non-empty string or any JSON value"); + return RAD_E_INVAL; + } + if (b.contains("images") && !(b["images"].is_array() && b["images"].empty())) { + *err = err_not_implemented("images: this server reads clef's state as text only"); + return RAD_E_UNSUPPORTED; + } + const json& qs = b.contains("questions") ? b["questions"] : json(); + if (!qs.is_object() || qs.empty()) { + *err = err_bad("questions", "must be a non-empty object of named questions"); + return RAD_E_INVAL; + } + + const ITokenizer& tok = *d.tok; + auto ids = [&](const std::string& text) { return tok.encode(text, false, true); }; + auto append = [](std::vector* to, const std::vector& v) { + to->insert(to->end(), v.begin(), v.end()); + }; + + /* encode_record: the schema first, with spans relative to its own start. */ + std::vector schema = ids("\n\nSCHEMA FIELDS:\n"); + size_t index = 0; + for (const auto& kv : qs.items()) { + const std::string path = "questions." + kv.key(); + const json& src = kv.value(); + if (!src.is_object()) { *err = err_bad(path, "must be an object"); return RAD_E_INVAL; } + if (!only_keys(src, { "type", "instructions", "criteria" }, path + ".", err)) return RAD_E_INVAL; + const auto ty = src.find("type"); + if (ty == src.end() || !ty->is_string() || + (*ty != "noul" && *ty != "choice" && *ty != "score")) { + *err = err_bad(path + ".type", "must be noul, choice or score"); + return RAD_E_INVAL; + } + ClefQuestion q; + q.name = kv.key(); + q.type = ty->get(); + q.type_id = q.type == "noul" ? 0 : q.type == "choice" ? 1 : 2; + std::vector descs; + RAD_TRY(question_options(path, q.type, src.contains("criteria") ? src.at("criteria") : json(), + &q, &descs, err)); + + append(&schema, ids("\nFIELD " + std::to_string(++index) + "\nID: " + q.name + "\nTYPE: " + + q.type + "\nINSTRUCTION: ")); + json instructions = src.contains("instructions") ? src.at("instructions") : json(); + if (instructions.is_null() || instructions == "") instructions = q.name; + q.question.first = (int64_t)schema.size(); + append(&schema, ids(clef_render(instructions))); + q.question.second = (int64_t)schema.size(); + append(&schema, ids("\nALLOWED OPTIONS:\n")); + for (size_t i = 0; i < q.options.size(); ++i) { + append(&schema, ids("OPTION " + std::to_string(i + 1) + ": ")); + json semantics = { { "option_id", q.options[i] } }; + if (!descs[i].is_null()) semantics["description"] = descs[i]; + const int64_t start = (int64_t)schema.size(); + append(&schema, ids(clef_render(semantics))); + q.option_spans.emplace_back(start, (int64_t)schema.size()); + append(&schema, ids("\n")); + } + append(&schema, ids("END FIELD\n")); + /* A span the tokenizer left empty would make the head average nothing. */ + if (q.question.first == q.question.second) { + *err = err_bad(path + ".instructions", "renders to no tokens"); + return RAD_E_INVAL; + } + out->questions.push_back(std::move(q)); + } + + const std::vector prefix = ids(std::string("<|im_start|>system\n") + kSystemPrompt + + "<|im_end|>\n<|im_start|>user\nSTATE:\n"); + const std::vector state = ids(clef_render(b["state"])); + const std::vector suffix = + ids("\n<|im_end|>\n<|im_start|>assistant\n\n\n\n\nJOINT SCHEMA DECISIONS:"); + const int64_t n = (int64_t)(prefix.size() + state.size() + schema.size() + suffix.size()); + if (lim.max_ctx > 0 && n > lim.max_ctx) { + ApiError e = err_bad("state", "the prompt is " + std::to_string(n) + " tokens; this " + "deployment's context holds " + std::to_string(lim.max_ctx)); + e.code = "context_length_exceeded"; + e.n_prompt_tokens = n; + e.n_ctx = lim.max_ctx; + *err = e; + return RAD_E_INVAL; + } + const int64_t offset = (int64_t)(prefix.size() + state.size()); + for (ClefQuestion& q : out->questions) { + q.question.first += offset; + q.question.second += offset; + for (TokenSpan& s : q.option_spans) { s.first += offset; s.second += offset; } + } + out->tokens = prefix; + append(&out->tokens, state); + append(&out->tokens, schema); + append(&out->tokens, suffix); + return RAD_OK; +} + +int clef_answer(const ClefQuestion& q, const std::vector& logits, json* out, ApiError* err) { + if (logits.size() != q.options.size()) { + *err = err_internal("the head returned no logits for question " + q.name); + return RAD_E_STATE; + } + double peak = -std::numeric_limits::infinity(); + for (float l : logits) { + if (!std::isfinite(l)) { + *err = err_internal("question " + q.name + " scored a non-finite logit"); + return RAD_E_STATE; + } + peak = std::max(peak, (double)l); + } + std::vector p; + double total = 0.0; + for (float l : logits) total += p.emplace_back(std::exp((double)l - peak)); + for (double& v : p) v /= total; + auto prob = [&](const std::string& option) { + return p[(size_t)(std::find(q.options.begin(), q.options.end(), option) - q.options.begin())]; + }; + + /* systemone_answer. */ + json a = json::object(); + a["type"] = q.type; + if (q.type == "noul") { + a["noul"] = round4(prob("true")); + *out = std::move(a); + return RAD_OK; + } + json probs = json::object(); + if (q.type == "choice") { + std::string best = q.response_order[0]; + for (const std::string& o : q.response_order) if (prob(o) > prob(best)) best = o; + a["choice"] = best; + a["confidence"] = round4(prob(best)); + for (const std::string& o : q.response_order) probs[o] = round4(prob(o)); + a["probabilities"] = std::move(probs); + } else { + double expected = 0.0, top = 0.0; + json legend = json::object(); + for (size_t i = 0; i < q.options.size(); ++i) { + expected += (double)i * p[i]; + top = std::max(top, p[i]); + legend[q.options[i]] = json::parse(q.legend[i]); + probs[q.options[i]] = round4(p[i]); + } + a["score"] = round4(expected); + a["confidence"] = round4(top); + a["legend"] = std::move(legend); + a["probabilities"] = std::move(probs); + } + *out = std::move(a); + return RAD_OK; +} + +} /* namespace server */ +} /* namespace rad */ diff --git a/core/server/clef.h b/core/server/clef.h new file mode 100644 index 00000000..b8e18fa1 --- /dev/null +++ b/core/server/clef.h @@ -0,0 +1,63 @@ +/* clef.h -- POST /v1/systemone for Cloudflare's clef and clef-flash: the prompt, its spans, and + * the answer read off the joint schema head's per-option logits. + * + * clef is not read at one position the way d1 is (systemone.h). Its joint schema head reads the + * final hidden state of EVERY prompt position, the mean over each question's instruction span and + * each option's span, and the lm_head rows of each option's tokens, and gives one logit an + * allowed option. So the prompt here comes with those spans, and the answer is a softmax over the + * head's logits. This file is a C++ rewrite of encode_record, question_options and + * systemone_answer in the release's joint_schema_model.py, with its strings kept as they are: the + * head was trained on exactly this text. + * + * Served only when the container declares clef (`decision.type` = `clef`, set at convert with + * `--set decision.type=clef`); the HF config does not declare it. + */ +#pragma once + +#include "oai.h" + +#include +#include +#include + +namespace rad { +namespace server { + +using TokenSpan = std::pair; /* [start, end) prompt positions */ + +struct ClefQuestion { + std::string name, type; /* type: noul | choice | score */ + int type_id = 0; /* noul 0, choice 1, score 2: the head's type embedding */ + TokenSpan question; /* the rendered instructions */ + /* One entry an allowed option, in the order the head scores them: true/false, the choice + * names sorted, or the levels "0".."n-1". */ + std::vector options; + std::vector option_spans; + /* The response's own order and wording: a choice lists its options as the request gave them, + * a score carries its legend: each level's criterion as given, any JSON value, dumped. */ + std::vector response_order; + std::vector legend; +}; + +struct ClefRequest { + std::vector tokens; + std::vector questions; +}; + +/* Parse and render. The whole prompt must fit `lim.max_ctx`: a state too long is refused, where + * joint_schema_model.py would cut it short, so an answer never reads a state the caller did not + * send whole. */ +int parse_clef_request(const std::string& body, const OaiDeps& d, const OaiLimits& lim, + const std::string& model_id, ClefRequest* out, ApiError* err); + +/* One question's answer from the head's logits, one an option in `options` order + * (systemone_answer: a softmax, rounded to four places as the release rounds). A non-finite logit + * is an error. */ +int clef_answer(const ClefQuestion& q, const std::vector& logits, json* out, ApiError* err); + +/* joint_schema_model.py's render: a string as it is, anything else as compact JSON with its keys + * sorted and non-ASCII kept. Exposed for the tests. */ +std::string clef_render(const json& v); + +} /* namespace server */ +} /* namespace rad */ diff --git a/core/server/server.cpp b/core/server/server.cpp index c1df2ff8..d455fefe 100644 --- a/core/server/server.cpp +++ b/core/server/server.cpp @@ -95,6 +95,8 @@ void Server::register_routes() { 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); }); + /* LiteLLM's name for the same endpoint. */ + router_.post("/v1/decisions", [this](const HttpRequest& q) { return handle_systemone(q); }); /* Speech to text, for a model whose plugin says how it transcribes (RadAudioFormat). */ router_.post("/v1/audio/speech", [this](const HttpRequest& q) { return handle_speech(q); }); router_.post("/v1/videos", [this](const HttpRequest& q) { return handle_video_create(q); }); diff --git a/tests/clef_test.cpp b/tests/clef_test.cpp new file mode 100644 index 00000000..25902197 --- /dev/null +++ b/tests/clef_test.cpp @@ -0,0 +1,193 @@ +/* clef_test.cpp -- clef's prompt, spans and answer (core/server/clef.h). + * + * The head reads spans of the prompt, so the spans are checked as text: the ids of a question's + * span decode to its rendered instructions, an option's to its rendered semantics. With a + * tokenizer.json from a clef release in RAD_CLEF_DIR, the ids and spans are also compared with + * the release's own encode_record over tests/data/golden/clef_encode.json (clef_encode_gen.py). + */ +#include "rad_test.h" + +#include "server/adapters.h" +#include "server/clef.h" +#include "text/tokenizer.h" + +#include + +#include +#include +#include + +using namespace rad; +using namespace rad::server; + +namespace { + +/* One id a byte, so a prompt decodes back to its exact text and a span to its exact piece. */ +struct ByteTokenizer : ITokenizer { + std::vector encode(const std::string& s, bool, bool) const override { + std::vector v; + for (unsigned char c : s) v.push_back(c); + return v; + } + std::string token_bytes(int32_t id) const override { return std::string(1, (char)id); } + std::string decode(const std::vector& t) const override { + std::string s; + for (int32_t x : t) s += (char)x; + return s; + } + int32_t eos() const override { return 0; } + int32_t bos() const override { return -1; } + std::unique_ptr detokenizer(const std::vector&, + const std::vector&) const override { + return nullptr; + } +}; + +int parse(const ITokenizer& tok, const std::string& body, ClefRequest* r, ApiError* e, + int64_t max_ctx = 0) { + OaiDeps d; + d.tok = const_cast(&tok); + OaiLimits l; + l.model_id = "clef-flash"; + l.max_ctx = max_ctx; + return parse_clef_request(body, d, l, "clef-flash", r, e); +} + +std::string span(const ITokenizer& tok, const ClefRequest& r, TokenSpan s) { + return tok.decode(std::vector(r.tokens.begin() + s.first, r.tokens.begin() + s.second)); +} + +const char* const kBody = R"({"state": "I was charged twice.", + "questions": { + "refund": {"type": "noul", "instructions": "Refund?"}, + "team": {"type": "choice", "instructions": "Which team?", + "criteria": {"technical": "Faults", "billing": "Charges"}}, + "urgency": {"type": "score", "instructions": "How urgent?", "criteria": ["Later", "Now"]}}})"; + +} /* namespace */ + +TEST(the_prompt_is_the_releases_text) { + ByteTokenizer tok; + ClefRequest r; + ApiError e; + CHECK_OK(parse(tok, kBody, &r, &e)); + CHECK_EQ(tok.decode(r.tokens), + "<|im_start|>system\nRead the complete state and schema. Decide every field jointly. " + "Each answer must be exactly one of that field's allowed options.<|im_end|>\n" + "<|im_start|>user\nSTATE:\nI was charged twice." + "\n\nSCHEMA FIELDS:\n" + "\nFIELD 1\nID: refund\nTYPE: noul\nINSTRUCTION: Refund?\nALLOWED OPTIONS:\n" + "OPTION 1: {\"description\":\"The proposition is true or the answer is yes.\",\"option_id\":\"true\"}\n" + "OPTION 2: {\"description\":\"The proposition is false or the answer is no.\",\"option_id\":\"false\"}\n" + "END FIELD\n" + "\nFIELD 2\nID: team\nTYPE: choice\nINSTRUCTION: Which team?\nALLOWED OPTIONS:\n" + "OPTION 1: {\"description\":\"Charges\",\"option_id\":\"billing\"}\n" + "OPTION 2: {\"description\":\"Faults\",\"option_id\":\"technical\"}\n" + "END FIELD\n" + "\nFIELD 3\nID: urgency\nTYPE: score\nINSTRUCTION: How urgent?\nALLOWED OPTIONS:\n" + "OPTION 1: {\"description\":\"Later\",\"option_id\":\"0\"}\n" + "OPTION 2: {\"description\":\"Now\",\"option_id\":\"1\"}\n" + "END FIELD\n" + "\n<|im_end|>\n<|im_start|>assistant\n\n\n\n\nJOINT SCHEMA DECISIONS:"); +} + +TEST(spans_cover_the_instructions_and_each_options_semantics) { + ByteTokenizer tok; + ClefRequest r; + ApiError e; + CHECK_OK(parse(tok, kBody, &r, &e)); + REQUIRE(r.questions.size() == 3); + CHECK_EQ(span(tok, r, r.questions[0].question), "Refund?"); + CHECK_EQ(r.questions[1].type_id, 1); + /* A choice's options are scored sorted; the response keeps the request's order. */ + CHECK(r.questions[1].options == (std::vector{ "billing", "technical" })); + CHECK(r.questions[1].response_order == (std::vector{ "technical", "billing" })); + CHECK_EQ(span(tok, r, r.questions[1].option_spans[0]), + "{\"description\":\"Charges\",\"option_id\":\"billing\"}"); + CHECK_EQ(span(tok, r, r.questions[2].option_spans[1]), "{\"description\":\"Now\",\"option_id\":\"1\"}"); +} + +TEST(render_sorts_keys_and_keeps_unicode) { + CHECK_EQ(clef_render(json::parse(R"({"b": [1, 2.5, null], "a": "ü\n"})")), + "{\"a\":\"ü\\n\",\"b\":[1,2.5,null]}"); + CHECK_EQ(clef_render(json("as is")), "as is"); +} + +TEST(bad_requests_are_400s) { + ByteTokenizer tok; + ClefRequest r; + ApiError e; + CHECK(parse(tok, R"({"questions": {"q": {"type": "noul"}}})", &r, &e) < 0); + CHECK_EQ(e.param, "state"); + CHECK(parse(tok, R"({"state": "", "questions": {"q": {"type": "noul"}}})", &r, &e) < 0); + CHECK(parse(tok, R"({"state": "s", "questions": {}})", &r, &e) < 0); + CHECK_EQ(e.param, "questions"); + CHECK(parse(tok, R"({"state": "s", "questions": {"q": {"instructions": "x"}}})", &r, &e) < 0); + CHECK_EQ(e.param, "questions.q.type"); + CHECK(parse(tok, R"({"state": "s", "questions": {"q": {"type": "choice", "criteria": {}}}})", &r, &e) < 0); + CHECK_EQ(e.param, "questions.q.criteria"); + CHECK(parse(tok, R"({"state": "s", "questions": {"q": {"type": "noul", "criteria": {"maybe": "x"}}}})", &r, &e) < 0); + CHECK(parse(tok, R"({"state": "s", "questions": {"q": {"type": "noul"}}, "extra": 1})", &r, &e) < 0); + CHECK(parse(tok, R"({"model": "other", "state": "s", "questions": {"q": {"type": "noul"}}})", &r, &e) < 0); + CHECK_EQ(e.param, "model"); + /* The whole prompt must fit; nothing is cut. */ + CHECK(parse(tok, kBody, &r, &e, 100) < 0); + CHECK_EQ(e.code, "context_length_exceeded"); +} + +TEST(answers_are_softmaxes_in_the_releases_shape) { + ByteTokenizer tok; + ClefRequest r; + ApiError e; + CHECK_OK(parse(tok, kBody, &r, &e)); + json a; + CHECK_OK(clef_answer(r.questions[0], { 2.0f, 0.0f }, &a, &e)); + CHECK_EQ(a["noul"].get(), std::round(1.0 / (1.0 + std::exp(-2.0)) * 1e4) / 1e4); + /* Options in head order (billing, technical); the response in request order. */ + CHECK_OK(clef_answer(r.questions[1], { 0.0f, 1.0f }, &a, &e)); + CHECK_EQ(a["choice"].get(), "technical"); + CHECK_EQ(a["probabilities"].begin().key(), "technical"); + double total = 0.0; + for (const auto& kv : a["probabilities"].items()) total += kv.value().get(); + CHECK(std::fabs(total - 1.0) < 1e-3); + CHECK_OK(clef_answer(r.questions[2], { 0.0f, 0.0f }, &a, &e)); + CHECK_EQ(a["score"].get(), 0.5); + CHECK_EQ(a["legend"]["1"].get(), "Now"); + CHECK(clef_answer(r.questions[2], { 0.0f, NAN }, &a, &e) < 0); + CHECK(clef_answer(r.questions[2], { 0.0f }, &a, &e) < 0); +} + +TEST(ids_and_spans_match_the_releases_encode_record) { + const char* dir = std::getenv("RAD_CLEF_DIR"); + if (!dir) SKIP("RAD_CLEF_DIR names no clef release with a tokenizer.json"); + VocabBuild vb; + REQUIRE(parse_tokenizer_json((std::string(dir) + "/tokenizer.json").c_str(), vb) == RAD_OK); + auto vocab = std::make_shared(); + REQUIRE(vocab->load(std::move(vb)) == RAD_OK); + TokenizerBridge tok(vocab); + std::ifstream f(std::string(RAD_GOLDEN_FIXTURES) + "/clef_encode.json"); + REQUIRE(f.is_open()); + for (const auto& g : json::parse(f)) { /* ordered: the questions keep their order */ + ClefRequest r; + ApiError e; + CHECK_OK(parse(tok, g["request"].dump(), &r, &e)); + CHECK(r.tokens == g["input_ids"].get>()); + REQUIRE(r.questions.size() == g["questions"].size()); + for (size_t i = 0; i < r.questions.size(); ++i) { + const auto& gq = g["questions"][i]; + const ClefQuestion& q = r.questions[i]; + CHECK_EQ(q.name, gq["id"].get()); + CHECK_EQ(q.type_id, gq["type"].get()); + CHECK_EQ(q.question.first, gq["span"][0].get()); + CHECK_EQ(q.question.second, gq["span"][1].get()); + CHECK(q.options == gq["option_ids"].get>()); + REQUIRE(q.option_spans.size() == gq["option_spans"].size()); + for (size_t k = 0; k < q.option_spans.size(); ++k) { + CHECK_EQ(q.option_spans[k].first, gq["option_spans"][k][0].get()); + CHECK_EQ(q.option_spans[k].second, gq["option_spans"][k][1].get()); + } + } + } +} + +RAD_TEST_MAIN() diff --git a/tests/data/golden/clef_encode.json b/tests/data/golden/clef_encode.json new file mode 100644 index 00000000..5f24a2d4 --- /dev/null +++ b/tests/data/golden/clef_encode.json @@ -0,0 +1,1094 @@ +[ + { + "request": { + "state": "I was charged twice this month, please refund one of them.", + "questions": { + "refund": { + "type": "noul", + "instructions": "Is the customer asking for a refund?" + }, + "team": { + "type": "choice", + "instructions": "Which team should handle this?", + "criteria": { + "technical": "App or site faults", + "billing": "Charges, refunds, invoices" + } + }, + "urgency": { + "type": "score", + "instructions": "How urgent is this?", + "criteria": [ + "Can wait", + "Today", + "Blocking the customer now" + ] + } + } + }, + "input_ids": [ + 248045, + 8678, + 198, + 4274, + 279, + 4434, + 1528, + 321, + 10485, + 13, + 95462, + 1396, + 2002, + 50407, + 13, + 8618, + 4087, + 1902, + 381, + 6681, + 799, + 314, + 421, + 2002, + 579, + 5252, + 2519, + 13, + 248046, + 198, + 248045, + 846, + 198, + 23852, + 25, + 198, + 40, + 557, + 11102, + 10598, + 411, + 2182, + 11, + 4338, + 20325, + 799, + 314, + 1070, + 13, + 271, + 3423, + 34651, + 426, + 32349, + 25, + 198, + 198, + 27806, + 220, + 16, + 198, + 887, + 25, + 20325, + 198, + 9222, + 25, + 307, + 10644, + 198, + 669, + 55530, + 25, + 220, + 3742, + 279, + 5813, + 9859, + 364, + 264, + 20325, + 30, + 198, + 51535, + 1425, + 49555, + 25, + 198, + 32929, + 220, + 16, + 25, + 220, + 4754, + 4532, + 3147, + 760, + 38749, + 369, + 804, + 466, + 279, + 4087, + 369, + 9542, + 46292, + 1979, + 816, + 3147, + 1802, + 8934, + 198, + 32929, + 220, + 17, + 25, + 220, + 4754, + 4532, + 3147, + 760, + 38749, + 369, + 867, + 466, + 279, + 4087, + 369, + 874, + 46292, + 1979, + 816, + 3147, + 3721, + 8934, + 198, + 4537, + 38945, + 198, + 198, + 27806, + 220, + 17, + 198, + 887, + 25, + 2015, + 198, + 9222, + 25, + 5576, + 198, + 669, + 55530, + 25, + 220, + 22365, + 2015, + 1220, + 3579, + 411, + 30, + 198, + 51535, + 1425, + 49555, + 25, + 198, + 32929, + 220, + 16, + 25, + 220, + 4754, + 4532, + 3147, + 1106, + 56281, + 11, + 70057, + 11, + 61893, + 2129, + 1979, + 816, + 3147, + 37355, + 8934, + 198, + 32929, + 220, + 17, + 25, + 220, + 4754, + 4532, + 3147, + 2095, + 466, + 2660, + 54794, + 2129, + 1979, + 816, + 3147, + 69685, + 8934, + 198, + 4537, + 38945, + 198, + 198, + 27806, + 220, + 18, + 198, + 887, + 25, + 52011, + 198, + 9222, + 25, + 5284, + 198, + 669, + 55530, + 25, + 220, + 4199, + 32556, + 369, + 411, + 30, + 198, + 51535, + 1425, + 49555, + 25, + 198, + 32929, + 220, + 16, + 25, + 220, + 4754, + 4532, + 3147, + 6503, + 3655, + 2129, + 1979, + 816, + 3147, + 15, + 8934, + 198, + 32929, + 220, + 17, + 25, + 220, + 4754, + 4532, + 3147, + 14917, + 2129, + 1979, + 816, + 3147, + 16, + 8934, + 198, + 32929, + 220, + 18, + 25, + 220, + 4754, + 4532, + 3147, + 46657, + 279, + 5813, + 1381, + 2129, + 1979, + 816, + 3147, + 17, + 8934, + 198, + 4537, + 38945, + 198, + 198, + 248046, + 198, + 248045, + 74455, + 198, + 248068, + 271, + 248069, + 271, + 25310, + 3118, + 7295, + 34651, + 41402, + 23451, + 50, + 25 + ], + "questions": [ + { + "id": "refund", + "type": 0, + "span": [ + 74, + 82 + ], + "option_ids": [ + "true", + "false" + ], + "option_spans": [ + [ + 93, + 111 + ], + [ + 117, + 135 + ] + ] + }, + { + "id": "team", + "type": 1, + "span": [ + 156, + 162 + ], + "option_ids": [ + "billing", + "technical" + ], + "option_spans": [ + [ + 173, + 188 + ], + [ + 194, + 207 + ] + ] + }, + { + "id": "urgency", + "type": 2, + "span": [ + 228, + 233 + ], + "option_ids": [ + "0", + "1", + "2" + ], + "option_spans": [ + [ + 244, + 255 + ], + [ + 261, + 271 + ], + [ + 277, + 290 + ] + ] + } + ] + }, + { + "request": { + "state": { + "zeta": [ + 1, + 2.5, + 1e-05, + 100.0, + null, + true + ], + "alpha": { + "b": "ü ☃ 😀", + "a": "line\nbreak \"q\" \\ \t" + }, + "n": -3, + "big": 12345678901234567890 + }, + "questions": { + "late": { + "type": "noul", + "instructions": "", + "criteria": { + "true": "Not on time", + "false": null + } + }, + "kind": { + "type": "choice", + "instructions": { + "ask": "what kind?", + "lang": "en" + }, + "criteria": { + "b_opt": { + "why": 1 + }, + "a_opt": null, + "Z": "upper first" + } + }, + "level": { + "type": "score", + "criteria": [ + { + "lo": true + }, + "mid", + 3 + ] + } + } + }, + "input_ids": [ + 248045, + 8678, + 198, + 4274, + 279, + 4434, + 1528, + 321, + 10485, + 13, + 95462, + 1396, + 2002, + 50407, + 13, + 8618, + 4087, + 1902, + 381, + 6681, + 799, + 314, + 421, + 2002, + 579, + 5252, + 2519, + 13, + 248046, + 198, + 248045, + 846, + 198, + 23852, + 25, + 198, + 4754, + 6918, + 21624, + 64, + 3147, + 1021, + 1639, + 8689, + 7018, + 80, + 2037, + 24193, + 1088, + 83, + 2129, + 65, + 3147, + 2314, + 24329, + 225, + 87209, + 56658, + 15679, + 763, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 15, + 1288, + 77, + 50303, + 18, + 1288, + 89, + 1850, + 8631, + 16, + 11, + 17, + 13, + 20, + 11, + 16, + 68, + 12, + 15, + 20, + 11, + 16, + 15, + 15, + 13, + 15, + 22357, + 20691, + 13587, + 271, + 3423, + 34651, + 426, + 32349, + 25, + 198, + 198, + 27806, + 220, + 16, + 198, + 887, + 25, + 3200, + 198, + 9222, + 25, + 307, + 10644, + 198, + 669, + 55530, + 25, + 220, + 4913, + 198, + 51535, + 1425, + 49555, + 25, + 198, + 32929, + 220, + 16, + 25, + 220, + 4754, + 4532, + 3147, + 2536, + 383, + 854, + 2129, + 1979, + 816, + 3147, + 1802, + 8934, + 198, + 32929, + 220, + 17, + 25, + 220, + 4754, + 1979, + 816, + 3147, + 3721, + 8934, + 198, + 4537, + 38945, + 198, + 198, + 27806, + 220, + 17, + 198, + 887, + 25, + 2993, + 198, + 9222, + 25, + 5576, + 198, + 669, + 55530, + 25, + 220, + 4754, + 1038, + 3147, + 12195, + 2993, + 30, + 2129, + 5040, + 3147, + 268, + 8934, + 198, + 51535, + 1425, + 49555, + 25, + 198, + 32929, + 220, + 16, + 25, + 220, + 4754, + 4532, + 3147, + 13181, + 1118, + 2129, + 1979, + 816, + 3147, + 57, + 8934, + 198, + 32929, + 220, + 17, + 25, + 220, + 4754, + 1979, + 816, + 3147, + 64, + 14596, + 8934, + 198, + 32929, + 220, + 18, + 25, + 220, + 4754, + 4532, + 21624, + 33488, + 763, + 16, + 49471, + 1979, + 816, + 3147, + 65, + 14596, + 8934, + 198, + 4537, + 38945, + 198, + 198, + 27806, + 220, + 18, + 198, + 887, + 25, + 2119, + 198, + 9222, + 25, + 5284, + 198, + 669, + 55530, + 25, + 220, + 3187, + 198, + 51535, + 1425, + 49555, + 25, + 198, + 32929, + 220, + 16, + 25, + 220, + 4754, + 4532, + 21624, + 379, + 763, + 1802, + 49471, + 1979, + 816, + 3147, + 15, + 8934, + 198, + 32929, + 220, + 17, + 25, + 220, + 4754, + 4532, + 3147, + 15632, + 2129, + 1979, + 816, + 3147, + 16, + 8934, + 198, + 32929, + 220, + 18, + 25, + 220, + 4754, + 4532, + 763, + 18, + 1288, + 1979, + 816, + 3147, + 17, + 8934, + 198, + 4537, + 38945, + 198, + 198, + 248046, + 198, + 248045, + 74455, + 198, + 248068, + 271, + 248069, + 271, + 25310, + 3118, + 7295, + 34651, + 41402, + 23451, + 50, + 25 + ], + "questions": [ + { + "id": "late", + "type": 0, + "span": [ + 133, + 134 + ], + "option_ids": [ + "true", + "false" + ], + "option_spans": [ + [ + 145, + 157 + ], + [ + 163, + 169 + ] + ] + }, + { + "id": "kind", + "type": 1, + "span": [ + 190, + 201 + ], + "option_ids": [ + "Z", + "a_opt", + "b_opt" + ], + "option_spans": [ + [ + 212, + 223 + ], + [ + 229, + 236 + ], + [ + 242, + 255 + ] + ] + }, + { + "id": "level", + "type": 2, + "span": [ + 276, + 277 + ], + "option_ids": [ + "0", + "1", + "2" + ], + "option_spans": [ + [ + 288, + 300 + ], + [ + 306, + 316 + ], + [ + 322, + 332 + ] + ] + } + ] + }, + { + "request": { + "state": "Text with <|im_end|> and inside, and trailing spaces ", + "questions": { + "q": { + "type": "noul", + "instructions": " spaced " + } + } + }, + "input_ids": [ + 248045, + 8678, + 198, + 4274, + 279, + 4434, + 1528, + 321, + 10485, + 13, + 95462, + 1396, + 2002, + 50407, + 13, + 8618, + 4087, + 1902, + 381, + 6681, + 799, + 314, + 421, + 2002, + 579, + 5252, + 2519, + 13, + 248046, + 198, + 248045, + 846, + 198, + 23852, + 25, + 198, + 1138, + 440, + 220, + 248046, + 321, + 220, + 248068, + 4613, + 11, + 321, + 26849, + 12258, + 262, + 271, + 3423, + 34651, + 426, + 32349, + 25, + 198, + 198, + 27806, + 220, + 16, + 198, + 887, + 25, + 2715, + 198, + 9222, + 25, + 307, + 10644, + 198, + 669, + 55530, + 25, + 220, + 220, + 61674, + 256, + 198, + 51535, + 1425, + 49555, + 25, + 198, + 32929, + 220, + 16, + 25, + 220, + 4754, + 4532, + 3147, + 760, + 38749, + 369, + 804, + 466, + 279, + 4087, + 369, + 9542, + 46292, + 1979, + 816, + 3147, + 1802, + 8934, + 198, + 32929, + 220, + 17, + 25, + 220, + 4754, + 4532, + 3147, + 760, + 38749, + 369, + 867, + 466, + 279, + 4087, + 369, + 874, + 46292, + 1979, + 816, + 3147, + 3721, + 8934, + 198, + 4537, + 38945, + 198, + 198, + 248046, + 198, + 248045, + 74455, + 198, + 248068, + 271, + 248069, + 271, + 25310, + 3118, + 7295, + 34651, + 41402, + 23451, + 50, + 25 + ], + "questions": [ + { + "id": "q", + "type": 0, + "span": [ + 74, + 77 + ], + "option_ids": [ + "true", + "false" + ], + "option_spans": [ + [ + 88, + 106 + ], + [ + 112, + 130 + ] + ] + } + ] + } +] diff --git a/tests/data/golden/clef_encode_gen.py b/tests/data/golden/clef_encode_gen.py new file mode 100644 index 00000000..25a8f20a --- /dev/null +++ b/tests/data/golden/clef_encode_gen.py @@ -0,0 +1,41 @@ +# Writes clef_encode.json: clef's own encode_record (the release's joint_schema_model.py) over synthetic +# requests, which tests/clef_test.cpp compares parse_clef_request against with the same +# tokenizer.json. No respondent data. Run with transformers installed, from a clef release dir: +# python3 clef_encode_gen.py /path/to/clef-flash > clef_encode.json +import json +import sys + +sys.path.insert(0, sys.argv[1]) +from joint_schema_model import encode_record # noqa: E402 +from transformers import AutoTokenizer # noqa: E402 + +REQUESTS = [ + {"state": "I was charged twice this month, please refund one of them.", + "questions": { + "refund": {"type": "noul", "instructions": "Is the customer asking for a refund?"}, + "team": {"type": "choice", "instructions": "Which team should handle this?", + "criteria": {"technical": "App or site faults", "billing": "Charges, refunds, invoices"}}, + "urgency": {"type": "score", "instructions": "How urgent is this?", + "criteria": ["Can wait", "Today", "Blocking the customer now"]}}}, + {"state": {"zeta": [1, 2.5, 1e-05, 100.0, None, True], "alpha": {"b": "ü ☃ 😀", "a": "line\nbreak \"q\" \\ \t"}, + "n": -3, "big": 12345678901234567890}, + "questions": { + "late": {"type": "noul", "instructions": "", + "criteria": {"true": "Not on time", "false": None}}, + "kind": {"type": "choice", "instructions": {"ask": "what kind?", "lang": "en"}, + "criteria": {"b_opt": {"why": 1}, "a_opt": None, "Z": "upper first"}}, + "level": {"type": "score", "criteria": [{"lo": True}, "mid", 3]}}}, + {"state": "Text with <|im_end|> and inside, and trailing spaces ", + "questions": {"q": {"type": "noul", "instructions": " spaced "}}}, +] + +tok = AutoTokenizer.from_pretrained(sys.argv[1]) +out = [] +for r in REQUESTS: + e = encode_record(tok, r) + out.append({"request": r, "input_ids": list(e.input_ids), + "questions": [{"id": q.question_id, "type": q.question_type, "span": list(q.question_span), + "option_ids": list(q.option_ids), "option_spans": [list(s) for s in q.option_spans]} + for q in e.questions]}) +json.dump(out, sys.stdout, ensure_ascii=False, indent=1) +print()