radiance 1.4.0

- Qwen3.8-Flash-Next on one card: the heat engine moves 64 experts a step (was 8), its copies and
  the prefill's expert staging run on the card's DMA engines instead of as copy kernels, and at
  decode the next layer's likeliest experts are copied onto the card ahead of its GEMMs. Against
  1.3.0 at --tp 1: prefill +17-20% from 8K tokens up, throughput under load +16-20%
- deploy/compose/flashnext-tp1.yaml: Qwen3.8-Flash-Next on one card and 64 GB of host RAM
  (4096-token prefill steps, 4 sequences, a 301K-token cache)
- #61: --busy-prefill-chunk (default auto): a long prefill leaves the rest of the step to the
  requests decoding beside it and to new arrivals, instead of taking all of it (baKon)
- LiquidAI's LFM2 and LFM2-VL, and d1's /v1/systemone (after zivius's PR #50)
- a startup report: every option with its value and where it came from, the hardware, and what
  on it costs speed with the fix; /diagnostics serves it (behind the API key; without one, only
  to the same machine)
- #69: a GPU memory fault names the buffer and kernel argument behind it and ends the server at
  once (exit status 70), instead of hanging or writing a core of tens of gigabytes
- #64: a card without Resizable BAR is refused at startup, naming what to turn on, instead of
  crashing at the first launch
- the image is built with ROCm 10.1 (the host's amdgpu driver must support it), with ROCm's
  libLLVM rebuilt so the same source compiles to the same kernels every time; a source build
  takes ROCm 10.1 or 7.2
- #71: the image ships curl, jq and a CA bundle, so --model <HF repo id> works in the container,
  and hfget.sh runs under its busybox (baKon)
- --profile-ops shows how long each op's lane sat idle before it; cardclock.py skips an
  integrated GPU instead of stopping
This commit is contained in:
Deadcode committed 2026-10-12 11:46:14 +02:00
1 parent d5b65cddc6
commit dc339b4cd2
153 files changed
+12956 -1067

No files matched your search

+71
View File
@@ -0,0 +1,71 @@
LFM Open License v1.0
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by this document.
"Licensor" shall mean Liquid AI, Inc.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work.
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
"Commercial Use" shall mean any use of the Work for direct or indirect commercial advantage or monetary compensation.
"Qualified Non-Profit Organization" shall mean a Legal Entity that is organized and operated exclusively for religious, charitable, scientific, testing for public safety, literary, or educational purposes, and which is exempt from federal income tax under Section 501(c)(3) of the United States Internal Revenue Code of 1986, as amended, or any equivalent non-profit or charitable organization in a foreign jurisdiction.
"Non-Commercial or Research Purposes" shall mean purposes that do not involve any use of the Work or a Derivative Work for Commercial Use.
"Threshold" shall mean annual revenue of 10 million United States dollars ($10,000,000) or more.
2. Grant of Copyright License. Subject to the terms and conditions of this License, including the Commercial Use limitation set forth in Section 5, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, including the Commercial Use limitation set forth in Section 5, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Commercial Use Limitation.
(a) The rights granted under this License for Commercial Use are conditioned upon You or Your Legal Entity not exceeding the Threshold.
(b) Any Commercial Use of the Work or a Derivative Work by a Legal Entity that exceeds the Threshold is not licensed under this Agreement.
(c) The Threshold shall not apply to a Qualified Non-Profit Organization's use of the Work or a Derivative Work for Non-Commercial or Research Purposes.
6. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
7. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except for the reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
8. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
9. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
10. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
11. Termination. This License will terminate automatically and immediately if You fail to comply with any of its terms and conditions. Upon termination, You must cease all use of the Work and any Derivative Works and delete all copies in Your possession.
END OF TERMS AND CONDITIONS
+2 -1
View File
@@ -733,7 +733,8 @@ public:
if (!accepts(k)) { if (why) *why = "this kind of media is not served"; return RAD_E_UNSUPPORTED; }
if (k == MediaKind::Audio) return p_->audio(bytes.data(), bytes.size(), out, why);
return k == MediaKind::Image
? p_->image(bytes.data(), bytes.size(), opts.image_tokens, out, why)
? p_->image(bytes.data(), bytes.size(), opts.image_tokens, out, why,
opts.max_pixels)
: p_->video(bytes.data(), bytes.size(), out, why);
}
+26
View File
@@ -534,6 +534,32 @@ HttpResponse Server::handle_server_info(const HttpRequest&) {
return HttpResponse::json_body(200, json_dump(o));
}
/* ================================================================== /diagnostics */
/* The startup report, read again for this request (ServerOptions::diagnostics_json). Behind the
* bearer key like /server_info: it names the machine's devices and boot parameters.
*
* AND WITHOUT A KEY, ONLY TO THIS MACHINE. /server_info without a key describes the model a
* client is already talking to; this describes the host -- its kernel, its boot parameters, its
* PCI layout, its memory limits -- which a server bound to 0.0.0.0 with no key would otherwise
* hand to anyone who can reach the port. A key is the operator's statement of who may ask. */
HttpResponse Server::handle_diagnostics(const HttpRequest& req) {
if (!opt_.diagnostics_json)
return error_response(err_not_implemented(
"the server was not given a diagnostics provider; this build has no engine attached"),
req.peer);
if (opt_.api_key.empty() && !req.peer_is_loopback()) {
ApiError e;
e.status = 403;
e.type = "permission_error";
e.message = "/diagnostics describes this machine, and a server started without --api-key "
"answers it only to a client on the same machine (a loopback address); start "
"it with --api-key to read it from elsewhere";
return error_response(e, req.peer);
}
metrics_.observe_http(200);
return HttpResponse::json_body(200, opt_.diagnostics_json());
}
/* ================================================================== /reset_prefix_cache */
/* 501 when there is no prefix cache to reset, and that is the point: vLLM answers 200 with an
* empty body whether or not anything happened, so a benchmark that thinks it started cold has no
+1
View File
@@ -313,6 +313,7 @@ HttpResponse Server::handle_stats(const HttpRequest&) {
e["staged_units"] = s.experts.staged_units;
e["staged_bytes"] = (double)s.experts.staged_bytes;
e["stage_overflow"] = s.experts.stage_overflow;
e["stage_copies"] = s.experts.stage_copies;
o["experts"] = std::move(e);
}
+24 -2
View File
@@ -5,6 +5,9 @@
* translation unit so that nothing above the transport seam pays for it. */
#include "cpp-httplib/httplib.h"
#include <arpa/inet.h>
#include <netinet/in.h>
#include <algorithm>
#include <atomic>
#include <cctype>
@@ -37,6 +40,26 @@ std::string HttpRequest::param(const std::string& k, const std::string& def) con
return q == query.end() ? def : q->second;
}
bool HttpRequest::peer_is_loopback() const {
if (peer.empty()) return true;
/* "addr:port", where an IPv6 address carries colons of its own: the port is after the last. */
const size_t colon = peer.rfind(':');
std::string addr = colon == std::string::npos ? peer : peer.substr(0, colon);
if (addr.size() >= 2 && addr.front() == '[' && addr.back() == ']')
addr = addr.substr(1, addr.size() - 2);
in_addr v4{};
if (inet_pton(AF_INET, addr.c_str(), &v4) == 1) return (ntohl(v4.s_addr) >> 24) == 127;
in6_addr v6{};
if (inet_pton(AF_INET6, addr.c_str(), &v6) != 1) return false;
if (IN6_IS_ADDR_LOOPBACK(&v6)) return true;
return IN6_IS_ADDR_V4MAPPED(&v6) && v6.s6_addr[12] == 127;
}
int idle_workers(int n_threads) {
const int n = n_threads > 0 ? n_threads : (int)std::thread::hardware_concurrency();
return std::max(n, 4);
}
HttpResponse HttpResponse::json_body(int status, std::string body) {
HttpResponse r;
r.status = status;
@@ -326,8 +349,7 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) {
svr.set_keep_alive_timeout(o.keep_alive_timeout_s);
svr.set_payload_max_length(o.max_body_bytes);
int nt = o.n_threads > 0 ? o.n_threads : (int)std::thread::hardware_concurrency();
if (nt < 4) nt = 4;
const int nt = idle_workers(o.n_threads);
const size_t most = (size_t)std::max<int64_t>(o.max_threads, nt);
const size_t queued = (size_t)std::max<int64_t>(o.max_queued, 0);
svr.new_task_queue = [nt, most, queued] { return new ConnectionPool((size_t)nt, most, queued); };
+8
View File
@@ -41,6 +41,9 @@ struct HttpRequest {
std::string header(const std::string& k, const std::string& def = "") const;
std::string param(const std::string& k, const std::string& def = "") const;
bool peer_gone() const { return closed && closed(); }
/* True when the peer is this machine: 127.0.0.0/8, ::1, or either written as an IPv4-mapped
* IPv6 address -- and for a request made in-process, which has no peer. */
bool peer_is_loopback() const;
};
struct HttpResponse {
@@ -129,6 +132,11 @@ struct TransportOptions {
bool cors = true;
};
/* The workers the pool keeps while idle for TransportOptions::n_threads: that many, one a
* hardware thread for 0, and never fewer than 4. One definition, so the number the startup
* report states is the number the transport runs. */
int idle_workers(int n_threads);
class HttpTransport {
public:
HttpTransport();
+3
View File
@@ -583,6 +583,9 @@ struct MediaOpts {
/* Soft tokens (encoder output rows) an image may become, for a processor that sizes images
* by a token budget (Gemma 4's: 70, 140, 280, 560 or 1120). */
int32_t image_tokens = 0;
/* A picture over this many pixels is first scaled down to that area (PIL's bicubic, sides
* truncated), as a model's own pipeline may do before its processor; 0 leaves it as sent. */
int64_t max_pixels = 0;
};
class IMultimodal {
+3 -1
View File
@@ -89,8 +89,10 @@ struct ExpertPlane {
int64_t routed = 0, routed_resident = 0;
int64_t no_record = 0, starved_slab = 0, starved_pool = 0, quarantined = 0;
/* The prefill stager's copies (Mover::stage_units), rank 0: layers staged, units and bytes
* copied onto the card, and pooled units a buffer had no room for. */
* copied onto the card, pooled units a buffer had no room for, and the copies that carried
* the units. */
int64_t stage_layers = 0, staged_units = 0, staged_bytes = 0, stage_overflow = 0;
int64_t stage_copies = 0;
/* HOW MUCH OF THE SLAB IS BORROWED. `flex_bytes` is what the slab holds in VRAM the KV cache
* lent it; `flex_capacity` is how much the cache is lending right now. The pair is what says
* whether the boundary between the two pools is moving, and whether what was lent is being
+5 -5
View File
@@ -1190,8 +1190,8 @@ static const char* const MEDIA_MARKER = RAD_MEDIA_MARKER;
* arbitrary http(s) URL on a caller's behalf turns the inference server into an SSRF proxy with
* network access to everything the deployment can reach, and no amount of allowlisting makes
* that a good default. */
static int decode_media_url(const std::string& url, const std::string& field,
std::vector<uint8_t>* out, ApiError* err) {
int decode_media_url(const std::string& url, const std::string& field,
std::vector<uint8_t>* out, ApiError* err) {
if (url.rfind("data:", 0) != 0) {
*err = err_bad(field, "only data: URLs are accepted; the server does not fetch remote URLs "
"on a request's behalf");
@@ -1462,9 +1462,9 @@ static int lower_content_parts(json& messages, const OaiDeps& d, const OaiLimits
* Each media part is processed HERE, on the request's own worker, because decoding a video and
* resizing its frames is the most expensive host work a request can bring: it must not reach the
* scheduler's thread, where every other request's step would wait on it. */
static int tokenize_with_media(const std::string& rendered, const OaiDeps& d,
std::vector<std::pair<MediaKind, std::vector<uint8_t>>>& media,
const MediaOpts& opts, PromptInput* out, ApiError* err) {
int tokenize_with_media(const std::string& rendered, const OaiDeps& d,
std::vector<std::pair<MediaKind, std::vector<uint8_t>>>& media,
const MediaOpts& opts, PromptInput* out, ApiError* err) {
out->text = rendered;
auto pm = std::make_shared<mm::PromptMedia>();
const std::string marker = MEDIA_MARKER;
+8
View File
@@ -291,6 +291,14 @@ int parse_chat_request(const std::string& body, const OaiDeps& d, const OaiLimit
* token ids mixed as ONE prompt, as llama-server reads it. */
int parse_completion_request(const std::string& body, const OaiDeps& d, const OaiLimits& lim,
OaiRequest* out, ApiError* err, bool native = false);
/* A media part's bytes out of a data: URL; any other URL is refused, never fetched. */
int decode_media_url(const std::string& url, const std::string& field,
std::vector<uint8_t>* out, ApiError* err);
/* A prompt holding RAD_MEDIA_MARKER once a media part, tokenised with each marker replaced by its
* part's processed token run; `media` is consumed in order. */
int tokenize_with_media(const std::string& rendered, const OaiDeps& d,
std::vector<std::pair<MediaKind, std::vector<uint8_t>>>& media,
const MediaOpts& opts, PromptInput* out, ApiError* err);
/* Embeddings: fills `out->prompts` with one entry per input. */
int parse_embeddings_request(const std::string& body, const OaiDeps& d, const OaiLimits& lim,
OaiRequest* out, ApiError* err);
+155
View File
@@ -2,6 +2,7 @@
#include <cstdio>
#include "json_partial.h"
#include "systemone.h"
#include "rad_internal.h"
#include "text/tokenizer.h"
@@ -136,6 +137,7 @@ void Server::register_routes() {
router_.post("/v1/chat/completions", [this](const HttpRequest& q) { return handle_chat(q); });
router_.post("/v1/completions", [this](const HttpRequest& q) { return handle_completion(q); });
router_.post("/v1/embeddings", [this](const HttpRequest& q) { return handle_embeddings(q); });
router_.post("/v1/systemone", [this](const HttpRequest& q) { return handle_systemone(q); });
router_.get ("/v1/models", [this](const HttpRequest& q) { return handle_models(q); });
router_.get ("/v1/models/:id", [this](const HttpRequest& q) { return handle_models(q); });
/* THE SAME ROUTES WITHOUT /v1, as llama-server answers them: a client configured with the
@@ -175,6 +177,7 @@ void Server::register_routes() {
router_.get ("/version", [this](const HttpRequest& q) { return handle_version(q); });
router_.get ("/server_info", [this](const HttpRequest& q) { return handle_server_info(q); });
router_.get ("/props", [this](const HttpRequest& q) { return handle_props(q); });
router_.get ("/diagnostics", [this](const HttpRequest& q) { return handle_diagnostics(q); });
router_.post("/tokenize", [this](const HttpRequest& q) { return handle_tokenize(q); });
router_.post("/detokenize", [this](const HttpRequest& q) { return handle_detokenize(q); });
@@ -1723,6 +1726,158 @@ HttpResponse Server::handle_embeddings(const HttpRequest& req) {
return HttpResponse::json_body(200, embeddings_body(r, vecs, u));
}
/* /v1/systemone (systemone.h): one request a question, each reading its answer's candidates at
* the prompt's last position (Request::token_scores) and sampling one token nobody reads.
*
* SEVERAL QUESTIONS SHARE THE STATE THEY ARE ASKED OVER, and it is read once. The first question
* runs alone and leaves the state at the end of that shared head in the prefix cache -- its
* attention blocks, and a checkpoint of the convolutions there (Request::checkpoint_at) -- and the
* rest are submitted together once it has finished, each starting from that head and computing
* only its own tail. d1's own runner shares the head the same way, as one batched tree. */
HttpResponse Server::handle_systemone(const HttpRequest& req) {
if (!deps_.sched || !deps_.tok)
return error_response(err_not_implemented("the server has no engine attached"), req.peer);
if (opt_.decision_type != "d1")
return error_response(err_not_implemented(
"/v1/systemone serves a decision model; this container does not declare one "
"(convert d1 with --set decision.type=d1)"), req.peer);
DecisionRequest r;
ApiError err;
if (parse_decision_request(req.body, odeps_, lim_, opt_.model_id, &r, &err) < 0)
return error_response(err, req.peer);
sweep_abandoned();
const int n = (int)r.questions.size();
if (!admit(n)) {
metrics_.observe_rejected();
return error_response(err_overloaded(
"the admission queue is full; retry after " + std::to_string(opt_.retry_after_s) +
"s. The server refuses rather than queueing without bound"), req.peer);
}
RAD_INFO("systemone admitted%s questions=%d prompt=%lld tok", from_peer(req.peer).c_str(), n,
(long long)r.input_tokens);
std::vector<Generation> gens;
std::vector<Request> rqs;
std::vector<std::shared_ptr<TokenScores>> scores;
for (int i = 0; i < n; ++i) {
Generation g;
g.index = i;
g.sink = std::make_shared<Sink>(16);
auto ts = std::make_shared<TokenScores>();
ts->tokens = r.questions[(size_t)i].candidates;
Request rq;
rq.prompt = r.questions[(size_t)i].tokens;
rq.media = r.media;
rq.token_scores = ts;
rq.max_tokens = 1;
rq.sp.temp = 0.0f;
rq.sink = g.sink.get();
if (i == 0 && n > 1) rq.checkpoint_at = r.trunk;
rqs.push_back(std::move(rq));
gens.push_back(std::move(g));
scores.push_back(std::move(ts));
}
/* The questions handed to the scheduler so far: an early exit retires those and drops the
* rest, whose sinks nothing will ever finish. */
size_t submitted = 0;
auto fail = [&](const std::string& why) {
gens.resize(submitted);
retire(gens);
release(n);
ApiError e;
e.status = 500;
e.type = "internal_server_error";
e.message = why;
return error_response(e, req.peer);
};
/* Questions [first, last) submitted together and waited for. A non-null response is the
* call's answer already: the scheduler refused one, the client left, or the server stops. */
std::unique_ptr<HttpResponse> early;
auto run = [&](int first, int last) {
std::vector<Request> part(std::make_move_iterator(rqs.begin() + first),
std::make_move_iterator(rqs.begin() + last));
std::vector<uint64_t> ids;
deps_.sched->submit_all(part, &ids);
submitted = (size_t)last;
for (size_t k = 0; k < ids.size(); ++k) {
Generation& g = gens[(size_t)first + k];
g.id = ids[k];
g.sink->id = ids[k];
if (!ids[k]) {
early = std::make_unique<HttpResponse>(
fail("the scheduler refused question " + r.questions[(size_t)first + k].name));
return;
}
}
for (;;) {
bool all = true;
for (int i = first; i < last; ++i) {
Generation& g = gens[(size_t)i];
if (!g.closed && g.sink->done()) { g.closed = true; g.finish = g.sink->finish_reason(); }
all = all && g.closed;
}
if (all) return;
if (req.peer_gone()) {
gens.resize(submitted);
cancel_all(gens, true);
retire(gens);
release(n);
metrics_.observe_http(499);
early = std::make_unique<HttpResponse>(
HttpResponse::text(499, "client closed request\n"));
return;
}
if (stopping_.load()) {
gens.resize(submitted);
cancel_all(gens, false);
retire(gens);
release(n);
early = std::make_unique<HttpResponse>(
error_response(err_overloaded("the server is shutting down"), req.peer));
return;
}
for (int i = first; i < last; ++i)
if (!gens[(size_t)i].closed) { gens[(size_t)i].sink->wait(); break; }
}
};
run(0, 1);
if (early) return std::move(*early);
/* A first question that failed fails the call; the rest would only repeat it. */
if (gens[0].finish == Finish::Error || gens[0].finish == Finish::Cancelled)
return fail(gens[0].finish == Finish::Error ? engine_failure(*gens[0].sink)
: "the engine cancelled question " +
r.questions[0].name);
if (n > 1) {
run(1, n);
if (early) return std::move(*early);
}
json answers = json::object();
for (size_t i = 0; i < gens.size(); ++i) {
const Generation& g = gens[i];
if (g.finish == Finish::Error || g.finish == Finish::Cancelled)
return fail(g.finish == Finish::Error ? engine_failure(*g.sink)
: "the engine cancelled question " +
r.questions[i].name);
json a;
if (decision_answer(r.questions[i], scores[i]->logits, &a, &err) < 0) {
retire(gens);
release(n);
return error_response(err, req.peer);
}
answers[r.questions[i].name] = std::move(a);
}
retire(gens);
release(n);
metrics_.observe_http(200);
return HttpResponse::json_body(200, json_dump(json{
{ "answers", std::move(answers) },
{ "usage", { { "input_tokens", r.input_tokens }, { "output_tokens", 0 } } } }));
}
HttpResponse Server::handle_models(const HttpRequest& req) {
const std::string id = req.param("id");
if (!id.empty() && id != opt_.model_id) {
+14
View File
@@ -57,6 +57,9 @@ struct ServerOptions {
* /v1/completions answer 501 naming /v1/embeddings, rather than queueing a request the engine
* would finish after one step with no text. */
bool embedding_model = false;
/* WHICH DECISION PROTOCOL THE MODEL WAS TRAINED ON, from the container's `decision.type`:
* "d1" serves /v1/systemone (systemone.h); empty answers it 501. Never inferred from a name. */
std::string decision_type;
/* What --model named, reported as the model entry's `root` the way vLLM reports the path it
* loaded: a served name chosen for clients says nothing about which file is behind it. Empty
* leaves the field out. */
@@ -121,6 +124,13 @@ struct ServerOptions {
* showing an op as unissued one step before it flips. Registry::select is asked with
* record = false and mutates nothing else. */
std::function<std::string()> graph_json;
/* THE STARTUP REPORT READ AGAIN, as JSON (core/diag/diag.h): the options in force, the machine
* as it is now (the provider may reuse a reading for a second), and what on it costs speed.
* Without a key it is answered to loopback clients only (Server::handle_diagnostics). A
* provider like the graph's, because a card's link speed and clock only say anything under
* load -- a request made during a long prefill is how a link parked below its maximum is told
* from one at rest. */
std::function<std::string()> diagnostics_json;
std::string api_key;
bool cors = true;
@@ -171,6 +181,8 @@ public:
int port() const { return transport_.port(); } /* 0 until run() is accepting */
int64_t in_flight() const { return in_flight_.load(std::memory_order_relaxed); }
/* The admission ceiling as resolved: ServerOptions::queue_depth, or 8 x max_seqs for 0. */
int64_t queue_cap() const { return queue_depth_; }
private:
struct Generation;
@@ -185,6 +197,7 @@ private:
HttpResponse handle_chat(const HttpRequest& req);
HttpResponse handle_completion(const HttpRequest& req);
HttpResponse handle_embeddings(const HttpRequest& req);
HttpResponse handle_systemone(const HttpRequest& req);
HttpResponse handle_models(const HttpRequest& req);
HttpResponse handle_metrics(const HttpRequest& req);
@@ -213,6 +226,7 @@ private:
HttpResponse handle_detokenize(const HttpRequest& req);
HttpResponse handle_tokenizer_info(const HttpRequest& req);
HttpResponse handle_server_info(const HttpRequest& req);
HttpResponse handle_diagnostics(const HttpRequest& req);
/* What this deployment can do -- chat, tools, reasoning, grammar, media, logprobs, the
* reasoning efforts it takes -- as /server_info's `capabilities` and the model entry both
* report it, built in one place so the two cannot disagree. */
+404
View File
@@ -0,0 +1,404 @@
/* systemone.cpp -- d1's prompt and readout (systemone.h).
*
* EVERY 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, the
* yes/no spellings. The model was trained on exactly these, so a reworded instruction or a
* different code for an option is a different (and 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.
*
* AND SO IS THE TOKENISATION SPLIT. d1 tokenises a single question's prompt as one text, and a
* request with several as the shared head (the state and the pictures) followed by each question's
* tail, tokenised separately -- its runner reads the head once and branches. The two are not the
* same ids where BPE would merge across the join, so each case is tokenised the way the model's
* own runner does.
*/
#include "systemone.h"
#include "llama/src/unicode.h"
#include "mm/processor.h"
#include <nlohmann/json.hpp>
#include <cmath>
#include <limits>
#include <unordered_set>
namespace rad {
namespace server {
namespace {
const char* const kImStart = "<|im_start|>";
const char* const kImEnd = "<|im_end|>";
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;
}
/* 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 */
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;
}
/* THE PICTURES, 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 bounds every picture at 1024 x 1024 pixels' area before
* its processor, so a larger one is a different input unless it is bounded here too. */
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: the request samples a token, which nobody reads. */
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 = ApiError{};
err->status = 500;
err->type = "internal_server_error";
err->message = "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 = ApiError{};
err->status = 500;
err->type = "internal_server_error";
err->message = "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 */
+59
View File
@@ -0,0 +1,59 @@
/* systemone.h -- POST /v1/systemone: LiquidAI d1's decisions, a distribution read off one position.
*
* d1 is a decision model. It is given a state (text, any JSON value, pictures, or a mix) and named
* questions, and each answer is a softmax over a handful of tokens at the position right after the
* assistant header: `yes` / `no` for a noul, one code a option for a choice, a digit a level for a
* score. Nothing is generated. The API and the prompt are the model's own (its prompt.py and api.py
* on the Hub); this file is that adapter, and the engine knows nothing of it beyond
* Request::token_scores -- "read these ids' raw logits at the prompt's last position".
*
* A container serves it only when it says it is d1 (`decision.type` = `d1`, set at convert with
* `--set decision.type=d1`); the HF config does not declare it.
*/
#pragma once
#include "oai.h"
#include <memory>
#include <string>
#include <vector>
namespace rad {
namespace server {
struct DecisionQuestion {
std::string name, type; /* type: noul | choice | score */
/* One entry an answer, in the response's order: "true"/"false", the option names, the
* levels "0".."n-1". */
std::vector<std::string> labels;
std::vector<std::string> legend; /* score: each level's description */
/* The ids read at the answer slot, and for each answer the indices into them of the
* spellings it scores as: an answer's score is its best spelling's. */
std::vector<int32_t> candidates;
std::vector<std::vector<size_t>> groups;
std::vector<int32_t> tokens; /* the whole prompt */
};
struct DecisionRequest {
std::vector<DecisionQuestion> questions;
/* The pictures, placed in the shared head of every question's prompt. */
std::shared_ptr<mm::PromptMedia> media;
/* How many leading tokens every question's prompt shares: the state, tokenised once. 0 for
* a single question, which d1 tokenises as one text. */
int32_t trunk = 0;
/* What the model reads, as d1 counts it: the shared head once and each question's own tail. */
int64_t input_tokens = 0;
};
/* Parse and render. `max_ctx` bounds every question's prompt (one position stays free for the
* token the request samples and discards). */
int parse_decision_request(const std::string& body, const OaiDeps& d, const OaiLimits& lim,
const std::string& model_id, DecisionRequest* out, ApiError* err);
/* One answer from its candidates' raw logits: each answer scores its best spelling, a softmax over
* the answers is the distribution. Non-finite logits are an error, not a distribution. */
int decision_answer(const DecisionQuestion& q, const std::vector<float>& logits, json* out,
ApiError* err);
} /* namespace server */
} /* namespace rad */