Archived
New models and formats: - IQR for Qwen3.8-27B: weights on the int8 grid under GPTQ, a trellis down each GPTQ column (IQR-V2), and IQR-V3, a computed trellis code under one scale a row, kept at its codes' width in VRAM and decoded in the GEMM; 15 IQR-V3 recipes from ~2 to ~7 bits a weight (data/recipes/q38-27b-*-v3.recipe, docs/IQR.md) - libhalo: a kernel library for Strix Halo (gfx1151), preferred there over libr3d - Nemotron 3.5 Embed 1B and 8B (nemotron35_embed): text and image embeddings through a Pixtral tower, on the card and on the CPU - Nemotron 3.5 Rerank 8B - /v1/systemone: Cloudflare's clef and clef-flash, Convai Innovations' Laya and Mica beside LiquidAI d1; scored steps read the candidates' logits from the head table with no lm_head pass - LFM2's 8-bit trunk: block-fp8 or int8 linears with the fused producers, and the d1-3B recipe - DeepSeek-V4.1's reply format with DSML tool calls and typed argument tags Weights on the drive: - The file tier reads only the experts the pass routes rows to; the draft head's weights stay in the host pool - A hot VRAM cache for routed experts read off the drive, reads deposited straight into free host pool slots, and copyless evictions; the file tier's counters are now ssd_* - GLM-5 Next shards its routed experts by expert, not by width, so they can live on the drive - The stall watch counts drive reads as progress, and the DMA lane's room check reads the lane's own completion fence Quantisation tooling: - --calib-corpus, --calib-dir and --calib-layers record each linear's input Hessian; beside --kld-record the reference's own run records them - --kld-top N records a sparse KL reference (the N most likely tokens and the tail's mass) - GPTQ in a third of the time with the same codes, trellis GPTQ on the card, vector codebooks with coordinate descent, and rad-convert --reuse repeated, each container supplying what the earlier ones lack Speculation: - Prompt lookup alone (--spec-ngram K, --spec-ngram-min/-max): each sequence keeps an index of its n-grams, and a proposal is verified only when its measured step cost says it pays; --draft-window adaptive follows it Speed: - IQR decode: the narrow tile splits K for four times the int8 tile's waves and folds each 128-K block once; at 8 tokens down and the output projections run in 0.61-0.82x and 0.70-0.92x FP8's time (2-6 bits); IQ6R-S-V3 with its DFlash2 drafter steps in 26.3 ms at TP2, against 29.4 ms before and FP8's 27.3 - Qwen MXFP4 feed-forward: the gated fold up to 16 rows, not 8 - libr4d: the gated prefill fold, the short-prompt split row, and the rows forms of rmsnorm and rope; KLATE again for the head-256 gqa6 paged prefill; gram_accum on the matrix cores Features: - /health, /v1/health and /ping answer 503 with "status": "stuck" once the device has advanced nothing for a minute or a queue has faulted, so a supervisor can restart a wedged server (#356) - --image-gen-max-pixels and --image-gen-max-refs size an image generator's buffers (#344) - The startup report lists only the options not at their default, with a count; -v lists all (#250) - --preempt-wait-ms bounds how long a preempted prefill waits for its whole-recompute room - --placement layer_offload spills dense layers so one --max-model-len sequence fits - Startup refuses amdgpu with CWSR off and says how to fix it; --proceed-with-incompatible-configuration starts anyway under an UNSUPPORTED banner Fixes: - The n-gram read-ahead hands each row to the reader once and reads only as far ahead as the row cache holds, and pauses while decode reads: about one drive read a row instead of two (#355) - A file-tier window reads each of its runs once, not once a run per run - The decode split law's verify floor is bounded by the batch's workgroups: max_seqs 256 no longer declares 64x the scratch (#342) - A prefetch DMA list's mark stays out of the signal pool until the engine has read it, and a prefill stage copies only the blocks its own tables name (#343) - The split-KV row sum is read with fetch-inactive (#328) - LFM2 on the host backend: libref and libavx serve the row-form ops it declares (#348) - The preempted-prefill gate skips a KV group that holds no blocks (#352) - Every request entry point bounded, gated and sanitised (JSON depth, invalid UTF-8, control bytes in the log, the dashboard's CSP, cross-origin browsers on the loopback-only routes); a prompt id outside the vocabulary refused at admission; --api-key "" refused at startup - The telemetry the HTTP thread reads is atomic - An RMS norm row no longer depends on how many rows its launch carries; prefill attention's rescale is decided by live rows only - A --kld-record prefill chunk that finishes no sequence gets its logits on a tied-head model - A kernel's lazily made counter block is zeroed outside the lock other ranks take (a TP2 first-step hang) Changes: Plugin ABI 32. Every plugin exports a layout fingerprint of the ABI structs and the loader refuses a plugin without it or with another (#302), so out-of-tree plugins must be rebuilt. Appended: RadBuildCtx calib_* and gen_max_*, RadArchProbe gen_max_*, RadBatch score_only and plugin_words, RadDeviceProps::unified, RadChatFormat arg_json_value_prefix.
434 lines
19 KiB
C++
434 lines
19 KiB
C++
/* systemone.cpp -- d1's prompt and readout (systemone.h).
|
|
*
|
|
* Every prompt string below is d1's own, from prompt.py in the model's repository: the user turn,
|
|
* the state block, the three question blocks, the option codes and their fallback codebook, and the
|
|
* yes/no spellings. The model was trained on exactly these; a reworded instruction or a different
|
|
* option code is a different, worse-calibrated question.
|
|
*
|
|
* That text is Liquid AI's, under the LFM Open License v1.0 (core/server/LICENSE.lfm, and NOTICE).
|
|
* This file is a C++ rewrite of prompt.py's and api.py's logic, modified from them, with their
|
|
* strings kept as they are.
|
|
*
|
|
* The tokenisation split also follows d1's runner: a single question's prompt is tokenised as one
|
|
* text; with several, the shared head (state and pictures) and each question's tail are tokenised
|
|
* separately, and the runner reads the head once and branches. BPE can merge across the join, so
|
|
* the two give different ids.
|
|
*/
|
|
#include "systemone.h"
|
|
|
|
#include "llama/src/unicode.h"
|
|
#include "mm/processor.h"
|
|
|
|
#include <nlohmann/json.hpp>
|
|
|
|
#include <algorithm>
|
|
#include <cctype>
|
|
#include <cmath>
|
|
#include <limits>
|
|
#include <unordered_set>
|
|
|
|
namespace rad {
|
|
namespace server {
|
|
|
|
namespace {
|
|
|
|
const char* const kImStart = "<|im_start|>";
|
|
const char* const kImEnd = "<|im_end|>";
|
|
|
|
|
|
/* The one id `text` encodes to, or -1 when it is not a single token. */
|
|
int32_t one_token(const ITokenizer& tok, const std::string& text) {
|
|
const std::vector<int32_t> ids = tok.encode(text, false, true);
|
|
return ids.size() == 1 ? ids[0] : -1;
|
|
}
|
|
|
|
/* An answer's spellings: the distinct single-token ones among `texts` (prompt.py, _ids). */
|
|
void add_answer(DecisionQuestion* q, const ITokenizer& tok, const std::vector<std::string>& texts) {
|
|
std::vector<size_t> group;
|
|
for (const std::string& t : texts) {
|
|
const int32_t id = one_token(tok, t);
|
|
if (id < 0) continue;
|
|
size_t at = 0;
|
|
while (at < q->candidates.size() && q->candidates[at] != id) ++at;
|
|
if (at == q->candidates.size()) q->candidates.push_back(id);
|
|
bool have = false;
|
|
for (size_t g : group) have = have || g == at;
|
|
if (!have) group.push_back(at);
|
|
}
|
|
q->groups.push_back(std::move(group));
|
|
}
|
|
|
|
/* Python's str.strip() and str.isalpha() over one stripped label. */
|
|
std::string strip(const std::string& s) {
|
|
const std::vector<uint32_t> c = unicode_cpts_from_utf8(s);
|
|
size_t a = 0, b = c.size();
|
|
while (a < b && unicode_cpt_flags_from_cpt(c[a]).is_whitespace) ++a;
|
|
while (b > a && unicode_cpt_flags_from_cpt(c[b - 1]).is_whitespace) --b;
|
|
std::string out;
|
|
for (size_t i = a; i < b; ++i) out += unicode_cpt_to_utf8(c[i]);
|
|
return out;
|
|
}
|
|
bool one_letter(const std::string& s) {
|
|
const std::vector<uint32_t> c = unicode_cpts_from_utf8(s);
|
|
return c.size() == 1 && unicode_cpt_flags_from_cpt(c[0]).is_letter;
|
|
}
|
|
|
|
std::string two_digits(size_t i) { return (i < 10 ? "0" : "") + std::to_string(i); }
|
|
|
|
/* prompt.py, option_codes: the labels themselves when every one is a single letter, else A..Z,
|
|
* else 00, 01, ... */
|
|
std::vector<std::string> option_codes(const std::vector<std::string>& labels) {
|
|
std::vector<std::string> codes;
|
|
bool letters = !labels.empty();
|
|
for (const std::string& l : labels) letters = letters && one_letter(strip(l));
|
|
for (size_t i = 0; i < labels.size(); ++i)
|
|
codes.push_back(letters ? strip(labels[i])
|
|
: labels.size() <= 26 ? std::string(1, (char)('A' + i)) : two_digits(i));
|
|
return codes;
|
|
}
|
|
|
|
/* prompt.py, _FALLBACK_POOL: where a code is not one token of its own, or is already taken. */
|
|
const std::vector<std::string>& fallback_pool() {
|
|
static const std::vector<std::string> pool = [] {
|
|
std::vector<std::string> v;
|
|
for (char c = 'A'; c <= 'Z'; ++c) v.emplace_back(1, c);
|
|
for (size_t i = 0; i < 100; ++i) v.push_back(two_digits(i));
|
|
for (char c = 'a'; c <= 'z'; ++c) v.emplace_back(1, c);
|
|
for (size_t i = 0; i < 200; ++i) v.push_back("#" + std::to_string(i));
|
|
for (char a = 'A'; a <= 'Z'; ++a)
|
|
for (char b = 'A'; b <= 'Z'; ++b) v.push_back(std::string{ a, b });
|
|
return v;
|
|
}();
|
|
return pool;
|
|
}
|
|
|
|
/* A string criterion, or null (Python's None, which a question block writes as "None"). */
|
|
bool text_or_null(const json& v, const std::string& path, ApiError* err) {
|
|
if (v.is_string() || v.is_null()) return true;
|
|
*err = err_bad(path, "must be a string or null");
|
|
return false;
|
|
}
|
|
std::string py_str(const json& v) { return v.is_null() ? "None" : v.get<std::string>(); }
|
|
|
|
/* One question: its block (prompt.py, question_block), the assistant header behind it, and the
|
|
* ids its answers are read at (readout_ids). */
|
|
int parse_question(const std::string& name, const json& src, const ITokenizer& tok,
|
|
DecisionQuestion* q, std::string* suffix, ApiError* err) {
|
|
const std::string path = "questions." + name;
|
|
auto bad = [&](const std::string& field, const std::string& why) {
|
|
*err = err_bad(path + field, why);
|
|
return RAD_E_INVAL;
|
|
};
|
|
if (!src.is_object()) return bad("", "must be an object");
|
|
if (!only_keys(src, { "type", "instructions", "criteria" }, path + ".", err)) return RAD_E_INVAL;
|
|
auto it = src.find("instructions");
|
|
if (it == src.end() || !it->is_string()) return bad(".instructions", "must be a string");
|
|
const std::string instructions = it->get<std::string>();
|
|
auto ty = src.find("type");
|
|
if (ty != src.end() && !ty->is_string()) return bad(".type", "must be noul, choice or score");
|
|
q->name = name;
|
|
q->type = ty == src.end() ? "choice" : ty->get<std::string>(); /* prompt.py's default */
|
|
const json criteria = src.contains("criteria") ? src.at("criteria") : json();
|
|
|
|
std::string block;
|
|
if (q->type == "noul") {
|
|
if (!criteria.is_null() && !criteria.is_object())
|
|
return bad(".criteria", "must be an object with `true` and `false`, or absent");
|
|
if (criteria.is_object()) {
|
|
if (!only_keys(criteria, { "true", "false" }, path + ".criteria.", err)) return RAD_E_INVAL;
|
|
for (const auto& kv : criteria.items())
|
|
if (!text_or_null(kv.value(), path + ".criteria." + kv.key(), err)) return RAD_E_INVAL;
|
|
}
|
|
block = instructions;
|
|
if (criteria.is_object() && !criteria.empty())
|
|
block += "\nYes: " + py_str(criteria.value("true", json())) +
|
|
"\nNo: " + py_str(criteria.value("false", json()));
|
|
block += "\n\nReply with yes or no only.";
|
|
q->labels = { "true", "false" };
|
|
add_answer(q, tok, { "yes", "Yes", "YES" });
|
|
add_answer(q, tok, { "no", "No", "NO" });
|
|
if (q->groups[0].empty() || q->groups[1].empty()) {
|
|
*err = err_not_implemented("this vocabulary has no single-token yes or no");
|
|
return RAD_E_UNSUPPORTED;
|
|
}
|
|
} else if (q->type == "choice") {
|
|
if (!criteria.is_object() || criteria.empty())
|
|
return bad(".criteria", "must be a non-empty object of option names to descriptions");
|
|
std::vector<std::string> descs;
|
|
for (const auto& kv : criteria.items()) {
|
|
if (!text_or_null(kv.value(), path + ".criteria." + kv.key(), err)) return RAD_E_INVAL;
|
|
q->labels.push_back(kv.key());
|
|
std::string d = kv.value().is_null() ? std::string() : kv.value().get<std::string>();
|
|
if (d.empty()) { /* `desc or label.replace("_", " ")` */
|
|
d = kv.key();
|
|
for (char& c : d) if (c == '_') c = ' ';
|
|
}
|
|
descs.push_back(std::move(d));
|
|
}
|
|
/* prompt.py, aliases: each option's code if it is one token nobody has, else the first
|
|
* fallback that is. Then readout_ids: the code, and " code" where that is one token. */
|
|
std::unordered_set<int32_t> used;
|
|
block = instructions + "\n\nOptions:\n";
|
|
const std::vector<std::string> codes = option_codes(q->labels);
|
|
for (size_t i = 0; i < codes.size(); ++i) {
|
|
std::string code;
|
|
int32_t id = one_token(tok, codes[i]);
|
|
if (id >= 0 && !used.count(id)) code = codes[i];
|
|
else {
|
|
id = -1;
|
|
for (const std::string& f : fallback_pool()) {
|
|
const int32_t t = one_token(tok, f);
|
|
if (t >= 0 && !used.count(t)) { id = t; code = f; break; }
|
|
}
|
|
}
|
|
if (id < 0) return bad(".criteria", "more options than this vocabulary has distinct "
|
|
"single-token codes for");
|
|
used.insert(id);
|
|
if (i) block += "\n";
|
|
block += code + " " + descs[i];
|
|
add_answer(q, tok, { code, " " + code });
|
|
}
|
|
block += "\n\nReply with the option code only.";
|
|
} else if (q->type == "score") {
|
|
if (!criteria.is_array() || criteria.size() < 2 || criteria.size() > 10)
|
|
return bad(".criteria", "must be an array of 2 to 10 level descriptions, lowest first");
|
|
block = instructions + "\n\n";
|
|
for (size_t i = 0; i < criteria.size(); ++i) {
|
|
if (!criteria[i].is_string()) return bad(".criteria", "each level must be a string");
|
|
q->labels.push_back(std::to_string(i));
|
|
q->legend.push_back(criteria[i].get<std::string>());
|
|
if (i) block += "\n";
|
|
block += q->labels.back() + " " + q->legend.back();
|
|
add_answer(q, tok, { q->labels.back() });
|
|
if (q->groups.back().empty()) {
|
|
*err = err_not_implemented("this vocabulary has no single-token digit " +
|
|
q->labels.back());
|
|
return RAD_E_UNSUPPORTED;
|
|
}
|
|
}
|
|
block += "\n\nReply with a single digit 0-" + std::to_string(criteria.size() - 1) + " only.";
|
|
} else {
|
|
return bad(".type", "must be noul, choice or score");
|
|
}
|
|
*suffix = block + kImEnd + "\n" + kImStart + "assistant\n";
|
|
return RAD_OK;
|
|
}
|
|
|
|
/* prompt.py, state_block at its default style: a string as it is, anything else as indented JSON
|
|
* in the order the request gave its keys. */
|
|
std::string state_block(const json& state) {
|
|
return (state.is_string() ? state.get<std::string>() : state.dump(2)) + "\n\n";
|
|
}
|
|
|
|
} /* namespace */
|
|
|
|
/* ---- shared by the System One models (systemone.h) */
|
|
|
|
bool only_keys(const json& o, std::initializer_list<const char*> 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;
|
|
}
|
|
|
|
std::string py_json_dumps(const json& v) {
|
|
if (v.is_object()) {
|
|
std::string s = "{";
|
|
bool first = true;
|
|
for (const auto& kv : v.items()) {
|
|
if (!first) s += ", ";
|
|
first = false;
|
|
s += json(kv.key()).dump(-1, ' ', false, json::error_handler_t::replace) + ": " +
|
|
py_json_dumps(kv.value());
|
|
}
|
|
return s + "}";
|
|
}
|
|
if (v.is_array()) {
|
|
std::string s = "[";
|
|
for (size_t i = 0; i < v.size(); ++i) s += (i ? ", " : "") + py_json_dumps(v[i]);
|
|
return s + "]";
|
|
}
|
|
return v.dump(-1, ' ', false, json::error_handler_t::replace);
|
|
}
|
|
|
|
std::string py_json_compact_sorted(const json& v) {
|
|
/* 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);
|
|
}
|
|
|
|
bool blank_text(const std::string& s) {
|
|
return std::all_of(s.begin(), s.end(), [](unsigned char c) { return std::isspace(c) != 0; });
|
|
}
|
|
|
|
|
|
int parse_decision_request(const std::string& body, const OaiDeps& d, const OaiLimits& lim,
|
|
const std::string& model_id, DecisionRequest* out, ApiError* err) {
|
|
*out = DecisionRequest{};
|
|
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")) {
|
|
*err = err_bad("state", "required: a string, any JSON value, or null with images");
|
|
return RAD_E_INVAL;
|
|
}
|
|
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;
|
|
}
|
|
|
|
/* Pictures are decoded here and processed when the head is tokenised. */
|
|
std::vector<std::pair<MediaKind, std::vector<uint8_t>>> media;
|
|
if (b.contains("images")) {
|
|
const json& im = b["images"];
|
|
if (!im.is_array()) { *err = err_bad("images", "must be an array of data: URLs"); return RAD_E_INVAL; }
|
|
if (!im.empty() && (!d.mm || !d.mm->accepts(MediaKind::Image))) {
|
|
*err = err_not_implemented("images need the model's image encoder, and this deployment "
|
|
"has none loaded");
|
|
return RAD_E_UNSUPPORTED;
|
|
}
|
|
for (size_t i = 0; i < im.size(); ++i) {
|
|
const std::string field = "images[" + std::to_string(i) + "]";
|
|
if (!im[i].is_string()) { *err = err_bad(field, "must be a data: URL"); return RAD_E_INVAL; }
|
|
std::vector<uint8_t> bytes;
|
|
RAD_TRY(decode_media_url(im[i].get<std::string>(), field, &bytes, err));
|
|
media.push_back({ MediaKind::Image, std::move(bytes) });
|
|
}
|
|
}
|
|
|
|
/* prompt.py, prefix_text: BOS, the user turn, the pictures as the chat template writes them
|
|
* (one marker each, which the processor expands), then the state. A null state leaves the
|
|
* question right behind the pictures. */
|
|
const std::string marker = RAD_MEDIA_MARKER;
|
|
std::string head;
|
|
if (d.tok->bos() >= 0) head += d.tok->token_bytes(d.tok->bos());
|
|
head += std::string(kImStart) + "user\n";
|
|
for (size_t i = 0; i < media.size(); ++i) head += marker;
|
|
std::string body_text;
|
|
if (!b["state"].is_null()) body_text = state_block(b["state"]) + "\nQUESTION:\n";
|
|
if (body_text.find(marker) != std::string::npos) {
|
|
*err = err_bad("state", "contains \"" + marker + "\", which this server reserves");
|
|
return RAD_E_INVAL;
|
|
}
|
|
head += body_text;
|
|
|
|
std::vector<std::string> suffixes;
|
|
for (const auto& kv : qs.items()) {
|
|
DecisionQuestion q;
|
|
std::string suffix;
|
|
RAD_TRY(parse_question(kv.key(), kv.value(), *d.tok, &q, &suffix, err));
|
|
if (!media.empty() && suffix.find(marker) != std::string::npos) {
|
|
*err = err_bad("questions." + kv.key(), "contains \"" + marker + "\", which this "
|
|
"server reserves");
|
|
return RAD_E_INVAL;
|
|
}
|
|
out->questions.push_back(std::move(q));
|
|
suffixes.push_back(std::move(suffix));
|
|
}
|
|
|
|
/* runner.py, VISION_MAX_PIXELS: d1 caps every picture at 1024 x 1024 pixels' area before its
|
|
* processor, so the same cap applies here. */
|
|
MediaOpts opts;
|
|
opts.max_pixels = 1024 * 1024;
|
|
auto tokenize = [&](const std::string& text, std::vector<int32_t>* ids) -> int {
|
|
if (media.empty()) { *ids = d.tok->encode(text, false, true); return RAD_OK; }
|
|
PromptInput in;
|
|
RAD_TRY(tokenize_with_media(text, d, media, opts, &in, err));
|
|
*ids = std::move(in.tokens);
|
|
out->media = std::move(in.media);
|
|
return RAD_OK;
|
|
};
|
|
if (out->questions.size() == 1) {
|
|
RAD_TRY(tokenize(head + suffixes[0], &out->questions[0].tokens));
|
|
out->input_tokens = (int64_t)out->questions[0].tokens.size();
|
|
} else {
|
|
std::vector<int32_t> trunk;
|
|
RAD_TRY(tokenize(head, &trunk));
|
|
out->trunk = (int32_t)trunk.size();
|
|
out->input_tokens = (int64_t)trunk.size();
|
|
for (size_t i = 0; i < out->questions.size(); ++i) {
|
|
std::vector<int32_t>& t = out->questions[i].tokens;
|
|
const std::vector<int32_t> tail = d.tok->encode(suffixes[i], false, true);
|
|
t = trunk;
|
|
t.insert(t.end(), tail.begin(), tail.end());
|
|
out->input_tokens += (int64_t)tail.size();
|
|
}
|
|
}
|
|
/* One position stays free for the token the request samples and discards. */
|
|
for (const DecisionQuestion& q : out->questions)
|
|
if (lim.max_ctx > 0 && (int64_t)q.tokens.size() >= lim.max_ctx) {
|
|
ApiError e = err_bad("questions." + q.name,
|
|
"the prompt is " + std::to_string(q.tokens.size()) +
|
|
" tokens; this deployment's context holds " +
|
|
std::to_string(lim.max_ctx - 1) + " for a decision");
|
|
e.code = "context_length_exceeded";
|
|
*err = e;
|
|
return RAD_E_INVAL;
|
|
}
|
|
return RAD_OK;
|
|
}
|
|
|
|
int decision_answer(const DecisionQuestion& q, const std::vector<float>& logits, json* out,
|
|
ApiError* err) {
|
|
if (logits.size() != q.candidates.size() || q.groups.size() != q.labels.size()) {
|
|
*err = err_internal("the engine returned no scores for question " + q.name);
|
|
return RAD_E_STATE;
|
|
}
|
|
std::vector<double> p;
|
|
for (const std::vector<size_t>& g : q.groups) {
|
|
double best = -std::numeric_limits<double>::infinity();
|
|
for (size_t i : g) best = std::max(best, (double)logits[i]);
|
|
if (!std::isfinite(best)) {
|
|
*err = err_internal("question " + q.name + " scored a non-finite logit");
|
|
return RAD_E_STATE;
|
|
}
|
|
p.push_back(best);
|
|
}
|
|
const double peak = *std::max_element(p.begin(), p.end());
|
|
double total = 0.0;
|
|
for (double& v : p) total += (v = std::exp(v - peak));
|
|
for (double& v : p) v /= total;
|
|
|
|
/* api.py, answer. */
|
|
json a = json::object();
|
|
a["type"] = q.type;
|
|
if (q.type == "noul") {
|
|
a["noul"] = p[0];
|
|
*out = std::move(a);
|
|
return RAD_OK;
|
|
}
|
|
const size_t best = (size_t)(std::max_element(p.begin(), p.end()) - p.begin());
|
|
json probs = json::object();
|
|
for (size_t i = 0; i < p.size(); ++i) probs[q.labels[i]] = p[i];
|
|
if (q.type == "choice") {
|
|
a["choice"] = q.labels[best];
|
|
} else {
|
|
double expected = 0.0;
|
|
for (size_t i = 0; i < p.size(); ++i) expected += (double)i * p[i];
|
|
a["score"] = expected;
|
|
}
|
|
a["confidence"] = p[best];
|
|
a["probabilities"] = std::move(probs);
|
|
if (q.type == "score") {
|
|
json legend = json::object();
|
|
for (size_t i = 0; i < q.legend.size(); ++i) legend[q.labels[i]] = q.legend[i];
|
|
a["legend"] = std::move(legend);
|
|
}
|
|
*out = std::move(a);
|
|
return RAD_OK;
|
|
}
|
|
|
|
} /* namespace server */
|
|
} /* namespace rad */
|