Archived
merge origin/main: the upstream LoRA-runtime refactor beneath the ref2va port
Merges upstream 1.10.0 (152 commits: the LoRA acquire/runtime refactor, the
form-1 LTX-2 scheduler family, guidance terms + negative prompts, decoder
selection, input_reference, new architectures) into the ref2va port branch.
Resolution rule throughout: keep BOTH feature sets; ABI numbering follows
upstream (RAD_ABI_VERSION 26, RAD_FORMAT_VER 2), with the port's video fields
unioned into RadVideoGenBatch/RadVideoGenDecl and abi_layout_table.h
regenerated from the live table.
Notable reconciliations:
* videos.cpp: the task grammars are disjoint by capability -- keyframe tasks
(i2va/l2va/flash-attn l2va/fl2va) are recognized only when decl.encodes,
so upstream models keep refusing them as unknown tasks; input_reference,
the LoRA tag/field pipeline, and the guidance/negative_prompt rendering
coexist with refs/ref2va; the prompt put() helper hoisted to block scope
for the media branch.
* video_schedule(): upstream's (steps, video_tokens, refine) keeps its
positional slots; the port's shift_video/shift_audio overrides move to the
tail so upstream's schedule tests call unchanged.
* r4d_selftest conv3d cases: the port's sp/st/causal/down/refl geometry and
upstream's tpad/tpre fold into one reference (ft = causal ? 2 : tpad==2 ?
2+tpre : 1); rms_mod rows keep the port's i8/fp8 quant modes alongside
upstream's wadd/norm_once/norm parameters.
* tests/oot_plugins.sh: the per-plugin cmake --install gains a --prefix
staging dir -- plugin .so files still land in the absolute
RAD_PLUGIN_INSTALL_HOME, but libr4d now also installs r4d_selftest to a
relative bin/, which needs no root.
Host ctest: 112/113 (mm_test's webp gap pre-exists this merge); r4d_selftest,
engine_e2e, oot_plugins, abi_layout, all LoRA tests green.
Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
commit
a1a75da7e9
415 files changed
+78837
-5310
No files matched your search
@@ -102,6 +102,8 @@ inline SchedMetrics bridge_metrics(const rad::SchedMetrics& m) {
|
||||
o.hit_cut_no_snapshot = m.hit_cut_no_snapshot;
|
||||
o.hit_cut_window = m.hit_cut_window;
|
||||
o.hit_cut_adopt = m.hit_cut_adopt;
|
||||
o.hit_cut_resumed_below = m.hit_cut_resumed_below;
|
||||
o.prefix_restore_cuts = m.prefix_restore_cuts;
|
||||
o.hit_cut_tokens = m.hit_cut_tokens;
|
||||
o.prefix_expired = m.prefix_expired;
|
||||
o.prefix_ckpt_expired = m.prefix_ckpt_expired;
|
||||
@@ -138,6 +140,8 @@ inline SchedMetrics bridge_metrics(const rad::SchedMetrics& m) {
|
||||
o.steps_held = m.steps_held;
|
||||
o.decode_rows_unspeculated = m.decode_rows_unspeculated;
|
||||
o.step_ns = m.step_ns; o.step_ns_decode = m.step_ns_decode;
|
||||
o.step_ns_decode_best = m.step_ns_decode_best;
|
||||
o.step_ns_decode_recent = m.step_ns_decode_recent;
|
||||
return o;
|
||||
}
|
||||
|
||||
|
||||
+458
-22
@@ -30,6 +30,51 @@ namespace server {
|
||||
* Derived rates are the page's job: they are counter differences over wall time, and only the
|
||||
* browser holds both ends of its poll interval. Computing them here would need per-client state. */
|
||||
|
||||
/* ------------------------------------------------------------------ /admin/control-vector
|
||||
*
|
||||
* The control vector's runtime switch (core/cvec.h). Turning it on for the next
|
||||
* request costs a boolean: the direction table was uploaded at startup and the per-request mask
|
||||
* is a derived buffer the core fills every step, so there is nothing to rebuild and nothing to
|
||||
* reload. The engine's own log records the load; this records the flip, because a deployment's
|
||||
* answer to "was that text produced with the vector" should not depend on a browser's memory.
|
||||
*
|
||||
* GET reports the state (and is what the Model view renders); POST takes {"enabled": true|false}
|
||||
* and answers with the same object. A deployment with no vector loaded answers 404 on both: it has
|
||||
* no such feature, and its requests refuse `control_vector: true` by name. */
|
||||
HttpResponse Server::handle_control_vector(const HttpRequest& req) {
|
||||
const bool have = deps_.control_vector.available && deps_.control_vector.available();
|
||||
if (!have) {
|
||||
/* 404, like a model the server does not serve: the route exists, this deployment has nothing
|
||||
* behind it, and that is what the page tests for before hiding the panel. */
|
||||
ApiError e;
|
||||
e.status = 404;
|
||||
e.type = "not_found_error";
|
||||
e.message = "this deployment found no control vector for its model; there is nothing to "
|
||||
"switch";
|
||||
return error_response(e, req.peer);
|
||||
}
|
||||
|
||||
if (req.method == "POST") {
|
||||
json body;
|
||||
try {
|
||||
body = json::parse(req.body.empty() ? "{}" : req.body);
|
||||
} catch (const std::exception& e) {
|
||||
return error_response(err_bad("body", std::string("not JSON: ") + e.what()), req.peer);
|
||||
}
|
||||
const auto it = body.find("enabled");
|
||||
if (it == body.end() || !it->is_boolean())
|
||||
return error_response(err_bad("enabled", "a boolean is required"), req.peer);
|
||||
const bool on = it->get<bool>();
|
||||
if (deps_.control_vector.set_default) deps_.control_vector.set_default(on);
|
||||
RAD_INFO("control vector: default %s by an admin request%s", on ? "ON" : "OFF",
|
||||
req.peer.empty() ? "" : (" from " + req.peer).c_str());
|
||||
}
|
||||
|
||||
metrics_.observe_http(200);
|
||||
return HttpResponse::json_body(
|
||||
200, deps_.control_vector.json ? deps_.control_vector.json() : std::string("{}"));
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ /sessions
|
||||
*
|
||||
* A separate route, not a /stats field: /stats is polled every second, while a stored session
|
||||
@@ -86,6 +131,7 @@ HttpResponse Server::handle_sessions(const HttpRequest&) {
|
||||
o["moved"] = { { "to_host", c.to_host }, { "dropped", c.dropped },
|
||||
{ "promoted", c.promoted }, { "host_drops", c.host_drops },
|
||||
{ "held_back", c.held_back },
|
||||
{ "restore_cuts", sm.prefix_restore_cuts },
|
||||
{ "failures", c.failures } };
|
||||
/* Snapshot store on a hybrid model: bytes per snapshot and slot count. `bytes_each` is 0
|
||||
* on a model with no recurrent state. */
|
||||
@@ -105,7 +151,8 @@ HttpResponse Server::handle_sessions(const HttpRequest&) {
|
||||
{ "refused", sm.prefix_ckpt_refused },
|
||||
{ "hit_cuts", { { "no_snapshot", sm.hit_cut_no_snapshot },
|
||||
{ "windowed_group", sm.hit_cut_window },
|
||||
{ "adopt_failed", sm.hit_cut_adopt } } },
|
||||
{ "adopt_failed", sm.hit_cut_adopt },
|
||||
{ "resumed_below", sm.hit_cut_resumed_below } } },
|
||||
{ "hit_cut_tokens", sm.hit_cut_tokens } };
|
||||
/* Whether a tier exists to move sessions to. A session is recorded whether or not it can be
|
||||
* demoted, so a non-empty table only says something is held. */
|
||||
@@ -124,7 +171,19 @@ HttpResponse Server::handle_stats(const HttpRequest&) {
|
||||
json o;
|
||||
o["model"] = opt_.model_id;
|
||||
o["version"] = opt_.version;
|
||||
/* The control vector (core/cvec.h), when this deployment has one: `available` is what a UI
|
||||
* tests before offering the control, `default` what a request that names no choice runs. The
|
||||
* dashboard's own control asks /admin/control-vector, which also reports this. */
|
||||
if (deps_.control_vector.json) {
|
||||
try {
|
||||
o["control_vector"] = json::parse(deps_.control_vector.json());
|
||||
} catch (const std::exception&) {
|
||||
/* A malformed snapshot is not worth failing /stats over; the field is omitted. */
|
||||
}
|
||||
}
|
||||
o["uptime_s"] = unix_now() - started_at_;
|
||||
/* Seconds this process took to come up, the cost of a restart; 0 before the server listens. */
|
||||
o["startup_s"] = startup_s_;
|
||||
o["in_flight"] = in_flight_.load(std::memory_order_relaxed);
|
||||
o["queue_cap"] = queue_depth_;
|
||||
o["now_ms"] = (int64_t)std::time(nullptr) * 1000;
|
||||
@@ -165,7 +224,8 @@ HttpResponse Server::handle_stats(const HttpRequest&) {
|
||||
o["ckpt_refused"] = m.prefix_ckpt_refused;
|
||||
o["hit_cuts"] = { { "no_snapshot", m.hit_cut_no_snapshot },
|
||||
{ "windowed_group", m.hit_cut_window },
|
||||
{ "adopt_failed", m.hit_cut_adopt } };
|
||||
{ "adopt_failed", m.hit_cut_adopt },
|
||||
{ "resumed_below", m.hit_cut_resumed_below } };
|
||||
o["hit_cut_tokens"] = (double)m.hit_cut_tokens;
|
||||
o["prefill_tps"] = m.prefill_tps;
|
||||
o["decode_tps"] = m.decode_tps;
|
||||
@@ -182,6 +242,8 @@ HttpResponse Server::handle_stats(const HttpRequest&) {
|
||||
* covers idle time (see SchedMetrics::step_ns). */
|
||||
o["step_ns"] = m.step_ns;
|
||||
o["step_ns_decode"] = m.step_ns_decode;
|
||||
o["step_ns_decode_best"] = m.step_ns_decode_best;
|
||||
o["step_ns_decode_recent"] = m.step_ns_decode_recent;
|
||||
o["rows_unspec"] = m.decode_rows_unspeculated;
|
||||
|
||||
/* Conditional rate per position with its reach count: a rate of 0.0 over a reach of 3 is
|
||||
@@ -413,6 +475,13 @@ h1 { margin:0; font-size:13.5px; font-weight:600; letter-spacing:-.005em; }
|
||||
.aside { font-family:var(--mono); font-size:11.5px; color:var(--dim); }
|
||||
.pbody { padding:14px 16px 16px; }
|
||||
|
||||
/* The control vector's switch: a checkbox row with its explanation under it. The two need a gap
|
||||
between them, because the explanation is set at the size every caption on this page uses, and a
|
||||
line that sits flush under the one above it reads as that line's tail, not as a sentence. It is
|
||||
inset a little too, so it does not start on the same edge as the row it belongs to. */
|
||||
.cvrow { display:flex; align-items:center; gap:8px; }
|
||||
#cvnote { margin-top:9px; padding-left:4px; }
|
||||
|
||||
/* ------------------------------------------------ THE FIRST ROW IS FIXED, THE REST FIT THEIR CONTENT
|
||||
A card whose content changes LENGTH moves every card under it while it is being read, and one
|
||||
card here does that every poll: the list of requests gains and loses rows. So the first row --
|
||||
@@ -497,7 +566,20 @@ h1 { margin:0; font-size:13.5px; font-weight:600; letter-spacing:-.005em; }
|
||||
#view-dash.boot > .strip { opacity:.45; }
|
||||
.strip { transition:opacity .18s linear; }
|
||||
.stack { display:grid; gap:14px; }
|
||||
@media (max-width:1000px) { .body { grid-template-columns:minmax(0,1fr); } }
|
||||
@media (max-width:1000px) {
|
||||
.body { grid-template-columns:minmax(0,1fr); }
|
||||
/* On a phone the page is one column you drag with your thumb. A nested scroller that
|
||||
* refuses to chain (overscroll-behavior:contain, set for the desktop wheel so a scroll
|
||||
* over the request table does not move the page behind it) traps the drag here: you
|
||||
* scroll the card, it bottoms out, and the page will not follow, so you reach for the
|
||||
* margins where no scroller lives to get the page moving again. On narrow screens let
|
||||
* the scroll chain to the document; the desktop containment stays.
|
||||
* .body .hold, not .hold: the base .hold rule is defined LATER in this file, so a bare
|
||||
* .hold override here would match and still LOSE the cascade (equal specificity, later
|
||||
* wins) -- judge slice 31 caught exactly that dead-code trap, and the operator's thumb
|
||||
* confirmed it on the request table. .body .hold wins on specificity regardless of order. */
|
||||
.body .panel > .pbody, .body .hold { overscroll-behavior:auto; }
|
||||
}
|
||||
|
||||
/* the request table */
|
||||
table { width:100%; border-collapse:collapse; font-family:var(--mono); font-size:11.5px;
|
||||
@@ -639,7 +721,8 @@ th + th, td + td { padding-left:14px; }
|
||||
it as a dot, because on a server with long-lived agent clients the second group is most of the
|
||||
table and none of it needs reading to understand the first. */
|
||||
#view-sess .cell { height:auto; padding-bottom:12px; }
|
||||
#view-sess .panel + .panel { margin-top:14px; }
|
||||
/* Stacked panels in one view are 14px apart, the same gap the strip's own margin-bottom gives. */
|
||||
#view-sess .panel + .panel, #view-model .panel + .panel { margin-top:14px; }
|
||||
.stbl td, .stbl th { width:1%; }
|
||||
/* The two text columns take the slack and read left to right; the figures stay narrow. */
|
||||
.stbl .l { text-align:left; width:auto; }
|
||||
@@ -1035,7 +1118,7 @@ nav button.on { color:var(--fg); background:var(--track); }
|
||||
<div><div class="n" id="tps_n">–<u>tok</u></div>
|
||||
<span class="cap">per step</span></div>
|
||||
<div><div class="n" id="acc_n">–<u>%</u></div>
|
||||
<span class="cap">accepted</span></div>
|
||||
<span class="cap">conditionally accepted</span></div>
|
||||
</div>
|
||||
<div class="kv" id="spec"></div>
|
||||
</div>
|
||||
@@ -1173,6 +1256,22 @@ nav button.on { color:var(--fg); background:var(--track); }
|
||||
|
||||
<div id="view-model" hidden>
|
||||
<div class="strip" id="gstrip"></div>
|
||||
<!-- The control vector (core/cvec.h): one direction per layer, projected out of the residual
|
||||
stream at run time. Shown only on a deployment that found one; flipping it needs no
|
||||
reload, and every request that names its own choice overrides it. -->
|
||||
<section class="panel" id="cvpanel" hidden>
|
||||
<div class="phead">
|
||||
<span class="cap">Control vector</span>
|
||||
<span class="aside" id="cvsum"></span>
|
||||
</div>
|
||||
<div class="pbody">
|
||||
<label class="cvrow">
|
||||
<input id="cvbox" type="checkbox">
|
||||
<span id="cvlabel">Remove safety behavior</span>
|
||||
</label>
|
||||
<div class="aside" id="cvnote"></div>
|
||||
</div>
|
||||
</section>
|
||||
<section class="panel">
|
||||
<div class="phead">
|
||||
<span class="cap">Kernel libraries</span>
|
||||
@@ -1228,6 +1327,10 @@ $("key").addEventListener("change", (e) => {
|
||||
e.target.hidden = true;
|
||||
identify();
|
||||
poll();
|
||||
/* The Model view's controls are fetched on demand, so a key entered after the tab was opened
|
||||
* has to re-ask: otherwise the control-vector panel stays in its "sign in" state until the
|
||||
* tab is left and re-opened. */
|
||||
loadControlVector();
|
||||
});
|
||||
const HIST = 120; /* 60s of history at the 500ms poll */
|
||||
|
||||
@@ -1354,16 +1457,28 @@ for (const k of METRICS) {
|
||||
}
|
||||
/* The axis follows the WINDOW's own minimum and maximum, not zero. This is a sparkline: what it
|
||||
* is for is the variation, and the number above it already states the level -- scaled from zero
|
||||
* every steady state is a flat line on the floor. No variation draws down the middle. */
|
||||
* every steady state is a flat line on the floor. No variation draws down the middle.
|
||||
*
|
||||
* The ends of the range are the 5th and 95th percentiles, not the extremes: on a min/max axis one
|
||||
* rare spike owns the box and the typical variation is squeezed into a pixel. A spike past the
|
||||
* 95th draws pinned to the top; the number above carries the level and the detail line the
|
||||
* extremes. The stroke is 1.25 units wide, so a one-unit inset keeps it off the edge. */
|
||||
function spark(key, vals) {
|
||||
const s = M[key], w = 200, h = 22;
|
||||
if (vals.length < 3) { s.line.setAttribute("d", ""); return; }
|
||||
const hi = Math.max(...vals), lo = Math.min(...vals), span = hi - lo;
|
||||
const q = (sorted, p) => sorted[Math.min(sorted.length - 1, Math.floor(p * (sorted.length - 1)))];
|
||||
const sorted = [...vals].sort((a, b) => a - b);
|
||||
let lo = q(sorted, 0.05), hi = q(sorted, 0.95);
|
||||
/* A window that is one value apart from rare spikes puts both percentiles on that value; the
|
||||
* extremes then serve, so the spikes still show. */
|
||||
if (!(hi > lo)) { lo = sorted[0]; hi = sorted[sorted.length - 1]; }
|
||||
const span = hi - lo;
|
||||
const dx = w / (vals.length - 1);
|
||||
let d = "";
|
||||
for (let i = 0; i < vals.length; i++) {
|
||||
const t = span > Math.abs(hi) * 1e-3 ? (vals[i] - lo) / span : 0.5;
|
||||
d += (i ? "L" : "M") + (i * dx).toFixed(1) + "," + (h - 2 - (h - 5) * t).toFixed(1);
|
||||
let t = span > Math.abs(hi) * 1e-3 ? (vals[i] - lo) / span : 0.5;
|
||||
if (t < 0) t = 0; else if (t > 1) t = 1;
|
||||
d += (i ? "L" : "M") + (i * dx).toFixed(1) + "," + (h - 1 - (h - 2) * t).toFixed(1);
|
||||
}
|
||||
s.line.setAttribute("d", d);
|
||||
}
|
||||
@@ -1373,6 +1488,147 @@ function setMetric(key, value, text) {
|
||||
spark(key, hist[key]);
|
||||
}
|
||||
|
||||
/* BEST / RECENT / NOW ON THE OTHER FOUR TILES, in the shape the decode step established.
|
||||
*
|
||||
* WHAT THESE ARE NOT: engine figures. The engine publishes a floor and a recent window for the
|
||||
* decode step alone (step_ns_decode_best / _recent); for tok/s, requests in flight and acceptance
|
||||
* it publishes ONE figure per poll and nothing older. So these three figures are page-side, and
|
||||
* they mean:
|
||||
* best / highest - the extreme this page session has seen AT THE CURRENT CONCURRENCY.
|
||||
* Resets on reload, not on restart.
|
||||
* recent - the mean over the last 15 s at that concurrency; 5 s on prefill, whose
|
||||
* events are shorter than the window that would fit them. Shorter
|
||||
* than the sparkline on purpose:
|
||||
* a 60 s mean still read 31 tok/s fifty seconds after the lane went
|
||||
* quiet, which is the lane being remembered rather than measured.
|
||||
* now - the current value as a percentage of that extreme.
|
||||
* "highest" rather than "best" on the two tiles where more is not better: a lane at its highest
|
||||
* request count is busy, not good. The word carries a direction the number alone does not.
|
||||
*
|
||||
* PER-CONCURRENCY BUCKETS, the decode step's structure: a c8 rate read against the
|
||||
* single-stream best reports the batch arriving as a level change -- the mistake that took
|
||||
* the old drift line out. Every figure on the line describes the current concurrency, and
|
||||
* past c1 the line says so ("@c8"). Requests in flight is the exception: its value IS the
|
||||
* concurrency, so bucketing it by concurrency would pin "highest" to the current number
|
||||
* forever -- it keeps one session-wide bucket. While the lane is idle nothing new is
|
||||
* recorded and the line keeps the last active concurrency's figures: frozen, no now clause,
|
||||
* which is what the Decode Step tile does at idle.
|
||||
*
|
||||
* NO ~99 CAP HERE, unlike the decode step. That cap exists because `now` there is a 500 ms poll
|
||||
* mean measured against a 32-step window mean -- different instruments, so a fast stretch can read
|
||||
* faster than the floor without being one. Here the extreme is computed FROM the same series as
|
||||
* `now`, so exceeding it is arithmetically impossible and 100% is exact: you are at your best.
|
||||
*/
|
||||
/* RECENT'S OWN WINDOW, deliberately shorter than the sparkline's. HIST is 60 s and that is right
|
||||
* for a picture -- a sparkline wants the whole minute to show shape. It is wrong for a number:
|
||||
* measured over real traffic (two 5 s bursts inside a quiet minute), a 60 s mean still read 31.7
|
||||
* tok/s fifty seconds after the lane went quiet, and 30 s only brought that to 26.9. Fifteen
|
||||
* seconds decays to zero within a quarter-minute of silence while still tracking the running mean
|
||||
* mid-burst (52.8 against an actual 53.3). Ten and five overshoot -- 79 and 144 against that same
|
||||
* 53 -- which is the current value wearing a different name, and the big number above already is
|
||||
* that. `best`/`highest` stay full-session: an extreme wants every chance to be broken.
|
||||
* Idle polls do not enter an active bucket -- the lane is not at that concurrency while it
|
||||
* sleeps -- but they DO count in requests in flight's window, whose value is meaningful
|
||||
* while nothing runs.
|
||||
*
|
||||
* PREFILL GETS ITS OWN WINDOW (RECENT_PREFILL, 5 s). Measured: small prompts prefill in 1.5-6 s
|
||||
* above 100 tok/s; the operator's compaction reload -- the big one -- runs 7-15 s by his own
|
||||
* count. A 15 s mean cannot report a 7 s event while it is running: it reaches barely half the
|
||||
* peak by the event's end, then spends a quarter-minute averaging it down. Five seconds is
|
||||
* shorter than the shortest event, so `recent` rides the prefill while it happens instead of
|
||||
* diluting it. The engine's own figure is already a windowed rate (its help text: "over the
|
||||
* scheduler's recent window"), so this window sits on top of the engine's smoothing -- it
|
||||
* decides how long the page remembers, not how sharply the engine measures. */
|
||||
const RECENT = 30; /* 15 s at the 500 ms poll WHILE the quantity keeps updating; a quantity
|
||||
that skips polls (acceptance, which only samples when it drafts) spans
|
||||
30 UPDATES, which under sparse drafting is minutes, not 15 s. */
|
||||
const RECENT_PREFILL = 10; /* 5 s: shorter than the shortest prefill event (see above) */
|
||||
const extAt = {}, winAt = {};
|
||||
let lastActiveC = 0;
|
||||
/* `win` false records the extreme only. Acceptance keeps its own pooled ring (accPool) and
|
||||
* reads `highest` from extAt, so a window here would be a second, never-read copy of the
|
||||
* same samples -- dead weight that a reviewer reasonably reads as a second figure. */
|
||||
function noteSample(key, c, value, cap, win) {
|
||||
if (value == null || !finite(value)) return;
|
||||
const e = extAt[key] || (extAt[key] = {});
|
||||
if (!(c in e) || value > e[c]) e[c] = value;
|
||||
if (win === false) return;
|
||||
const w = winAt[key] || (winAt[key] = {});
|
||||
const s = w[c] || (w[c] = []);
|
||||
s.push(value); if (s.length > (cap || RECENT)) s.shift();
|
||||
}
|
||||
function triple(key, c, label, fmt, showNow) {
|
||||
/* RECENT IS A WINDOW MEAN, not a window maximum -- a maximum would sit equal to `best` on
|
||||
* any steady lane, and two figures that always agree read as a broken instrument. */
|
||||
const e = extAt[key];
|
||||
if (!e || !(c in e)) return "";
|
||||
/* A bucket whose extreme is zero still has a story -- requests in flight has seen nothing yet --
|
||||
* so it renders. Only the `now` clause needs a nonzero extreme to divide by. */
|
||||
const s = winAt[key][c];
|
||||
let sum = 0;
|
||||
for (const v of s) sum += v;
|
||||
const recent = sum / s.length;
|
||||
const now = s[s.length - 1];
|
||||
const tag = typeof c === "number" && c > 1 ? "@c" + c : "";
|
||||
let out = label + " " + fmt(e[c]) + " · recent " + fmt(recent);
|
||||
/* THE SAME GUARD THE DECODE STEP USES: no `now` clause while nothing is running. A rate of
|
||||
* zero is the lane being idle, not the lane being slow, and "now 0% of best" reads as a
|
||||
* fault. The "@cN" tag rides the tail, exactly where the decode step puts it. */
|
||||
if (showNow !== false && e[c] > 0) out += " · now " + Math.round(100 * now / e[c]) + "% of " + label + tag;
|
||||
return out;
|
||||
}
|
||||
/* The acceptance tile's detail line: highest stays the full-session extreme of window ratios
|
||||
* (an extreme is an extreme), but recent and now are POOLED ratios of sums (see above). */
|
||||
function acceptTriple(c, showNow) {
|
||||
const e = extAt["accept"];
|
||||
const ring = accPool[c];
|
||||
if (!e || !(c in e) || !ring || !ring.length) return "";
|
||||
let R = 0, A = 0;
|
||||
for (const d of ring) { R += d.dr; A += d.da; }
|
||||
if (R <= 0) return "";
|
||||
const last = ring[ring.length - 1];
|
||||
const tag = typeof c === "number" && c > 1 ? "@c" + c : "";
|
||||
let out = "highest " + pct(e[c], 0) + " \u00b7 recent " + pct(A / R, 0);
|
||||
if (showNow !== false && e[c] > 0 && last.dr > 0)
|
||||
out += " \u00b7 now " + Math.round(100 * (last.da / last.dr) / e[c]) + "% of highest" + tag;
|
||||
return out;
|
||||
}
|
||||
|
||||
/* WINDOWED ACCEPTANCE. The engine's figure is cumulative and exact -- tot_accepted_/tot_drafted_
|
||||
* over the life of the process -- so a best/recent/now line built on it would print the same
|
||||
* number three times and call it a trend. The per-position counters the acceptance chart already
|
||||
* reads are cumulative too, and the DIFFERENCE between two polls is exact acceptance over that
|
||||
* interval, which is the only figure a detail line can move on. Each sample is one poll's delta
|
||||
* (~500 ms, and only when it drafted); `recent` POOLS the last RECENT such deltas AT THAT
|
||||
* CONCURRENCY and `now` is the newest one -- different windows, free to disagree.
|
||||
* The counters go backwards when the engine restarts; that poll resets the window rather than
|
||||
* reporting a negative draft. */
|
||||
const accPool = {}; /* per concurrency: ring of {dr, da} for the pooled tile window */
|
||||
let accPrev = null, accUp = -1;
|
||||
function accWindow(s) {
|
||||
let reach = 0, hit = 0;
|
||||
for (const p of (s.draft_positions || [])) { reach += p.reached || 0; hit += p.accepted || 0; }
|
||||
/* RESTART DETECTION (2026-10-20, Turnstone audit). Counters going BACKWARDS catches a restart
|
||||
* the page was watching. uptime_s going backwards catches the one it missed: a backgrounded
|
||||
* tab whose accPrev froze while a new process drafted past the old process's lifetime total,
|
||||
* where the delta is positive and the first guard never fires. Either clears every pooled
|
||||
* ring -- a pre-restart pair must not pool with a post-restart one -- and yields no delta,
|
||||
* so the headline reads the idle 0 rather than a dead process's ratio. */
|
||||
const up = s.uptime_s;
|
||||
const restart = accPrev !== null && (reach < accPrev.r || hit < accPrev.a ||
|
||||
(typeof up === "number" && up < accUp));
|
||||
if (typeof up === "number") accUp = up;
|
||||
if (accPrev === null || restart) {
|
||||
accPrev = { r: reach, a: hit };
|
||||
if (restart) for (const k in accPool) delete accPool[k];
|
||||
return null;
|
||||
}
|
||||
const dr = reach - accPrev.r, da = hit - accPrev.a;
|
||||
accPrev = { r: reach, a: hit };
|
||||
if (dr <= 0) return null;
|
||||
return { ratio: da / dr, dr: dr, da: da };
|
||||
}
|
||||
|
||||
|
||||
/* ---------------------------------------------------------------- the batch
|
||||
*
|
||||
@@ -1418,7 +1674,14 @@ function kvPanel(host, keys) {
|
||||
return out;
|
||||
}
|
||||
const totals = kvPanel($("totals"), ["Requests", "Steps"]);
|
||||
const spec = kvPanel($("spec"), ["Drafter", "Depth"]);
|
||||
/* "Accepted of drafted" is the LIFETIME MARGINAL ratio -- the engine's figure, unchanged, and
|
||||
* the one this panel used to carry as its headline. A bullet now rather than the big number:
|
||||
* see the note at the accept tile. It divides by every token DRAFTED, so it is not comparable
|
||||
* with the live figure above it, which divides by the positions actually REACHED; the two bases
|
||||
* are worked through in README.md, section "Draft acceptance", and both are derivable from the
|
||||
* log. Each label names its own denominator, which is the whole distinction -- so neither needs
|
||||
* a tooltip, and a tooltip would be invisible on the phone anyway. */
|
||||
const spec = kvPanel($("spec"), ["Drafter", "Depth", "Accepted of drafted"]);
|
||||
|
||||
/* ---------------------------------------------------------------- meters */
|
||||
/* `split` gives the track a second segment for a fill that is two things -- see setSplit. */
|
||||
@@ -1652,7 +1915,17 @@ function renderRequests(list, poolTokens) {
|
||||
|
||||
/* ---------------------------------------------------------------- update */
|
||||
let prev = null, prevAt = 0, bars = [], devs = [], layerBars = [];
|
||||
let lastStepMs = null, lastTps = null;
|
||||
let lastStepMs = null; /* lastTps retired with the per-step freeze (slice 26) */
|
||||
|
||||
/* The single-stream floor and the engine's most recent window, shown as two numbers with no
|
||||
* verdict. The engine records the fastest single-sequence decode window it has measured
|
||||
* (step_ns_decode_best) and its most recent one (step_ns_decode_recent). Their gap is not engine
|
||||
* drift: on a healthy lane the recent window moves 3-11% above a flat floor with whatever else the
|
||||
* lane is doing, so a restart priced against it would not pay back. Until the engine's first
|
||||
* window completes, the fastest single-stream step this tab has seen stands in. */
|
||||
let c1hist = [];
|
||||
const C1CAP = 7200; /* an hour at 2 polls/s of single-stream samples */
|
||||
const bestAt = {}; /* fastest step seen at each concurrency, this process */
|
||||
|
||||
function update(s, dt) {
|
||||
$("ver").textContent = s.version + " · up " + dur(s.uptime_s);
|
||||
@@ -1664,17 +1937,63 @@ function update(s, dt) {
|
||||
* mixed load the answer is the mean of two populations. `step_ns_decode / steps_decode` is
|
||||
* neither -- it is what a decode step cost.
|
||||
*
|
||||
* A window with no decode steps in it holds the last reading rather than blanking, because a
|
||||
* gauge that flickers to a dash every time the engine pauses is a gauge nobody reads. */
|
||||
* A window with no decode steps in it reads 0, not the last reading (operator ruling
|
||||
* 2026-10-20, second pass): every other live figure on this page shows 0 when the lane is idle
|
||||
* -- tps() renders 0 as "0" and the engine publishes 0 rates -- so 0 IS the idle signal here,
|
||||
* and the dash stays reserved for a quantity that has no value at all. A held value was the
|
||||
* original sin (a stale number wearing a current name); a dash was an over-correction that
|
||||
* broke the convention. The floor and the engine's recent window below are the engine's own
|
||||
* figures and stay put. */
|
||||
const dSteps = prev ? s.steps_decode - prev.steps_decode : 0;
|
||||
const stepMs = dSteps > 0 ? (s.step_ns_decode - prev.step_ns_decode) / 1e6 / dSteps : null;
|
||||
if (stepMs != null) lastStepMs = stepMs;
|
||||
const st = stepTime(lastStepMs);
|
||||
const liveStepMs = stepMs === null ? 0 : stepMs; /* no steps in the window -> 0, the idle figure */
|
||||
const st = stepTime(liveStepMs);
|
||||
M.step.u.textContent = st.u;
|
||||
setMetric("step", lastStepMs, st.n);
|
||||
setMetric("step", liveStepMs, st.n);
|
||||
|
||||
/* Single-stream steps only: the floor is a single-sequence window, and a batched step read
|
||||
* against it would report a batch arriving as a slowdown. */
|
||||
if (s.running === 1 && stepMs != null) { c1hist.push(stepMs); if (c1hist.length > C1CAP) c1hist.shift(); }
|
||||
const engBestMs = s.step_ns_decode_best > 0 ? s.step_ns_decode_best / 1e6 : 0;
|
||||
const engRecentMs = s.step_ns_decode_recent > 0 ? s.step_ns_decode_recent / 1e6 : 0;
|
||||
const floorMs = engBestMs > 0 ? engBestMs : (c1hist.length ? Math.min(...c1hist) : 0);
|
||||
let det = "";
|
||||
if (floorMs > 0) {
|
||||
det = "best " + floorMs.toFixed(2) + "ms";
|
||||
if (engRecentMs > 0) det += " · recent " + engRecentMs.toFixed(2) + "ms";
|
||||
}
|
||||
/* The step as a percentage of the fastest at this concurrency (`@cN` above one). `now` is a
|
||||
* ~500 ms poll mean and `best` a 32-step window mean, so a short fast stretch can beat the
|
||||
* floor; the figure is capped at 99 and shown as ~99, "at the best", rather than claiming a
|
||||
* record the window cannot confirm. */
|
||||
/* Gated on this window HAVING decode steps, not on the lane being busy: during a
|
||||
* prefill-only stretch the lane is busy, lastStepMs holds the last DECODE poll, and the
|
||||
* headline correctly reads 0 -- printing "now X% of best" under it would put a stale
|
||||
* value under the word "now", the exact defect the idle-0 ruling exists to kill. */
|
||||
if (stepMs != null && s.running > 0) {
|
||||
const k = s.running;
|
||||
if (!(k in bestAt) || lastStepMs < bestAt[k]) bestAt[k] = lastStepMs;
|
||||
const ref = k === 1 && floorMs > 0 ? floorMs : bestAt[k];
|
||||
const shown = ref > 0 ? Math.min(99, Math.round(100 * ref / lastStepMs)) : 0;
|
||||
if (ref > 0) det += " · now " + (shown === 99 ? "~99" : shown) + "% of best" + (k === 1 ? "" : "@c" + k);
|
||||
}
|
||||
$("m-stepdet").textContent = det;
|
||||
|
||||
setMetric("decode", s.decode_tps, tps(s.decode_tps));
|
||||
setMetric("prefill", s.prefill_tps, tps(s.prefill_tps));
|
||||
setMetric("flight", s.in_flight, String(s.in_flight));
|
||||
const busy = s.running > 0;
|
||||
if (busy) {
|
||||
lastActiveC = s.running;
|
||||
noteSample("decode", s.running, s.decode_tps);
|
||||
noteSample("prefill", s.running, s.prefill_tps, RECENT_PREFILL);
|
||||
}
|
||||
noteSample("flight", "*", s.in_flight);
|
||||
const cNow = busy ? s.running : lastActiveC;
|
||||
$("m-decodedet").textContent = triple("decode", cNow, "best", tps, busy);
|
||||
$("m-prefilldet").textContent = triple("prefill", cNow, "best", tps, busy);
|
||||
$("m-flightdet").textContent = triple("flight", "*", "highest", (v) => String(Math.round(v)), s.in_flight > 0);
|
||||
/* THE MERGED POOL, not the maximum over groups. The max is the right preemption signal and the
|
||||
* wrong headline: the drafter's own window group is sized one block-run per slot and therefore
|
||||
* sits at 100% for the whole life of the server, so a headline reading the max reads 100% on a
|
||||
@@ -1700,9 +2019,45 @@ function update(s, dt) {
|
||||
+ cnt3(s.kv_tokens_used) + " tok"
|
||||
+ (kvGave > 0 ? " · " + hb(kvGave) + " lent to experts" : "")
|
||||
: "";
|
||||
setMetric("accept", 100 * s.draft_accept,
|
||||
s.draft_positions && s.draft_positions.length
|
||||
? pctn(s.draft_accept, 0) : DASH);
|
||||
const aw = accWindow(s);
|
||||
const awR = aw ? aw.ratio : null;
|
||||
if (awR != null) noteSample("accept", s.running > 0 ? s.running : lastActiveC, awR, null, false);
|
||||
/* POOLED ACCEPTANCE WINDOW (2026-10-20, math audit before the production roll).
|
||||
* triple()'s `recent` averages the per-poll RATIOS; polls carry unequal draft counts, so a
|
||||
* quiet poll and a 500-draft poll would weigh the same -- a mean of ratios, not a ratio of
|
||||
* sums. Measured on a live c8 burst: avg-of-ratios 65.7% vs pooled 54.7%, a 11-point skew
|
||||
* that grows with burstiness. The honest window figure is sum(accepted)/sum(reached) over
|
||||
* the same span, so the tile keeps its own ring of delta pairs per concurrency. */
|
||||
if (aw != null && aw.dr > 0) {
|
||||
const c = s.running > 0 ? s.running : lastActiveC;
|
||||
const ring = accPool[c] || (accPool[c] = []);
|
||||
ring.push(aw); if (ring.length > RECENT) ring.shift();
|
||||
}
|
||||
/* THE HEADLINE IS THE LIVE WINDOW, not the cumulative ratio. The engine's figure is exact but
|
||||
* cumulative, so on a process that has been up for hours it cannot move: 559 fresh drafts moved
|
||||
* it one point against a 33,000-draft denominator, and it froze outright the moment the lane
|
||||
* went quiet. Every other tile's big number is the current value, and feeding the cumulative one
|
||||
* here also fed the sparkline a quantity that is flat by construction.
|
||||
* Polls with no new drafts read 0 (operator ruling 2026-10-20, second pass): the page's
|
||||
* convention is that a live figure shows 0 when the lane is doing nothing, and the dash is for
|
||||
* quantities with no value at all. The original freeze was the real defect -- a held value
|
||||
* reads as a live measurement of a lane that drafted nothing. The lifetime ratio stays on
|
||||
* /stats and /metrics; what the tile answers is "what is it accepting now", and now, idle,
|
||||
* it is accepting nothing.
|
||||
* THE SPARKLINE'S SCALE IS THE SAME as the other tiles -- 120 samples at the 500 ms poll, 60 s
|
||||
* -- because setMetric samples every poll, idle polls included (0 is a value; see above). The
|
||||
* one difference is the dash case: with no draft head there is no value to push, so those polls
|
||||
* leave a gap and the line stretches over more wall-clock than 60 s. (Judge slice 4C: this
|
||||
* comment claimed a 10 s window, then a drafting-only window; neither sampling scheme exists.) */
|
||||
if (!(s.draft_positions && s.draft_positions.length)) setMetric("accept", null, DASH);
|
||||
else if (awR != null) setMetric("accept", 100 * awR, pctn(awR, 0));
|
||||
else setMetric("accept", 0, pctn(0, 0)); /* drafted nothing this poll -> 0, the idle figure */
|
||||
/* `now` is shown only when THIS poll drafted. The guard inside acceptTriple (last.dr > 0)
|
||||
* cannot ever be false -- the ring only stores deltas with dr > 0 -- so the freshness test
|
||||
* belongs here, where the poll's own delta is known. Otherwise a busy lane that drafted
|
||||
* nothing this poll shows 0 in the headline and "now Z% of highest" one line below it,
|
||||
* computed from the last drafted delta. highest/recent are session statistics and stay. */
|
||||
$("m-acceptdet").textContent = acceptTriple(cNow, busy && awR != null);
|
||||
M.flight.u.textContent = "/ " + s.queue_cap;
|
||||
|
||||
const list = s.requests || [];
|
||||
@@ -1786,12 +2141,35 @@ function update(s, dt) {
|
||||
* gives tokens a step for the whole batch -- which grows with concurrency and says nothing
|
||||
* about the drafter. What speculation buys is tokens a step for ONE sequence. */
|
||||
const perStep = sps > 0 && s.decode_tps > 0 ? s.decode_tps / sps / seqs : null;
|
||||
if (perStep != null) lastTps = perStep;
|
||||
$("tps_n").firstChild.nodeValue = lastTps == null ? DASH : sig3(lastTps);
|
||||
$("acc_n").firstChild.nodeValue = pctn(s.draft_accept, 0);
|
||||
/* Reads 0 when this window took no decode steps -- the page's idle figure, same law as
|
||||
* the step tile above it, which this figure is derived from. It used to hold the last
|
||||
* value, so a lane that stopped decoding kept reporting what its steps used to cost.
|
||||
* (Extension of the operator's idle-0 ruling by one figure: same defect, one line down,
|
||||
* flagged by judge slice 26 as "pre-existing, now more visible".) */
|
||||
$("tps_n").firstChild.nodeValue = perStep == null ? "0" : sig3(perStep);
|
||||
/* ACCEPTED IS THE LIVE FIGURE, matching the tile above it. `aw` is the same pooled drafting
|
||||
* window the tile's headline reads, computed earlier in this function -- one derivation, two
|
||||
* readers, so the panel and the tile cannot disagree.
|
||||
* DESIGN DECISION, 10-19, at the Operator's direction: this section shows the REAL-TIME
|
||||
* accepted percentage and the lifetime average sits in the bullets below it. The reasoning is
|
||||
* on the tile; the short form is that a cumulative ratio on a process that has been up for
|
||||
* hours is a number that cannot move, and a headline that cannot move reads as a dead page.
|
||||
* PINNED, NOT PRICED: the Operator may prefer the average back in the big seat, and the swap
|
||||
* is these two lines. What must not happen is the average returning as the headline with no
|
||||
* bullet left behind, because then the live figure is the thing nobody can see.
|
||||
* Nothing drafted this poll reads 0 -- the page's idle figure, same law as the accept tile
|
||||
* (op ruling 2026-10-20, second pass). The defect being fixed is the FREEZE: a held value
|
||||
* reads as a live measurement of a lane that drafted nothing. */
|
||||
if (awR != null) $("acc_n").firstChild.nodeValue = pctn(awR, 0);
|
||||
else $("acc_n").firstChild.nodeValue = pctn(0, 0); /* idle: 0, the page's idle figure */
|
||||
$("specaside").textContent = "depth " + dp.length;
|
||||
spec["Drafter"].textContent = drafterName;
|
||||
spec["Depth"].textContent = dp.length;
|
||||
/* The lifetime marginal, always shown. Judge 22: guarding on >0 conflated "no drafts yet"
|
||||
* with "drafts made, all rejected" -- a drafter that accepts nothing is exactly the case a
|
||||
* reader needs to see, and a dash hid it. 0 is the honest figure for both, and the README's
|
||||
* "Draft acceptance" section says which question this bullet answers. */
|
||||
spec["Accepted of drafted"].textContent = pct(s.draft_accept, 0);
|
||||
}
|
||||
|
||||
/* ---- devices, in the same panel as the cache meter: they are one question. */
|
||||
@@ -2778,7 +3156,7 @@ function show(which) {
|
||||
$("tab-dash").className = (model || sess) ? "" : "on";
|
||||
$("tab-sess").className = sess ? "on" : "";
|
||||
$("tab-model").className = model ? "on" : "";
|
||||
if (model) loadGraph();
|
||||
if (model) { loadGraph(); loadControlVector(); }
|
||||
if (sess) loadSessions();
|
||||
window.scrollTo(0, 0);
|
||||
const h = model ? "#model" : sess ? "#sessions" : "#";
|
||||
@@ -2934,6 +3312,64 @@ async function identify() {
|
||||
} catch (err) { /* the header simply keeps its placeholder */ }
|
||||
}
|
||||
|
||||
/* THE CONTROL VECTOR, asked when the Model view opens. It is not a polled value: it changes only
|
||||
* when this page (or an admin call) flips it, and a control that silently reverted under the
|
||||
* reader would be worse than one that is a second old. A deployment without a control vector
|
||||
* answers 404 and the panel stays hidden. */
|
||||
async function loadControlVector() {
|
||||
/* THREE OUTCOMES, and only one of them hides the panel:
|
||||
* 404 this deployment has no control vector -- there is no such control, so it is omitted;
|
||||
* 200 the vector is loaded -- show the switch and its state;
|
||||
* anything else (most often 401, the page has no API key yet) -- the feature may well be
|
||||
* there, so SAY that instead of hiding the control. A control that silently disappears
|
||||
* because the page has not signed in reads exactly like a build without the feature. */
|
||||
try {
|
||||
const r = await api("admin/control-vector");
|
||||
if (r.status === 404) { $("cvpanel").hidden = true; return; }
|
||||
if (!r.ok) throw new Error(String(r.status));
|
||||
const p = await r.json();
|
||||
$("cvpanel").hidden = false;
|
||||
$("cvbox").disabled = false;
|
||||
$("cvbox").checked = !!p.default;
|
||||
/* The family leads: it is the one term that says whether this file belongs to the model on the
|
||||
* card at all, and it is the loader's own answer, not a label the page invents. */
|
||||
$("cvsum").textContent = (p.arch ? p.arch + " \u00b7 " : "") + "layers " + p.first +
|
||||
"\u2013" + p.last + " \u00b7 " + p.mode + " \u00b7 scale " + p.scale;
|
||||
/* New requests only, because a running request keeps the choice it was admitted with; and a
|
||||
* session whose context already holds a refusal can repeat it, since the refusal is in the
|
||||
* prompt the next turn reads. */
|
||||
$("cvnote").textContent = "New requests only. A session with a refusal already in its " +
|
||||
"context may repeat it.";
|
||||
} catch (e) {
|
||||
$("cvpanel").hidden = false;
|
||||
$("cvbox").disabled = true;
|
||||
$("cvbox").checked = false;
|
||||
$("cvsum").textContent = "";
|
||||
$("cvnote").textContent =
|
||||
"Sign in with the API key (the field in the header) to read or change this: the vector " +
|
||||
"is present on this deployment, but its state needs the key.";
|
||||
}
|
||||
}
|
||||
$("cvbox").addEventListener("change", async (e) => {
|
||||
const want = e.target.checked;
|
||||
e.target.disabled = true;
|
||||
try {
|
||||
const r = await fetch("admin/control-vector", {
|
||||
method: "POST", cache: "no-store",
|
||||
headers: Object.assign({ "Content-Type": "application/json" },
|
||||
apiKey ? { Authorization: "Bearer " + apiKey } : {}),
|
||||
body: JSON.stringify({ enabled: want }),
|
||||
});
|
||||
if (!r.ok) throw new Error(String(r.status));
|
||||
const p = await r.json();
|
||||
$("cvbox").checked = !!p.default;
|
||||
} catch (err) {
|
||||
e.target.checked = !want; // the server kept the old value
|
||||
} finally {
|
||||
e.target.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
async function poll() {
|
||||
/* A background tab watches nothing, and neither does the Model view -- which is static. */
|
||||
if (document.hidden || $("view-dash").hidden) return;
|
||||
|
||||
@@ -72,7 +72,10 @@ struct SchedMetrics {
|
||||
/* Admissions whose prefix hit was cut to nothing, by reason, and the checkpoint shortfall:
|
||||
* attention-cached prompt tokens computed again (rad::SchedMetrics::hit_cut_tokens). */
|
||||
int64_t hit_cut_no_snapshot = 0, hit_cut_window = 0, hit_cut_adopt = 0;
|
||||
int64_t hit_cut_resumed_below = 0; /* resumed more than an interval below the hit */
|
||||
int64_t hit_cut_tokens = 0;
|
||||
/* Host-tier restores the pool could not hold whole (rad::SchedMetrics::prefix_restore_cuts). */
|
||||
int64_t prefix_restore_cuts = 0;
|
||||
/* Removed by --prefix-cache-ttl, cumulative. Not evictions: nothing wanted the memory. */
|
||||
int64_t prefix_expired = 0, prefix_ckpt_expired = 0;
|
||||
/* Decoupled prefix caching (spec §7.3). `prefix_hit_rate` is the attention hit rate, as in
|
||||
@@ -127,6 +130,9 @@ struct SchedMetrics {
|
||||
* a decode step regardless of load. */
|
||||
int64_t step_ns = 0;
|
||||
int64_t step_ns_decode = 0;
|
||||
/* The single-sequence decode floor and most recent window (rad::SchedMetrics). */
|
||||
int64_t step_ns_decode_best = 0;
|
||||
int64_t step_ns_decode_recent = 0;
|
||||
};
|
||||
|
||||
|
||||
@@ -625,7 +631,35 @@ struct ImageGenInfo {
|
||||
/* The model samples on a schedule of its own and takes no step count (a distilled model). */
|
||||
bool fixed_schedule = false;
|
||||
int64_t fixed_steps = 0;
|
||||
/* Guidance in the model card's terms: with `cfg_original` the scale s means cond + s (cond -
|
||||
* uncond), off at 0, and the core runs s + 1; otherwise uncond + s (cond - uncond), off at 1. */
|
||||
double default_cfg = 1.0;
|
||||
bool cfg_original = false;
|
||||
/* The negative prompt a guided request gets when it names none; without one it must. */
|
||||
bool has_default_negative = false;
|
||||
std::string default_negative;
|
||||
/* The pictures are not read by the conditioning network: they go to the generator's own
|
||||
* encoder only (RAD_GEN_LAYOUT_JOINT_STEP). */
|
||||
bool refs_encoder_only = false;
|
||||
/* A reference picture is shrunk to `ref_area` only when larger, then centre-cropped to the
|
||||
* size multiple; otherwise resized to `ref_area` at its aspect. */
|
||||
bool ref_shrink_only = false;
|
||||
/* A prompt of fewer tokens after the drop prefix is padded with `pad_token` up to this many
|
||||
* (RadGeneratorDecl::min_tokens); 0: no minimum. */
|
||||
int64_t min_tokens = 0;
|
||||
int32_t pad_token = 0;
|
||||
/* The prompt is also read through the model's second tokenizer (IImageGen::encode_aux), at
|
||||
* most `aux_max_tokens` ids of it. */
|
||||
bool aux_tokens = false;
|
||||
int64_t aux_max_tokens = 0;
|
||||
/* A discrete-time model (RadGeneratorDecl::train_steps): the samplers it serves (1 << id)
|
||||
* and the sampler and scheduler a request gets when it names none. 0 samplers: flow
|
||||
* matching, which takes neither field. */
|
||||
uint32_t samplers = 0;
|
||||
int32_t default_sampler = 0, default_scheduler = 0;
|
||||
/* The prompt in windows (RadGeneratorDecl::chunk_tokens): tokens a window, its markers and
|
||||
* its padding token; 0 for a prompt read whole. */
|
||||
int32_t chunk_tokens = 0, chunk_bos = 0, chunk_eos = 0, chunk_pad = 0;
|
||||
};
|
||||
|
||||
class IImageGen {
|
||||
@@ -639,6 +673,13 @@ public:
|
||||
virtual int picture(const mm::Frame& f, std::shared_ptr<mm::Item>* out, std::string* why) = 0;
|
||||
virtual int64_t queued() const = 0;
|
||||
virtual int64_t running() const = 0;
|
||||
/* The user's prompt through the model's second tokenizer (ImageGenInfo::aux_tokens), with the
|
||||
* special tokens that tokenizer adds; RAD_E_UNSUPPORTED for a model without one. */
|
||||
virtual int encode_aux(const std::string& text, std::vector<int32_t>* out) const {
|
||||
(void)text;
|
||||
(void)out;
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
};
|
||||
|
||||
/* The audio generator (core/gen/audio_driver.h), for a model that makes music or other audio from
|
||||
@@ -702,6 +743,22 @@ struct VideoGenInfo {
|
||||
* encoders — a text-only or TE-only model leaves them and the server never prepares pixels. */
|
||||
int64_t encodes = 0, max_enc_frames = 0, max_enc_side = 0, max_enc_samples = 0;
|
||||
int64_t enc_ratio = 0;
|
||||
/* `steps` counts model evaluations rather than sigma grid points (RadVideoGenDecl form 1). */
|
||||
bool step_evals = false;
|
||||
/* Guidance (RadVideoGenDecl::guidance): the terms a request may name, their defaults and the
|
||||
* negative prompt a guided request gets when it names none. */
|
||||
bool guidance = false;
|
||||
double guidance_default[8] = {};
|
||||
std::string default_negative;
|
||||
/* Image to video: a first frame is taken, after an H.264 round trip at image_crf when > 0. */
|
||||
bool image_cond = false;
|
||||
int32_t image_crf = 0;
|
||||
/* A length head: a request that names no length gets the one the model predicts. */
|
||||
bool length_head = false;
|
||||
/* The decoders a request may name, the default first, and each one's largest frame in pixels
|
||||
* (RadVideoGenDecl::decoders); empty for a model with one. */
|
||||
std::vector<std::string> decoders;
|
||||
std::vector<int64_t> decoder_max_area;
|
||||
};
|
||||
|
||||
class IVideoGen {
|
||||
|
||||
+212
-36
@@ -9,8 +9,10 @@
|
||||
* repainted where the mask is transparent; the rest is restored exactly after decoding.
|
||||
*
|
||||
* Extensions, under vLLM-Omni's names: `seed`, `negative_prompt` with `true_cfg_scale`
|
||||
* (guidance), `num_inference_steps`, and `width` / `height` instead of `size`. A fixed-schedule
|
||||
* (distilled) model accepts only its own step count.
|
||||
* (guidance, in the model card's terms; `guidance_scale` is the same field under diffusers' name),
|
||||
* `num_inference_steps`, and `width` / `height` instead of `size`. A fixed-schedule (distilled)
|
||||
* model accepts only its own step count. A model whose card guides by default does so with its
|
||||
* own negative prompt unless the request names one or turns guidance off.
|
||||
*
|
||||
* Refused: `response_format: url`, since no image is stored to serve later; only b64_json.
|
||||
*
|
||||
@@ -19,6 +21,7 @@
|
||||
* `.completed` event per image.
|
||||
*/
|
||||
#include "server.h"
|
||||
#include "loras.h"
|
||||
#include "oai.h"
|
||||
|
||||
#include "gen/gen.h"
|
||||
@@ -56,11 +59,13 @@ struct ImgReq {
|
||||
bool has_neg = false;
|
||||
double cfg = 1.0;
|
||||
int32_t w = 0, h = 0, n = 1, steps = 0, previews = 0;
|
||||
int32_t sampler = 0, scheduler = 0;
|
||||
bool seed_given = false;
|
||||
uint64_t seed = 0;
|
||||
std::string background = "auto", format = "png", quality = "auto";
|
||||
int32_t compression = -1;
|
||||
bool stream = false;
|
||||
bool rebalance = false;
|
||||
std::vector<mm::FrameRGBA> images;
|
||||
bool has_mask = false;
|
||||
mm::FrameRGBA mask;
|
||||
@@ -77,16 +82,21 @@ json form_value(const std::string& key, const std::string& v) {
|
||||
if (e && *e == 0 && !v.empty()) return json(x);
|
||||
return json(v);
|
||||
}
|
||||
if (key == "true_cfg_scale") {
|
||||
if (key == "true_cfg_scale" || key == "guidance_scale") {
|
||||
char* e = nullptr;
|
||||
const double x = std::strtod(v.c_str(), &e);
|
||||
if (e && *e == 0 && !v.empty()) return json(x);
|
||||
return json(v);
|
||||
}
|
||||
if (key == "stream") {
|
||||
if (key == "stream" || key == "rebalance") {
|
||||
if (v == "true" || v == "1") return json(true);
|
||||
if (v == "false" || v == "0") return json(false);
|
||||
}
|
||||
/* `loras` as JSON text, or one adapter's name. */
|
||||
if ((key == "loras" || key == "lora") && !v.empty() && (v[0] == '[' || v[0] == '{')) {
|
||||
json j = json::parse(v, nullptr, false);
|
||||
if (!j.is_discarded()) return j;
|
||||
}
|
||||
return json(v);
|
||||
}
|
||||
|
||||
@@ -107,18 +117,34 @@ std::string replace_all(std::string s, const std::string& what, const std::strin
|
||||
}
|
||||
|
||||
/* A picture as the generator's encoder reads it: each channel u -> 2 * (u / 255) - 1 in f32, then
|
||||
* bf16 (VaeImageProcessor's preprocess, cast to the VAE's dtype). */
|
||||
gen::Pixels to_pixels(const mm::FrameRGBA& f) {
|
||||
* bf16 (VaeImageProcessor's preprocess, cast to the VAE's dtype). An RGB model reads the colour
|
||||
* channels and not the alpha, as PIL's convert("RGB") drops it. */
|
||||
gen::Pixels to_pixels(const mm::FrameRGBA& f, int ch) {
|
||||
gen::Pixels p;
|
||||
p.w = f.w;
|
||||
p.h = f.h;
|
||||
p.ch = 4;
|
||||
p.bf16.resize(f.rgba.size());
|
||||
for (size_t i = 0; i < f.rgba.size(); ++i)
|
||||
p.bf16[i] = rad_f32_to_bf16(2.0f * ((float)f.rgba[i] / 255.0f) - 1.0f);
|
||||
p.ch = ch;
|
||||
p.bf16.resize((size_t)f.w * f.h * ch);
|
||||
for (size_t px = 0; px < (size_t)f.w * f.h; ++px)
|
||||
for (int c = 0; c < ch; ++c)
|
||||
p.bf16[px * ch + c] =
|
||||
rad_f32_to_bf16(2.0f * ((float)f.rgba[px * 4 + c] / 255.0f) - 1.0f);
|
||||
return p;
|
||||
}
|
||||
|
||||
/* The centred w x h window of a picture (diffusers' resize_mode "crop" after its resize). */
|
||||
mm::FrameRGBA crop_centre(const mm::FrameRGBA& f, int32_t w, int32_t h) {
|
||||
mm::FrameRGBA o;
|
||||
o.w = w;
|
||||
o.h = h;
|
||||
o.rgba.resize((size_t)w * h * 4);
|
||||
const int32_t x0 = (f.w - w) / 2, y0 = (f.h - h) / 2;
|
||||
for (int32_t y = 0; y < h; ++y)
|
||||
std::memcpy(&o.rgba[(size_t)y * w * 4], &f.rgba[((size_t)(y0 + y) * f.w + x0) * 4],
|
||||
(size_t)w * 4);
|
||||
return o;
|
||||
}
|
||||
|
||||
/* The decoded RGBA flattened on white (no alpha), for a jpeg or an opaque background. */
|
||||
std::vector<uint8_t> on_white(const std::vector<uint8_t>& rgba, int32_t w, int32_t h) {
|
||||
mm::FrameRGBA f;
|
||||
@@ -216,7 +242,9 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
|
||||
"prompt", "model", "n", "size", "quality", "background", "output_format",
|
||||
"output_compression", "response_format", "stream", "partial_images", "moderation",
|
||||
"style", "user", "input_fidelity", "seed", "negative_prompt", "true_cfg_scale",
|
||||
"num_inference_steps", "width", "height",
|
||||
"guidance_scale",
|
||||
"num_inference_steps", "width", "height", "loras", "lora", "sampler", "scheduler",
|
||||
"rebalance",
|
||||
};
|
||||
for (auto it = body.begin(); it != body.end(); ++it) {
|
||||
bool known = false;
|
||||
@@ -243,7 +271,20 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
|
||||
return error_response(err_bad("prompt", "expected a string"), req.peer);
|
||||
if (!body.contains("prompt"))
|
||||
return error_response(err_bad("prompt", "the prompt is required"), req.peer);
|
||||
if (r.prompt.empty()) r.prompt = " ";
|
||||
/* Runtime LoRA adapters: `loras` and <lora:...> tags, which leave the prompt. */
|
||||
std::vector<std::pair<std::string, double>> loras;
|
||||
{
|
||||
std::string field, why;
|
||||
if (parse_loras(body, &r.prompt, &loras, &field, &why) < 0)
|
||||
return error_response(err_bad(field.c_str(), why), req.peer);
|
||||
if (!loras.empty() && !opt_.gen_lora_acquire)
|
||||
return error_response(err_unsupported(field.c_str(), "this server was started without "
|
||||
"adapters (--lora, --lora-dir)"),
|
||||
req.peer);
|
||||
}
|
||||
/* An empty prompt becomes " ", as in the diffusers pipelines, unless the model pads a short
|
||||
* prompt itself (ImageGenInfo::min_tokens), as ComfyUI's tokenizers do. */
|
||||
if (r.prompt.empty() && info.min_tokens == 0) r.prompt = " ";
|
||||
std::string rf;
|
||||
if (str("response_format", &rf) < 0 || (!rf.empty() && rf != "b64_json" && rf != "url"))
|
||||
return error_response(err_bad("response_format", "expected b64_json"), req.peer);
|
||||
@@ -274,6 +315,8 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
|
||||
if (r.background == "transparent" && r.format == "jpeg")
|
||||
return error_response(err_bad("background", "jpeg has no transparency; ask for png or "
|
||||
"webp"), req.peer);
|
||||
if (r.background == "transparent" && info.pixel_channels < 4)
|
||||
return error_response(err_bad("background", "this model makes opaque images"), req.peer);
|
||||
if (num("output_compression", 0, 100, &v) < 0)
|
||||
return error_response(err_bad("output_compression", "expected an integer in 0..100"),
|
||||
req.peer);
|
||||
@@ -314,6 +357,39 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
|
||||
else if (r.quality == "medium") steps = std::max<int64_t>(1, info.default_steps * 3 / 4);
|
||||
}
|
||||
r.steps = (int32_t)steps;
|
||||
/* A discrete-time model's sampler and scheduler, by ComfyUI's names. */
|
||||
{
|
||||
std::string sname, kname;
|
||||
if (str("sampler", &sname) < 0)
|
||||
return error_response(err_bad("sampler", "expected a string"), req.peer);
|
||||
if (str("scheduler", &kname) < 0)
|
||||
return error_response(err_bad("scheduler", "expected a string"), req.peer);
|
||||
if (!info.samplers && (!sname.empty() || !kname.empty()))
|
||||
return error_response(err_unsupported(sname.empty() ? "scheduler" : "sampler",
|
||||
"this model samples with flow-matching Euler "
|
||||
"on its own schedule"), req.peer);
|
||||
r.sampler = info.default_sampler;
|
||||
r.scheduler = info.default_scheduler;
|
||||
if (!sname.empty()) {
|
||||
r.sampler = gen::sampler_id(sname);
|
||||
if (r.sampler < 0 || !(info.samplers & (1u << r.sampler))) {
|
||||
ApiError e = err_bad("sampler", "'" + sname + "' is not a sampler this model serves");
|
||||
for (int32_t i = 0; i < RAD_GEN_SAMPLER_COUNT; ++i)
|
||||
if (info.samplers & (1u << i)) e.supported.push_back(gen::sampler_name(i));
|
||||
return error_response(e, req.peer);
|
||||
}
|
||||
}
|
||||
if (!kname.empty()) {
|
||||
r.scheduler = gen::scheduler_id(kname);
|
||||
if (r.scheduler < 0) {
|
||||
ApiError e = err_bad("scheduler", "'" + kname + "' is not a scheduler this model "
|
||||
"serves");
|
||||
for (int32_t i = 0; i < RAD_GEN_SCHED_COUNT; ++i)
|
||||
e.supported.push_back(gen::scheduler_name(i));
|
||||
return error_response(e, req.peer);
|
||||
}
|
||||
}
|
||||
}
|
||||
/* -1 asks for a random seed, as llama-server and the chat endpoints read it. */
|
||||
if (body.contains("seed") && !body["seed"].is_null()) {
|
||||
if (!body["seed"].is_number_integer())
|
||||
@@ -321,23 +397,44 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
|
||||
r.seed = (uint64_t)body["seed"].get<int64_t>();
|
||||
r.seed_given = body["seed"].is_number_unsigned() || body["seed"].get<int64_t>() != -1;
|
||||
}
|
||||
/* Krea 2's fixed tap gains (ConditioningKrea2Rebalance's defaults, arch/krea2); other models
|
||||
* ignore it. */
|
||||
if (body.contains("rebalance") && !body["rebalance"].is_null()) {
|
||||
if (!body["rebalance"].is_boolean())
|
||||
return error_response(err_bad("rebalance", "expected true or false"), req.peer);
|
||||
r.rebalance = body["rebalance"].get<bool>();
|
||||
}
|
||||
if (str("negative_prompt", &r.negative) < 0)
|
||||
return error_response(err_bad("negative_prompt", "expected a string"), req.peer);
|
||||
if (body.contains("true_cfg_scale") && !body["true_cfg_scale"].is_null()) {
|
||||
if (!body["true_cfg_scale"].is_number())
|
||||
return error_response(err_bad("true_cfg_scale", "expected a number"), req.peer);
|
||||
r.cfg = body["true_cfg_scale"].get<double>();
|
||||
if (!(r.cfg >= 1.0 && r.cfg <= 30.0))
|
||||
return error_response(err_bad("true_cfg_scale", "expected a number in 1..30"),
|
||||
req.peer);
|
||||
/* The scale in the model card's terms: off at 0 for a card that states it as
|
||||
* cond + s (cond - uncond), at 1 for uncond + s (cond - uncond). */
|
||||
const double cfg_off = info.cfg_original ? 0.0 : 1.0;
|
||||
const char* cfg_key = body.contains("guidance_scale") && !body["guidance_scale"].is_null()
|
||||
? "guidance_scale" : "true_cfg_scale";
|
||||
const bool cfg_given = body.contains(cfg_key) && !body[cfg_key].is_null();
|
||||
if (cfg_given && body.contains("true_cfg_scale") && body.contains("guidance_scale") &&
|
||||
!body["true_cfg_scale"].is_null())
|
||||
return error_response(err_bad("guidance_scale", "true_cfg_scale and guidance_scale are "
|
||||
"the same field; name one"), req.peer);
|
||||
r.cfg = info.default_cfg;
|
||||
if (cfg_given) {
|
||||
if (!body[cfg_key].is_number())
|
||||
return error_response(err_bad(cfg_key, "expected a number"), req.peer);
|
||||
r.cfg = body[cfg_key].get<double>();
|
||||
if (!(r.cfg >= cfg_off && r.cfg <= 30.0))
|
||||
return error_response(err_bad(cfg_key, "expected a number in " +
|
||||
std::string(cfg_off > 0 ? "1" : "0") +
|
||||
"..30"), req.peer);
|
||||
}
|
||||
/* Guidance needs a scale above one and a negative prompt (empty becomes " "), as in the
|
||||
* reference pipeline. */
|
||||
r.has_neg = r.cfg > 1.0 && body.contains("negative_prompt");
|
||||
if (r.has_neg && r.negative.empty()) r.negative = " ";
|
||||
if (r.cfg > 1.0 && !r.has_neg)
|
||||
return error_response(err_bad("true_cfg_scale", "guidance needs a negative_prompt"),
|
||||
req.peer);
|
||||
/* Guidance needs a scale past its off value and a negative prompt: the request's (empty
|
||||
* becomes " " as the prompt does), or the model's own. */
|
||||
const bool guided = r.cfg > cfg_off;
|
||||
const bool named_neg = body.contains("negative_prompt") && !body["negative_prompt"].is_null();
|
||||
r.has_neg = guided && (named_neg || info.has_default_negative);
|
||||
if (r.has_neg && !named_neg) r.negative = info.default_negative;
|
||||
else if (r.has_neg && r.negative.empty() && info.min_tokens == 0) r.negative = " ";
|
||||
if (guided && !r.has_neg)
|
||||
return error_response(err_bad(cfg_key, "guidance needs a negative_prompt"), req.peer);
|
||||
|
||||
/* ---- the pictures */
|
||||
if (edit) {
|
||||
@@ -372,7 +469,7 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
|
||||
* image generated without transparency has only decoder noise in its alpha. */
|
||||
if (r.background == "auto") {
|
||||
bool alpha = false;
|
||||
if (r.format != "jpeg")
|
||||
if (r.format != "jpeg" && info.pixel_channels >= 4)
|
||||
for (const mm::FrameRGBA& f : r.images)
|
||||
for (size_t i = 3; i < f.rgba.size() && !alpha; i += 4)
|
||||
alpha = f.rgba[i] < kTransparentBelow;
|
||||
@@ -435,19 +532,45 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
|
||||
g->height = r.h;
|
||||
g->n = r.n;
|
||||
g->steps = r.steps;
|
||||
g->sampler = r.sampler;
|
||||
g->scheduler = r.scheduler;
|
||||
g->seed = r.seed;
|
||||
g->previews = r.previews;
|
||||
g->cfg = (float)r.cfg;
|
||||
g->cond_opts = r.rebalance ? RAD_GEN_COND_REBALANCE : 0;
|
||||
/* The driver guides as uncond + cfg (cond - uncond); a card's cond + s (cond - uncond) is
|
||||
* that at s + 1. */
|
||||
g->cfg = (float)(info.cfg_original ? r.cfg + 1.0 : r.cfg);
|
||||
g->has_neg = r.has_neg;
|
||||
g->ticket = std::make_shared<gen::Ticket>();
|
||||
|
||||
std::vector<std::shared_ptr<mm::Item>> items;
|
||||
const int pch = (int)info.pixel_channels;
|
||||
for (const mm::FrameRGBA& f : r.images) {
|
||||
int32_t rw = 0, rh = 0;
|
||||
dims_for((double)info.ref_area, (double)f.w / (double)f.h, mult, &rw, &rh);
|
||||
mm::FrameRGBA rs;
|
||||
mm::resize_lanczos_rgba(f, rw, rh, &rs);
|
||||
g->refs.push_back(to_pixels(rs));
|
||||
if (info.ref_shrink_only) {
|
||||
/* Shrunk to the reference area only when larger, then cut to the size multiple. */
|
||||
const double area = (double)f.w * f.h;
|
||||
if (area > (double)info.ref_area) {
|
||||
const double k = std::sqrt((double)info.ref_area / area);
|
||||
rw = std::max<int32_t>(1, (int32_t)(f.w * k));
|
||||
rh = std::max<int32_t>(1, (int32_t)(f.h * k));
|
||||
mm::resize_lanczos_rgba(f, rw, rh, &rs);
|
||||
} else {
|
||||
rs = f;
|
||||
}
|
||||
const int32_t cw = rs.w / mult * mult, ch = rs.h / mult * mult;
|
||||
if (cw <= 0 || ch <= 0)
|
||||
return error_response(err_bad("image", "a picture must be at least " +
|
||||
std::to_string(mult) + " pixels a side"),
|
||||
req.peer);
|
||||
if (cw != rs.w || ch != rs.h) rs = crop_centre(rs, cw, ch);
|
||||
} else {
|
||||
dims_for((double)info.ref_area, (double)f.w / (double)f.h, mult, &rw, &rh);
|
||||
mm::resize_lanczos_rgba(f, rw, rh, &rs);
|
||||
}
|
||||
g->refs.push_back(to_pixels(rs, pch));
|
||||
if (info.refs_encoder_only) continue;
|
||||
mm::Frame rgb;
|
||||
mm::composite_white(rs, &rgb);
|
||||
std::shared_ptr<mm::Item> it;
|
||||
@@ -465,7 +588,7 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
|
||||
mm::resize_lanczos_rgba(r.images[0], r.w, r.h, &src);
|
||||
mm::resize_lanczos_rgba(r.mask, r.w, r.h, &msk);
|
||||
g->inpaint = true;
|
||||
g->inp_src = to_pixels(src);
|
||||
g->inp_src = to_pixels(src, pch);
|
||||
const int32_t lw = r.w / (int32_t)ls, lh = r.h / (int32_t)ls;
|
||||
g->inp_mask.assign((size_t)lw * lh, 0.0f);
|
||||
keep_px.assign((size_t)r.w * r.h, 0);
|
||||
@@ -527,6 +650,41 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
out->n_drop = (int32_t)drop.size();
|
||||
/* The reference tokenizer's minimum length: an empty prompt is padding the model reads. */
|
||||
while ((int64_t)out->tokens.size() - out->n_drop < info.min_tokens)
|
||||
out->tokens.push_back(info.pad_token);
|
||||
if (info.aux_tokens) {
|
||||
if (deps_.images->encode_aux(prompt, &out->aux) < 0) {
|
||||
*err = err_internal("the prompt could not be read by the model's second "
|
||||
"tokenizer");
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
if ((int64_t)out->aux.size() > info.aux_max_tokens) {
|
||||
*err = err_bad("prompt", "the prompt is " + std::to_string(out->aux.size()) +
|
||||
" tokens to this model's second tokenizer, which "
|
||||
"reads at most " +
|
||||
std::to_string(info.aux_max_tokens));
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
/* A prompt read in windows: runs of at most chunk_tokens after the prefix, each between
|
||||
* its markers and padded to the window. */
|
||||
if (info.chunk_tokens > 0) {
|
||||
const size_t W = (size_t)info.chunk_tokens;
|
||||
std::vector<int32_t> win(out->tokens.begin(), out->tokens.begin() + out->n_drop);
|
||||
const size_t n_body = out->tokens.size() - (size_t)out->n_drop;
|
||||
size_t at = 0;
|
||||
do {
|
||||
const size_t take = std::min(W, n_body - at);
|
||||
win.push_back(info.chunk_bos);
|
||||
win.insert(win.end(), out->tokens.begin() + out->n_drop + (std::ptrdiff_t)at,
|
||||
out->tokens.begin() + out->n_drop + (std::ptrdiff_t)(at + take));
|
||||
win.push_back(info.chunk_eos);
|
||||
win.resize(win.size() + (W - take), info.chunk_pad);
|
||||
at += take;
|
||||
} while (at < n_body);
|
||||
out->tokens = std::move(win);
|
||||
}
|
||||
if ((int64_t)out->tokens.size() > info.max_cond_tokens) {
|
||||
*err = err_bad("prompt", "the prompt is " + std::to_string(out->tokens.size()) +
|
||||
" tokens with its pictures; this deployment conditions on "
|
||||
@@ -542,6 +700,19 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
|
||||
return error_response(err, req.peer);
|
||||
}
|
||||
|
||||
/* ---- the adapters' slot, held until the request is done */
|
||||
std::string lora_note;
|
||||
if (!loras.empty()) {
|
||||
std::string why;
|
||||
const int s = opt_.gen_lora_acquire(loras, &g->lora_slot, &g->lora_hold, &lora_note, &why);
|
||||
if (s < 0) {
|
||||
ApiError e = err_bad("loras", why);
|
||||
if (s == RAD_E_NOTFOUND) { e.status = 404; e.type = "not_found_error"; }
|
||||
else if (s != RAD_E_INVAL) { e.status = 503; e.type = "server_error"; }
|
||||
return error_response(e, req.peer);
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- admitted and queued */
|
||||
if (auto no = admit(1, req.peer)) return *no;
|
||||
std::shared_ptr<gen::Ticket> ticket = g->ticket;
|
||||
@@ -555,9 +726,11 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
|
||||
return error_response(e, req.peer);
|
||||
}
|
||||
}
|
||||
RAD_INFO("images: %s %dx%d n=%d steps=%d seed=%llu%s%s%s", edit ? "edit" : "generation", r.w,
|
||||
std::string lora_s;
|
||||
for (const auto& [n, w] : loras) lora_s += (lora_s.empty() ? " loras=" : ",") + n + fmt(":%g", w);
|
||||
RAD_INFO("images: %s %dx%d n=%d steps=%d seed=%llu%s%s%s%s", edit ? "edit" : "generation", r.w,
|
||||
r.h, r.n, r.steps, (unsigned long long)r.seed, r.has_neg ? " guided" : "",
|
||||
r.has_mask ? " masked" : "", r.stream ? " streamed" : "");
|
||||
r.has_mask ? " masked" : "", r.stream ? " streamed" : "", lora_s.c_str());
|
||||
|
||||
/* ---- one finished picture to a file */
|
||||
const std::string size_s = std::to_string(r.w) + "x" + std::to_string(r.h);
|
||||
@@ -567,12 +740,15 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
|
||||
auto encode = [fmt, comp, keep_px, src_px, flatten](gen::Image& im, std::string* b64,
|
||||
std::string* why) -> int {
|
||||
std::vector<uint8_t>& px = im.px;
|
||||
const size_t ch = (size_t)im.ch;
|
||||
if (!keep_px.empty() && !im.preview)
|
||||
for (size_t i = 0; i < keep_px.size(); ++i)
|
||||
if (keep_px[i]) std::memcpy(&px[i * 4], &src_px[i * 4], 4);
|
||||
if (keep_px[i]) std::memcpy(&px[i * ch], &src_px[i * 4], ch);
|
||||
std::vector<uint8_t> file;
|
||||
int s;
|
||||
if (flatten) {
|
||||
if (ch == 3) {
|
||||
s = mm::encode_image(px.data(), im.w, im.h, 3, fmt, comp, &file, why);
|
||||
} else if (flatten) {
|
||||
const std::vector<uint8_t> rgb = on_white(px, im.w, im.h);
|
||||
s = mm::encode_image(rgb.data(), im.w, im.h, 3, fmt, comp, &file, why);
|
||||
} else {
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
/* loras.cpp -- see loras.h. */
|
||||
#include "loras.h"
|
||||
#include "rad_internal.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdlib>
|
||||
|
||||
namespace rad {
|
||||
namespace server {
|
||||
|
||||
namespace {
|
||||
|
||||
/* "name" or "name:strength" (the last ':' splits, so a name may hold one). */
|
||||
bool split_entry(const std::string& s, std::string* name, double* w) {
|
||||
*w = 1.0;
|
||||
const size_t c = s.rfind(':');
|
||||
if (c != std::string::npos && c + 1 < s.size()) {
|
||||
char* end = nullptr;
|
||||
const double v = std::strtod(s.c_str() + c + 1, &end);
|
||||
if (end && *end == '\0' && std::isfinite(v)) {
|
||||
*name = s.substr(0, c);
|
||||
*w = v;
|
||||
return !name->empty();
|
||||
}
|
||||
}
|
||||
*name = s;
|
||||
return !name->empty();
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
int parse_loras(const nlohmann::json& body, std::string* prompt,
|
||||
std::vector<std::pair<std::string, double>>* out, std::string* field,
|
||||
std::string* why) {
|
||||
out->clear();
|
||||
const char* key = body.contains("loras") ? "loras" : "lora";
|
||||
if (body.contains(key) && !body[key].is_null()) {
|
||||
*field = key;
|
||||
const nlohmann::json& v = body[key];
|
||||
auto entry = [&](const nlohmann::json& e) -> bool {
|
||||
std::string name;
|
||||
double w = 1.0;
|
||||
if (e.is_string()) {
|
||||
if (!split_entry(e.get<std::string>(), &name, &w)) return false;
|
||||
} else if (e.is_object()) {
|
||||
if (!e.contains("name") || !e["name"].is_string()) return false;
|
||||
name = e["name"].get<std::string>();
|
||||
for (const char* k : { "weight", "strength", "scale" })
|
||||
if (e.contains(k) && !e[k].is_null()) {
|
||||
if (!e[k].is_number()) return false;
|
||||
w = e[k].get<double>();
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
if (name.empty() || !std::isfinite(w)) return false;
|
||||
out->push_back({ name, w });
|
||||
return true;
|
||||
};
|
||||
if (v.is_array()) {
|
||||
for (const nlohmann::json& e : v)
|
||||
if (!entry(e)) {
|
||||
*why = "each entry is a name, \"name:strength\" or {\"name\", \"weight\"}";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
} else if (v.is_object() && !v.contains("name")) {
|
||||
for (auto it = v.begin(); it != v.end(); ++it) {
|
||||
if (!it.value().is_number() || !std::isfinite(it.value().get<double>())) {
|
||||
*why = "a {name: strength} object's strengths are numbers";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
out->push_back({ it.key(), it.value().get<double>() });
|
||||
}
|
||||
} else if (!entry(v)) {
|
||||
*why = "expected a list of adapters (names, \"name:strength\" or {\"name\", \"weight\"})";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
/* <lora:name[:strength]> tags in the prompt. */
|
||||
if (prompt) {
|
||||
std::string p;
|
||||
size_t at = 0;
|
||||
for (;;) {
|
||||
const size_t open = prompt->find("<lora:", at);
|
||||
if (open == std::string::npos) { p += prompt->substr(at); break; }
|
||||
const size_t close = prompt->find('>', open);
|
||||
if (close == std::string::npos) { p += prompt->substr(at); break; }
|
||||
std::string name;
|
||||
double w = 1.0;
|
||||
if (!split_entry(prompt->substr(open + 6, close - open - 6), &name, &w)) {
|
||||
*field = "prompt";
|
||||
*why = "a <lora:...> tag names no adapter";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
out->push_back({ name, w });
|
||||
p += prompt->substr(at, open - at);
|
||||
at = close + 1;
|
||||
}
|
||||
if (p.size() != prompt->size()) {
|
||||
/* Tidy the gaps the tags leave: runs of spaces, and commas with nothing between. */
|
||||
std::string t;
|
||||
for (char c : p) {
|
||||
if (c == ' ' && (t.empty() || t.back() == ' ')) continue;
|
||||
t += c;
|
||||
}
|
||||
for (size_t k; (k = t.find(", ,")) != std::string::npos;) t.erase(k, 2);
|
||||
for (size_t k; (k = t.find(",,")) != std::string::npos;) t.erase(k, 1);
|
||||
while (!t.empty() && (t[0] == ' ' || t[0] == ',')) t.erase(0, 1);
|
||||
while (!t.empty() && (t.back() == ' ' || t.back() == ',')) t.pop_back();
|
||||
*prompt = t.empty() ? std::string(" ") : t;
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
} /* namespace server */
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,30 @@
|
||||
/* loras.h -- which runtime LoRA adapters an image or video request asks for, and at what strength.
|
||||
*
|
||||
* Two spellings, merged:
|
||||
*
|
||||
* `loras` in the body: a list whose entries are a name, "name:strength", or an object
|
||||
* {"name": ..., "weight" | "strength" | "scale": ...}; or an object {name: strength}.
|
||||
* `lora` is the same field.
|
||||
*
|
||||
* <lora:name> or <lora:name:strength> in the prompt, as Stable Diffusion web UIs write it: the
|
||||
* tag is taken out of the prompt, the text around it kept.
|
||||
*
|
||||
* A strength not given is 1. */
|
||||
#pragma once
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
namespace server {
|
||||
|
||||
/* RAD_OK with the adapters in `out` (possibly none) and their tags removed from *prompt;
|
||||
* RAD_E_INVAL with `why` for a malformed entry. `field` receives the field the error is about. */
|
||||
int parse_loras(const nlohmann::json& body, std::string* prompt,
|
||||
std::vector<std::pair<std::string, double>>* out, std::string* field,
|
||||
std::string* why);
|
||||
|
||||
} /* namespace server */
|
||||
} /* namespace rad */
|
||||
+36
-3
@@ -140,6 +140,10 @@ void Metrics::sample(const SchedMetrics& m) {
|
||||
g_prefill_tps_.set(m.prefill_tps);
|
||||
g_decode_tps_.set(m.decode_tps);
|
||||
g_draft_accept_.set(m.draft_acceptance);
|
||||
/* Nanoseconds in the scheduler, seconds on the wire: the base unit Prometheus expects, and
|
||||
* what radiance:engine_step_seconds_* already use. */
|
||||
g_step_best_.set((double)m.step_ns_decode_best / 1e9);
|
||||
g_step_recent_.set((double)m.step_ns_decode_recent / 1e9);
|
||||
const int seen = std::max(0, std::min(m.draft_depth_seen, (int)MAX_DRAFT_POS));
|
||||
for (int j = 0; j < seen; ++j) {
|
||||
const int64_t r = m.draft_pos_reached[j];
|
||||
@@ -192,6 +196,8 @@ void Metrics::sample(const SchedMetrics& m) {
|
||||
c_cut_no_snapshot_.advance_to(m.hit_cut_no_snapshot);
|
||||
c_cut_window_.advance_to(m.hit_cut_window);
|
||||
c_cut_adopt_.advance_to(m.hit_cut_adopt);
|
||||
c_cut_resumed_below_.advance_to(m.hit_cut_resumed_below);
|
||||
c_restore_cuts_.advance_to(m.prefix_restore_cuts);
|
||||
c_cut_tokens_.advance_to(m.hit_cut_tokens);
|
||||
g_linear_hit_.set(m.linear_hit_rate);
|
||||
}
|
||||
@@ -324,6 +330,26 @@ std::string Metrics::render() const {
|
||||
"Prefill throughput over the scheduler's recent window.", L, g_prefill_tps_.get());
|
||||
w.gauge("radiance:decode_tokens_per_second",
|
||||
"Decode throughput over the scheduler's recent window.", L, g_decode_tps_.get());
|
||||
/* THE DECODE FLOOR, the two figures the dashboard's Decode Step tile shows. They were on
|
||||
* /stats only, and /stats is documented as not a stable API -- so the one figure worth
|
||||
* comparing across restarts was reachable only from the surface automation is told not to
|
||||
* use. Omitted until measured: a floor of 0 seconds is not an unmeasured floor, it is an
|
||||
* infinitely fast one, and a scrape would plot it as a record. Both reset on restart, so a
|
||||
* freshly started server simply has no floor to report yet. */
|
||||
if (g_step_best_.get() > 0)
|
||||
w.gauge("radiance:decode_step_seconds_best",
|
||||
"Fastest single-sequence decode step window this process has run, in seconds "
|
||||
"PER STEP. A mean over 32 consecutive single-stream steps, not a stopwatch "
|
||||
"reading. Not seconds per token: with speculation a step can emit several "
|
||||
"tokens, so per-token time is this divided by (1 + accepted per step), "
|
||||
"not by the accepted figure alone. Resets on restart.", L, g_step_best_.get());
|
||||
if (g_step_recent_.get() > 0)
|
||||
w.gauge("radiance:decode_step_seconds_recent",
|
||||
"Most recent single-sequence decode step window, in seconds PER STEP (see "
|
||||
"_best: not a token rate). The gap "
|
||||
"to _best tracks what else the machine is doing, not wear; see docs/GUIDE.md. "
|
||||
"Freezes while the lane is idle, because no window is completing.",
|
||||
L, g_step_recent_.get());
|
||||
w.counter("radiance:engine_steps_total",
|
||||
"Scheduler steps executed. One forward pass of the model, plus whatever draft "
|
||||
"rounds followed it; with speculation a step emits more than one token.",
|
||||
@@ -425,13 +451,20 @@ std::string Metrics::render() const {
|
||||
"Checkpoints not written because every snapshot slot was in use by a restore "
|
||||
"in the same step.", L, c_ckpt_refused_.get());
|
||||
w.help("radiance:prefix_hit_cuts_total",
|
||||
"Admissions whose prefix hit reused nothing, by reason: no snapshot at or below "
|
||||
"the hit, a windowed group no window snapshot covers, or blocks that could not be "
|
||||
"adopted.", "counter");
|
||||
"Admissions whose prefix hit was cut, by reason: reused nothing for want of a "
|
||||
"snapshot at or below the hit, for a windowed group no window snapshot covers, or "
|
||||
"for blocks that could not be adopted; or resumed at a snapshot more than one "
|
||||
"checkpoint interval below the hit.", "counter");
|
||||
labelled("radiance:prefix_hit_cuts_total", "reason", "no_snapshot",
|
||||
c_cut_no_snapshot_.get());
|
||||
labelled("radiance:prefix_hit_cuts_total", "reason", "windowed_group", c_cut_window_.get());
|
||||
labelled("radiance:prefix_hit_cuts_total", "reason", "adopt_failed", c_cut_adopt_.get());
|
||||
labelled("radiance:prefix_hit_cuts_total", "reason", "resumed_below",
|
||||
c_cut_resumed_below_.get());
|
||||
w.counter("radiance:prefix_restore_cuts_total",
|
||||
"Restores from the host tier the pool could not hold whole, even after giving "
|
||||
"up the VRAM copies of other stored conversations; each came back to a "
|
||||
"snapshot short of its end.", L, c_restore_cuts_.get());
|
||||
w.counter("radiance:prefix_hit_cut_tokens_total",
|
||||
"Prompt tokens the attention cache held and admission computed again, because "
|
||||
"the hit resumed at a snapshot below it or reused nothing.", L,
|
||||
|
||||
@@ -113,6 +113,10 @@ private:
|
||||
Gauge g_running_, g_waiting_, g_kv_util_, g_prefix_hit_;
|
||||
Gauge g_kv_max_tokens_, g_kv_max_bytes_;
|
||||
Gauge g_prefill_tps_, g_decode_tps_, g_draft_accept_, g_preempted_;
|
||||
/* The decode floor, in seconds: the fastest single-sequence window this process has run,
|
||||
* and the most recent one. Both stay 0 until a window of 32 single-stream steps completes,
|
||||
* and both reset on restart -- the render omits them rather than expose an unmeasured 0. */
|
||||
Gauge g_step_best_, g_step_recent_;
|
||||
Gauge queue_depth_;
|
||||
/* Per-position conditional draft acceptance (see render() and core/sched/draft.h). */
|
||||
enum { MAX_DRAFT_POS = 64 };
|
||||
@@ -149,7 +153,8 @@ private:
|
||||
Counter c_prefix_evict_, c_prefix_ckpt_evict_;
|
||||
Counter c_prefix_expired_, c_prefix_ckpt_expired_;
|
||||
Counter c_ckpt_retired_, c_ckpt_lru_, c_ckpt_refused_;
|
||||
Counter c_cut_no_snapshot_, c_cut_window_, c_cut_adopt_, c_cut_tokens_;
|
||||
Counter c_cut_no_snapshot_, c_cut_window_, c_cut_adopt_, c_cut_resumed_below_, c_cut_tokens_;
|
||||
Counter c_restore_cuts_;
|
||||
Gauge g_linear_hit_;
|
||||
Counter c_success_[(size_t)SuccessReason::N_];
|
||||
Counter c_rejected_, c_disconnect_, c_overflow_;
|
||||
|
||||
+93
-20
@@ -13,6 +13,7 @@
|
||||
#include <ctime>
|
||||
#include <limits>
|
||||
#include <random>
|
||||
#include <set>
|
||||
#include <type_traits>
|
||||
|
||||
namespace rad {
|
||||
@@ -239,6 +240,7 @@ const char* kAcceptedCommon[] = {
|
||||
"dry_sequence_breakers", "samplers",
|
||||
"grammar", "json_schema", "priority", "logprobs", "ignore_eos",
|
||||
"timings_per_token", "return_progress", "session_id", "n_probs",
|
||||
"control_vector", "experimental_speed_projection",
|
||||
};
|
||||
|
||||
const char* kAcceptedChat[] = {
|
||||
@@ -841,6 +843,21 @@ static int parse_sampling(const json& b, const OaiLimits& lim, OaiRequest* r, Ap
|
||||
/* ignore_eos: generate to max_tokens whatever the model emits. See Request::ignore_eos. */
|
||||
if (!get_bool(b, "ignore_eos", &r->ignore_eos, err)) return RAD_E_INVAL;
|
||||
|
||||
/* The control vector (core/cvec.h): an opt-in per request, and the only place an API client
|
||||
* turns it on when the deployment's default is off. `control_vector` is the field's name;
|
||||
* `experimental_speed_projection` is Strata's spelling of the same switch, kept as an alias so
|
||||
* a client written against that reports what it means -- and read only when the request did not
|
||||
* send the field itself, so the field wins when a body carries both. A JSON null is "not sent",
|
||||
* as everywhere else in this parser. */
|
||||
for (const char* key : { "control_vector", "experimental_speed_projection" }) {
|
||||
const auto it = b.find(key);
|
||||
if (it == b.end() || it->is_null()) continue;
|
||||
bool on = false;
|
||||
if (!get_bool(b, key, &on, err)) return RAD_E_INVAL;
|
||||
r->control_vector = on ? 1 : 0;
|
||||
break;
|
||||
}
|
||||
|
||||
/* stop: a string or an array of strings. Bounded in count and length because every stop
|
||||
* string is searched in each piece of generated text (by the decoder and the server's scan),
|
||||
* so per-token cost is count x longest. OpenAI allows four; the bounds are far above that
|
||||
@@ -3854,9 +3871,17 @@ json message_item(const std::string& id, const std::string& text, const char* st
|
||||
{ "content", text.empty() && std::strcmp(status, "in_progress") == 0
|
||||
? json::array() : json::array({ text_part(text) }) } };
|
||||
}
|
||||
json call_item(const ToolCall& tc, const char* status) {
|
||||
return json{ { "id", fc_id(tc.id) }, { "type", "function_call" }, { "call_id", tc.id },
|
||||
{ "name", tc.name }, { "arguments", tc.arguments }, { "status", status } };
|
||||
/* A call to a flattened namespace tool reports its namespace and its own name apart, as the
|
||||
* Responses API's function_call item does. */
|
||||
json call_item(const OaiRequest& r, const ToolCall& tc, const char* status) {
|
||||
json it = { { "id", fc_id(tc.id) }, { "type", "function_call" }, { "call_id", tc.id },
|
||||
{ "name", tc.name }, { "arguments", tc.arguments }, { "status", status } };
|
||||
auto ns = r.tool_namespace.find(tc.name);
|
||||
if (ns != r.tool_namespace.end()) {
|
||||
it["namespace"] = ns->second.first;
|
||||
it["name"] = ns->second.second;
|
||||
}
|
||||
return it;
|
||||
}
|
||||
|
||||
/* The response object, around its output items, with the request fields it echoes. */
|
||||
@@ -3880,7 +3905,8 @@ json response_object(const OaiRequest& r, const char* status, const json& output
|
||||
} /* namespace */
|
||||
|
||||
int responses_to_chat(const std::string& body, const OaiLimits& lim, std::string* chat,
|
||||
std::string* echo, ApiError* err) {
|
||||
std::string* echo, ApiError* err,
|
||||
std::map<std::string, std::pair<std::string, std::string>>* ns) {
|
||||
json b;
|
||||
RAD_TRY(parse_request_object(body, lim, &b, err));
|
||||
auto prev = b.find("previous_response_id");
|
||||
@@ -3983,11 +4009,14 @@ int responses_to_chat(const std::string& body, const OaiLimits& lim, std::string
|
||||
}
|
||||
msgs.push_back(json{ { "role", role }, { "content", parts } });
|
||||
} else if (type == "function_call") {
|
||||
std::string id, name, args = "{}";
|
||||
std::string id, name, args = "{}", space;
|
||||
if (!member_str(item, "call_id", "input[].call_id", &id, err) ||
|
||||
!member_str(item, "name", "input[].name", &name, err) ||
|
||||
!member_str(item, "arguments", "input[].arguments", &args, err))
|
||||
!member_str(item, "arguments", "input[].arguments", &args, err) ||
|
||||
!member_str(item, "namespace", "input[].namespace", &space, err))
|
||||
return RAD_E_INVAL;
|
||||
/* A namespaced call, under the name its tool was flattened to below. */
|
||||
if (!space.empty()) name = space + "__" + name;
|
||||
json call = { { "id", id }, { "type", "function" },
|
||||
{ "function", { { "name", name }, { "arguments", args } } } };
|
||||
json* prev = last_assistant();
|
||||
@@ -4040,34 +4069,78 @@ int responses_to_chat(const std::string& body, const OaiLimits& lim, std::string
|
||||
}
|
||||
o["messages"] = std::move(msgs);
|
||||
|
||||
/* Function tools only. Built-in tools (web search, file search, computer use) and freeform
|
||||
* custom tools have no chat-completions counterpart and are left out. */
|
||||
/* Function tools, and the function tools a namespace groups (Codex sends every MCP server's
|
||||
* tools that way), flattened to "<namespace>__<name>": the chat path has one flat list, and
|
||||
* the reply's function_call items report the two apart again (OaiRequest::tool_namespace).
|
||||
* Built-in tools (web search, file search, computer use) and freeform custom tools have no
|
||||
* chat-completions counterpart and are left out. */
|
||||
json echo_tools = json::array();
|
||||
auto tit = b.find("tools");
|
||||
if (tit != b.end() && tit->is_array()) {
|
||||
json tools = json::array();
|
||||
std::set<std::string> names;
|
||||
auto add = [&](const json& t, const std::string& space) -> int {
|
||||
std::string name;
|
||||
if (!member_str(t, "name", space.empty() ? "tools[].name" : "tools[].tools[].name",
|
||||
&name, err))
|
||||
return RAD_E_INVAL;
|
||||
const std::string flat = space.empty() ? name : space + "__" + name;
|
||||
if (!names.insert(flat).second) {
|
||||
*err = err_bad("tools", "two tools are named \"" + flat + "\" (a namespace's tools "
|
||||
"are offered to the model as <namespace>__<name>)");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
json fn = { { "name", flat },
|
||||
{ "parameters", t.contains("parameters") ? t.at("parameters") : json::object() } };
|
||||
if (t.contains("description")) fn["description"] = t.at("description");
|
||||
tools.push_back(json{ { "type", "function" }, { "function", fn } });
|
||||
if (!space.empty() && ns) (*ns)[flat] = { space, name };
|
||||
return RAD_OK;
|
||||
};
|
||||
for (const json& t : *tit) {
|
||||
if (str_or(t, "type") != "function") {
|
||||
const std::string type = str_or(t, "type");
|
||||
if (type == "namespace") {
|
||||
std::string space;
|
||||
if (!member_str(t, "name", "tools[].name", &space, err)) return RAD_E_INVAL;
|
||||
if (space.empty()) {
|
||||
*err = err_bad("tools[].name", "a namespace needs a name");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
auto inner = t.find("tools");
|
||||
if (inner == t.end() || !inner->is_array()) {
|
||||
*err = err_bad("tools[].tools", "a namespace holds an array of tools");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
for (const json& f : *inner) {
|
||||
if (str_or(f, "type") != "function") {
|
||||
RAD_DEBUG("responses: tool of type \"%s\" in namespace \"%s\" left out: "
|
||||
"no chat equivalent", str_or(f, "type", "?").c_str(),
|
||||
space.c_str());
|
||||
continue;
|
||||
}
|
||||
RAD_TRY(add(f, space));
|
||||
}
|
||||
echo_tools.push_back(t);
|
||||
continue;
|
||||
}
|
||||
if (type != "function") {
|
||||
RAD_DEBUG("responses: tool of type \"%s\" left out: no chat equivalent",
|
||||
str_or(t, "type", "?").c_str());
|
||||
continue;
|
||||
}
|
||||
std::string name;
|
||||
if (!member_str(t, "name", "tools[].name", &name, err)) return RAD_E_INVAL;
|
||||
json fn = { { "name", name },
|
||||
{ "parameters", t.contains("parameters") ? t.at("parameters") : json::object() } };
|
||||
if (t.contains("description")) fn["description"] = t.at("description");
|
||||
tools.push_back(json{ { "type", "function" }, { "function", fn } });
|
||||
RAD_TRY(add(t, ""));
|
||||
echo_tools.push_back(t);
|
||||
}
|
||||
if (!tools.empty()) o["tools"] = std::move(tools);
|
||||
}
|
||||
auto tc = b.find("tool_choice");
|
||||
if (tc != b.end() && !tc->is_null()) {
|
||||
std::string type = "auto", name;
|
||||
std::string type = "auto", name, space;
|
||||
if (tc->is_object() && (!member_str(*tc, "type", "tool_choice.type", &type, err) ||
|
||||
!member_str(*tc, "name", "tool_choice.name", &name, err)))
|
||||
!member_str(*tc, "name", "tool_choice.name", &name, err) ||
|
||||
!member_str(*tc, "namespace", "tool_choice.namespace", &space, err)))
|
||||
return RAD_E_INVAL;
|
||||
if (!space.empty()) name = space + "__" + name;
|
||||
if (!tc->is_object()) o["tool_choice"] = *tc;
|
||||
else if (type == "function")
|
||||
o["tool_choice"] = json{ { "type", "function" }, { "function", { { "name", name } } } };
|
||||
@@ -4119,7 +4192,7 @@ std::string responses_body(const OaiRequest& r, const ChoiceOut& c, const UsageO
|
||||
out.push_back(reasoning_item(random_id("rs_"), c.msg.reasoning, "completed"));
|
||||
if (!c.msg.content.empty())
|
||||
out.push_back(message_item(random_id("msg_"), c.msg.content, "completed"));
|
||||
for (const ToolCall& tc : c.msg.tool_calls) out.push_back(call_item(tc, "completed"));
|
||||
for (const ToolCall& tc : c.msg.tool_calls) out.push_back(call_item(r, tc, "completed"));
|
||||
const bool cut = c.finish == Finish::Length;
|
||||
return response_object(r, cut ? "incomplete" : "completed", out, &u,
|
||||
cut ? "max_output_tokens" : nullptr).dump();
|
||||
@@ -4175,7 +4248,7 @@ void ResponsesStream::open(std::string& out, Item k, size_t call) {
|
||||
const ToolCall& tc = last_.tool_calls[call];
|
||||
item_id_ = fc_id(tc.id);
|
||||
event(out, "response.output_item.added",
|
||||
json{ { "output_index", at }, { "item", call_item(tc, "in_progress") } });
|
||||
json{ { "output_index", at }, { "item", call_item(*r_, tc, "in_progress") } });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4207,7 +4280,7 @@ void ResponsesStream::close(std::string& out) {
|
||||
const bool cut = finished_ && last_.open_call && call_ + 1 == last_.tool_calls.size();
|
||||
event(out, "response.function_call_arguments.done",
|
||||
json{ { "item_id", item_id_ }, { "output_index", at }, { "arguments", tc.arguments } });
|
||||
item = call_item(tc, cut ? "incomplete" : "completed");
|
||||
item = call_item(*r_, tc, cut ? "incomplete" : "completed");
|
||||
}
|
||||
event(out, "response.output_item.done", json{ { "output_index", at }, { "item", item } });
|
||||
items_.push_back(std::move(item));
|
||||
|
||||
+13
-2
@@ -94,6 +94,11 @@ struct OaiRequest {
|
||||
|
||||
int n = 1;
|
||||
SamplingParams sp;
|
||||
/* The control vector, tri-state: -1 the request named no choice (the deployment's
|
||||
* runtime default applies), 0 it asked for the stock model, 1 for the loaded control vector.
|
||||
* Parsed from `control_vector` (or Strata's `experimental_speed_projection`); a deployment
|
||||
* with no vector refuses 1 rather than silently serving the stock model. */
|
||||
int control_vector = -1;
|
||||
int32_t max_tokens = 0;
|
||||
std::vector<std::string> stop;
|
||||
/* How many of `stop` the client sent; the rest are the chat format's end-of-turn markers.
|
||||
@@ -109,6 +114,10 @@ struct OaiRequest {
|
||||
/* The Responses API request fields its response object echoes (instructions, tools,
|
||||
* tool_choice, text, reasoning, ...), as a JSON object; "" for the other shapes. */
|
||||
std::string echo_json;
|
||||
/* The Responses API's namespaced function tools, flattened for the chat path: the flattened
|
||||
* name ("<namespace>__<name>") to its namespace and name, which a function_call item reports
|
||||
* apart. Empty for the other shapes. */
|
||||
std::map<std::string, std::pair<std::string, std::string>> tool_namespace;
|
||||
/* llama-server's native /completion: the generated token ids beside the text. */
|
||||
bool return_tokens = false;
|
||||
/* The reasoning block's closer when the reply starts inside the block, else "": the stop
|
||||
@@ -499,9 +508,11 @@ std::string anthropic_error_body(const ApiError& e);
|
||||
/* OpenAI's Responses API, translated into the equivalent chat request like Anthropic's. `*echo`
|
||||
* holds the request fields the response object repeats. previous_response_id needs server-side
|
||||
* storage and is refused; non-function tool types have no chat equivalent and are dropped, as
|
||||
* llama-server does. */
|
||||
* llama-server does. A namespace's function tools are flattened to "<namespace>__<name>", and
|
||||
* `*ns` (when given) maps each flattened name back for the reply's function_call items. */
|
||||
int responses_to_chat(const std::string& body, const OaiLimits& lim, std::string* chat,
|
||||
std::string* echo, ApiError* err);
|
||||
std::string* echo, ApiError* err,
|
||||
std::map<std::string, std::pair<std::string, std::string>>* ns = nullptr);
|
||||
std::string responses_body(const OaiRequest& r, const ChoiceOut& c, const UsageOut& u);
|
||||
|
||||
/* Anthropic's stop_reason for a finish and the stop string that caused it. */
|
||||
|
||||
+78
-8
@@ -132,6 +132,7 @@ void Server::register_routes() {
|
||||
return r;
|
||||
});
|
||||
router_.get ("/v1/models", [this](const HttpRequest& q) { return handle_models(q); });
|
||||
router_.get ("/v1/loras", [this](const HttpRequest& q) { return handle_loras(q); });
|
||||
router_.get ("/v1/models/*id", [this](const HttpRequest& q) { return handle_models(q); });
|
||||
router_.post("/v1/load_lora_adapter", [this](const HttpRequest& q) { return handle_lora_admin(q, true); });
|
||||
router_.post("/v1/unload_lora_adapter", [this](const HttpRequest& q) { return handle_lora_admin(q, false); });
|
||||
@@ -170,7 +171,12 @@ void Server::register_routes() {
|
||||
router_.post("/v1/responses", [this](const HttpRequest& q) { return handle_responses(q); });
|
||||
router_.post("/responses", [this](const HttpRequest& q) { return handle_responses(q); });
|
||||
auto responses_tokens = [this](const HttpRequest& q) {
|
||||
return count_tokens(q, responses_to_chat, ApiShape::OpenAI, "response.input_tokens");
|
||||
return count_tokens(q,
|
||||
[](const std::string& b, const OaiLimits& l, std::string* c,
|
||||
std::string* ec, ApiError* e) {
|
||||
return responses_to_chat(b, l, c, ec, e);
|
||||
},
|
||||
ApiShape::OpenAI, "response.input_tokens");
|
||||
};
|
||||
router_.post("/v1/responses/input_tokens", responses_tokens);
|
||||
router_.post("/responses/input_tokens", responses_tokens);
|
||||
@@ -198,6 +204,12 @@ void Server::register_routes() {
|
||||
router_.get ("/stats", [this](const HttpRequest& q) { return handle_stats(q); });
|
||||
router_.get ("/graph", [this](const HttpRequest& q) { return handle_graph(q); });
|
||||
router_.get ("/sessions", [this](const HttpRequest& q) { return handle_sessions(q); });
|
||||
/* The control vector's switch, for the dashboard's Model view and for automation: a
|
||||
* deployment with no vector found answers 404 here. */
|
||||
router_.get ("/admin/control-vector",
|
||||
[this](const HttpRequest& q) { return handle_control_vector(q); });
|
||||
router_.post("/admin/control-vector",
|
||||
[this](const HttpRequest& q) { return handle_control_vector(q); });
|
||||
}
|
||||
|
||||
/* Workers beyond the admission ceiling. A generation holds its connection's worker for its whole
|
||||
@@ -207,6 +219,14 @@ void Server::register_routes() {
|
||||
* number bounds the connections that may wait once the reserve is busy too. */
|
||||
static const int64_t kSpareWorkers = 64;
|
||||
|
||||
void Server::note_ready(uint64_t begin_ns) {
|
||||
if (begin_ns == 0) return;
|
||||
const uint64_t now = rad_mono_ns();
|
||||
/* A stamp that is not in the past leaves the figure unset rather than writing a zero. */
|
||||
if (now <= begin_ns) return;
|
||||
startup_s_ = (int64_t)((now - begin_ns) / 1000000000ull);
|
||||
}
|
||||
|
||||
int Server::run() {
|
||||
TransportOptions t;
|
||||
t.host = opt_.host;
|
||||
@@ -254,20 +274,32 @@ std::vector<std::string> Server::probe_reasoning_efforts() {
|
||||
l.default_reasoning_effort.clear();
|
||||
l.reasoning_effort_map.clear();
|
||||
l.probe = true;
|
||||
auto takes = [&](const std::string& effort) {
|
||||
template_default_effort_.clear();
|
||||
auto render = [&](const std::string& effort, std::string* text) {
|
||||
std::string body = R"({"messages":[{"role":"user","content":"Hello"}],"max_tokens":1)";
|
||||
if (!effort.empty()) body += R"(,"reasoning_effort":)" + json(effort).dump();
|
||||
body += "}";
|
||||
OaiRequest r;
|
||||
ApiError e;
|
||||
return parse_chat_request(body, odeps_, l, &r, &e) >= 0;
|
||||
if (parse_chat_request(body, odeps_, l, &r, &e) < 0) return false;
|
||||
if (text) *text = r.prompts.empty() ? std::string() : r.prompts[0].text;
|
||||
return true;
|
||||
};
|
||||
/* A render that fails without an effort says nothing about efforts; one that takes a
|
||||
* nonsense word takes every word. */
|
||||
if (!takes("") || takes("radiance-probe-not-a-level")) return {};
|
||||
std::vector<std::string> set;
|
||||
for (const char* w : { "low", "medium", "high", "xhigh", "max" })
|
||||
if (takes(w)) set.push_back(w);
|
||||
std::string plain;
|
||||
if (!render("", &plain) || render("radiance-probe-not-a-level", nullptr)) return {};
|
||||
std::vector<std::string> set, same;
|
||||
for (const char* w : { "low", "medium", "high", "xhigh", "max" }) {
|
||||
std::string text;
|
||||
if (!render(w, &text)) continue;
|
||||
set.push_back(w);
|
||||
if (text == plain) same.push_back(w);
|
||||
}
|
||||
/* The level a request naming none gets: the one level whose render is the same. A template may
|
||||
* spend it in a system prompt the client never sees (#113: Qwen3.8's is xhigh). Several, or
|
||||
* none, say nothing. */
|
||||
if (same.size() == 1) template_default_effort_ = same[0];
|
||||
lim_.reasoning_efforts = set;
|
||||
return set;
|
||||
}
|
||||
@@ -434,6 +466,25 @@ int Server::submit_all(const OaiRequest& r, std::vector<Generation>* gens, ApiEr
|
||||
}
|
||||
}
|
||||
|
||||
/* The control vector: the request's own choice, else the deployment's runtime default. A
|
||||
* deployment with no vector refuses the on state by name -- serving the stock model while the
|
||||
* client believes it asked for the vector would be a silent lie about what produced the text.
|
||||
* (Naming: `control_vector` is the field, `experimental_speed_projection` its alias.) */
|
||||
bool projection_on = false;
|
||||
{
|
||||
const bool named = r.control_vector >= 0;
|
||||
projection_on = named
|
||||
? (r.control_vector == 1)
|
||||
: (deps_.control_vector.get_default && deps_.control_vector.get_default());
|
||||
if (projection_on &&
|
||||
!(deps_.control_vector.available && deps_.control_vector.available())) {
|
||||
*err = err_bad("control_vector",
|
||||
"this deployment found no control vector for its model; the stock model "
|
||||
"is what it serves");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
|
||||
int idx = 0;
|
||||
std::vector<Request> rqs;
|
||||
rqs.reserve(r.prompts.size() * (size_t)r.n);
|
||||
@@ -456,6 +507,7 @@ int Server::submit_all(const OaiRequest& r, std::vector<Generation>* gens, ApiEr
|
||||
Request rq;
|
||||
rq.prompt = r.prompts[p].tokens;
|
||||
rq.sp = r.sp;
|
||||
rq.sp.use_control_vector = projection_on;
|
||||
/* Distinct seeds per choice, or `n` identical completions. An offset suffices: the
|
||||
* sampler's stream is seeded, not chained. */
|
||||
rq.sp.seed = r.sp.seed + (uint64_t)k;
|
||||
@@ -1538,10 +1590,12 @@ HttpResponse Server::handle_responses(const HttpRequest& req) {
|
||||
std::string chat, echo;
|
||||
ApiError err;
|
||||
OaiRequest r;
|
||||
if (responses_to_chat(req.body, lim_, &chat, &echo, &err) < 0 ||
|
||||
std::map<std::string, std::pair<std::string, std::string>> ns;
|
||||
if (responses_to_chat(req.body, lim_, &chat, &echo, &err, &ns) < 0 ||
|
||||
parse_chat_request(chat, odeps_, lim_, &r, &err) < 0)
|
||||
return error_response(err, req.peer);
|
||||
r.shape = ApiShape::Responses;
|
||||
r.tool_namespace = std::move(ns);
|
||||
r.id = random_id("resp_");
|
||||
r.echo_json = std::move(echo);
|
||||
return serve(req, r);
|
||||
@@ -1837,6 +1891,22 @@ HttpResponse Server::handle_models(const HttpRequest& req) {
|
||||
/* Runtime LoRA admin, vLLM's routes and bodies: {"lora_name", "lora_path"} to load, {"lora_name"}
|
||||
* to unload. The path is read on this machine, so without --api-key only a loopback client may
|
||||
* ask, the rule /diagnostics follows. */
|
||||
/* A generator's adapter files: what `loras` and <lora:...> tags may name. */
|
||||
HttpResponse Server::handle_loras(const HttpRequest& req) {
|
||||
using json = nlohmann::json;
|
||||
if (!opt_.gen_lora_names) {
|
||||
ApiError e;
|
||||
e.status = 404;
|
||||
e.type = "not_found_error";
|
||||
e.message = "this server takes no adapters in image or video requests (--lora, --lora-dir)";
|
||||
return error_response(e, req.peer);
|
||||
}
|
||||
json data = json::array();
|
||||
for (const std::string& n : opt_.gen_lora_names()) data.push_back({ { "id", n }, { "object", "lora" } });
|
||||
metrics_.observe_http(200);
|
||||
return HttpResponse::json_body(200, json_dump(json{ { "object", "list" }, { "data", std::move(data) } }));
|
||||
}
|
||||
|
||||
HttpResponse Server::handle_lora_admin(const HttpRequest& req, bool load) {
|
||||
using json = nlohmann::json;
|
||||
auto fail = [&](int status, const char* type, const std::string& msg) {
|
||||
|
||||
@@ -48,6 +48,19 @@ struct Deps {
|
||||
* (liveview.h), so the terminal and the web page agree. Absent, the dashboard shows only the
|
||||
* scheduler's metrics and omits the cards. */
|
||||
LiveView::Source live;
|
||||
|
||||
/* The control vector (core/cvec.h), as the server sees it: whether the engine found one for
|
||||
* this container, the runtime default for requests that name no choice, and the switch the
|
||||
* admin endpoint flips. Absent (the function members null) means the feature does not exist on
|
||||
* this deployment: a request that asks for it is refused by name, and the dashboard shows no
|
||||
* control. Nothing here reloads the model. */
|
||||
struct ControlVectorSwitch {
|
||||
std::function<bool()> available;
|
||||
std::function<bool()> get_default;
|
||||
std::function<void(bool)> set_default;
|
||||
std::function<std::string()> json;
|
||||
};
|
||||
ControlVectorSwitch control_vector;
|
||||
};
|
||||
|
||||
struct ServerOptions {
|
||||
@@ -141,6 +154,12 @@ struct ServerOptions {
|
||||
* of an adapter requests still use drains it: RAD_OK with *in_flight > 0 (Engine::lora_unload). */
|
||||
std::function<int(const std::string&, const std::string&, std::string*)> lora_load;
|
||||
std::function<int(const std::string&, std::string*, int*)> lora_unload;
|
||||
/* A generator's adapters (Engine::gen_lora_acquire): the images and videos endpoints' `loras`
|
||||
* and <lora:...> tags get a slot holding that combination, a hold on it and a note on what was
|
||||
* left out; `gen_lora_names` is GET /v1/loras. Unset without adapters. */
|
||||
std::function<int(const std::vector<std::pair<std::string, double>>&, int32_t*,
|
||||
std::shared_ptr<void>*, std::string*, std::string*)> gen_lora_acquire;
|
||||
std::function<std::vector<std::string>()> gen_lora_names;
|
||||
|
||||
std::string api_key;
|
||||
bool cors = true;
|
||||
@@ -181,6 +200,9 @@ public:
|
||||
* also takes a nonsense word it takes any word, and the result is empty. Used to refuse words
|
||||
* outside the set and for /server_info; called once, before run(). */
|
||||
std::vector<std::string> probe_reasoning_efforts();
|
||||
/* The effort the template applies to a request that names none, found by the probe above as
|
||||
* the one whose render is the same; "" when none matches or the probe found no set. */
|
||||
const std::string& template_default_effort() const { return template_default_effort_; }
|
||||
/* Renders each --reasoning-effort-map target as a request's effort. Empty when the template
|
||||
* takes all of them; otherwise the first refusal, naming the target. */
|
||||
std::string check_reasoning_effort_map() const;
|
||||
@@ -191,7 +213,14 @@ public:
|
||||
/* The admission ceiling as resolved: ServerOptions::queue_depth, or 8 x max_seqs for 0. */
|
||||
int64_t queue_cap() const { return queue_depth_; }
|
||||
|
||||
/* Records how long bringup took, called by Engine::serve just before it starts listening
|
||||
* (the same moment the startup watch ends). `begin_ns` is rad_mono_ns from the top of
|
||||
* Engine::start(); 0 leaves the figure unset. run() blocks serving forever, so the value is
|
||||
* handed in rather than taken inside it. */
|
||||
void note_ready(uint64_t begin_ns);
|
||||
|
||||
private:
|
||||
std::string template_default_effort_;
|
||||
struct Generation;
|
||||
struct TranscriptionJob; /* speech.cpp */
|
||||
struct RealtimeSession; /* realtime.cpp */
|
||||
@@ -230,6 +259,7 @@ private:
|
||||
void realtime_run(RealtimeSession& s, WsConn& ws);
|
||||
bool realtime_loop(RealtimeSession& s, WsConn& ws);
|
||||
HttpResponse handle_models(const HttpRequest& req);
|
||||
HttpResponse handle_loras(const HttpRequest& req);
|
||||
HttpResponse handle_metrics(const HttpRequest& req);
|
||||
std::optional<HttpResponse> refuse_text(const std::string& peer,
|
||||
ApiShape shape = ApiShape::OpenAI);
|
||||
@@ -299,6 +329,10 @@ private:
|
||||
HttpResponse handle_stats(const HttpRequest& req);
|
||||
HttpResponse handle_graph(const HttpRequest& req);
|
||||
HttpResponse handle_sessions(const HttpRequest& req);
|
||||
/* The control vector's runtime switch (dashboard.cpp): GET reports the state, POST
|
||||
* {"enabled": bool} sets the default for requests that name no choice. Guarded by the API key
|
||||
* like every other route but the health probes and the page. */
|
||||
HttpResponse handle_control_vector(const HttpRequest& req);
|
||||
|
||||
HttpResponse error_response(const ApiError& e, const std::string& peer,
|
||||
ApiShape shape = ApiShape::OpenAI);
|
||||
@@ -355,6 +389,9 @@ private:
|
||||
std::atomic<int64_t> speech_sessions_{0};
|
||||
std::atomic<bool> stopping_{false};
|
||||
int64_t started_at_ = 0;
|
||||
/* Seconds from the top of Engine::start() to the moment the server began listening; 0 until
|
||||
* note_ready(). */
|
||||
int64_t startup_s_ = 0;
|
||||
|
||||
/* Sinks whose HTTP side is gone but whose engine side may still be mid-step. Held until the
|
||||
* scheduler reports the request terminal, because Request::sink is a raw pointer and freeing
|
||||
|
||||
+266
-51
@@ -16,11 +16,24 @@
|
||||
* (`w:h`) instead lays the model's own canvas over that ratio: the short edge (the model's, or
|
||||
* `short_edge`), the area capped at the model's largest, both sides rounded to the multiple.
|
||||
* A video's length is a whole number of the model's chunks: `seconds` is rounded up to the next.
|
||||
* A model that takes reference media (VideoGenInfo) also serves SGLang's `task` value `ref2va`:
|
||||
* A model that takes reference media (VideoGenInfo) also serves SGLang's `task` value `ref2va`:
|
||||
* the media are form file parts named `ref_image_N` (at most 9), `ref_video_N` (3), a video's
|
||||
* soundtrack as `ref_video_audio_N` and standalone audios as `ref_audio_N` (3), N 1-based and
|
||||
* contiguous within each kind. `input_reference` and non-empty `conditions` are still refused:
|
||||
* the parts carry the bytes, so no JSON array of media is read.
|
||||
* A model with a length head (LTX-2.5's duration head) chooses the length of a request that names
|
||||
* none, or says `"seconds": "auto"`; the video object reports it once chosen. A model with more
|
||||
* than one decoder takes `decoder`, one of their names (LTX-2.5: `vae`, the default, or
|
||||
* `diffusion`).
|
||||
* A model that can start from a picture takes OpenAI's `input_reference`, a file in the form or a
|
||||
* data URL (a string or {image_url}) in JSON, as the video's first frame, prepared as the model's
|
||||
* pipeline prepares it: an H.264 round trip at the model's quality, then a bilinear resize to the
|
||||
* size the first steps run at. Non-empty `conditions` are refused.
|
||||
*
|
||||
* A guided model takes `negative_prompt` and its guidance terms, each the model's default when
|
||||
* absent: `guidance_scale`, `stg_scale`, `modality_scale` and `guidance_rescale` for the video,
|
||||
* the same with `audio_` in front for the soundtrack. A scale of 1 turns that modality's
|
||||
* unconditional branch off; the negative prompt is the model's own unless named.
|
||||
*
|
||||
* A model with a latent upscaler also takes `latent_upscale`, a factor from 1 to its largest: the
|
||||
* first steps run at `size` divided by it and the latent is enlarged to `size` for the last
|
||||
@@ -32,9 +45,11 @@
|
||||
* special tokens and the prompt without, so a caller cannot write control tokens into it.
|
||||
*/
|
||||
#include "server.h"
|
||||
#include "loras.h"
|
||||
#include "oai.h"
|
||||
|
||||
#include "gen/video.h"
|
||||
#include "mm/imaging.h"
|
||||
#include "mm/media.h"
|
||||
#include "mm/video_out.h"
|
||||
#include "rad_internal.h"
|
||||
@@ -80,12 +95,24 @@ struct Server::VideoJob {
|
||||
double upscale = 0.0;
|
||||
int32_t refine = 0;
|
||||
std::string upscale_from;
|
||||
/* A guided model's terms as resolved against its defaults, the negative prompt when a scale
|
||||
* used it, and whether the video started from a picture. */
|
||||
bool guided = false;
|
||||
double guidance[8] = {};
|
||||
std::string negative;
|
||||
bool has_negative = false;
|
||||
bool from_image = false;
|
||||
std::string decoder; /* a decoder the request named other than the default */
|
||||
int32_t w = 0, h = 0;
|
||||
bool worker_done = false; /* its thread has nothing left to do but return */
|
||||
};
|
||||
|
||||
namespace {
|
||||
|
||||
/* The largest picture `input_reference` may decode to, which bounds the memory a request can make
|
||||
* the server allocate before the resize. */
|
||||
constexpr int64_t kMaxRefPixels = (int64_t)1 << 26;
|
||||
|
||||
std::string new_video_id() {
|
||||
static const char* hex = "0123456789abcdef";
|
||||
std::random_device rd;
|
||||
@@ -300,14 +327,15 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
|
||||
* alone they are I2VA (first) or L2VA (last). */
|
||||
std::vector<gen::VideoRefMedia> keys;
|
||||
json body = json::object();
|
||||
std::vector<uint8_t> ref_bytes;
|
||||
bool has_ref = false;
|
||||
if (!req.form.empty()) {
|
||||
for (const FormPart& p : req.form) {
|
||||
if (p.name == "input_reference")
|
||||
return error_response(err_unsupported("input_reference", takes_refs
|
||||
? "this server reads reference media as "
|
||||
"ref_image_N file parts"
|
||||
: "this server makes video from text "
|
||||
"only"), req.peer);
|
||||
if (p.name == "input_reference" && !p.filename.empty()) {
|
||||
ref_bytes.assign(p.data.begin(), p.data.end());
|
||||
has_ref = true;
|
||||
continue;
|
||||
}
|
||||
if (p.name == "first_frame" || p.name == "last_frame") {
|
||||
if (p.filename.empty())
|
||||
return error_response(err_bad(p.name, "'" + p.name + "' must carry an image "
|
||||
@@ -340,7 +368,9 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
|
||||
continue;
|
||||
}
|
||||
json v = p.data;
|
||||
if (p.name == "target" || p.name == "conditions") {
|
||||
if (p.name == "target" || p.name == "conditions" ||
|
||||
((p.name == "loras" || p.name == "lora") && !p.data.empty() &&
|
||||
(p.data[0] == '[' || p.data[0] == '{'))) {
|
||||
v = json::parse(p.data, nullptr, false);
|
||||
if (v.is_discarded())
|
||||
return error_response(err_bad(p.name, "expected JSON"), req.peer);
|
||||
@@ -356,6 +386,10 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
|
||||
"model", "prompt", "seconds", "size", "input_reference", "seed", "num_inference_steps",
|
||||
"task", "target", "conditions", "user", "latent_upscale", "upscale_refine_steps", "format",
|
||||
"sampler", "shift", "audio_shift",
|
||||
"negative_prompt", "decoder", "loras", "lora",
|
||||
/* RadVideoGenBatch::guidance_h's order */
|
||||
"guidance_scale", "stg_scale", "modality_scale", "guidance_rescale",
|
||||
"audio_guidance_scale", "audio_stg_scale", "audio_modality_scale", "audio_guidance_rescale",
|
||||
};
|
||||
for (auto it = body.begin(); it != body.end(); ++it) {
|
||||
bool known = false;
|
||||
@@ -379,35 +413,75 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
|
||||
if (!has(body, "prompt") || !body["prompt"].is_string() ||
|
||||
body["prompt"].get<std::string>().find_first_not_of(" \t\r\n") == std::string::npos)
|
||||
return bad("prompt", "the prompt is required, as a non-empty string");
|
||||
const std::string prompt = body["prompt"].get<std::string>();
|
||||
if (has(body, "input_reference"))
|
||||
std::string prompt = body["prompt"].get<std::string>();
|
||||
/* Runtime LoRA adapters: `loras` and <lora:...> tags, which leave the prompt. */
|
||||
std::vector<std::pair<std::string, double>> loras;
|
||||
{
|
||||
std::string field, why;
|
||||
if (parse_loras(body, &prompt, &loras, &field, &why) < 0) return bad(field.c_str(), why);
|
||||
if (!loras.empty() && !opt_.gen_lora_acquire)
|
||||
return error_response(err_unsupported(field.c_str(), "this server was started without "
|
||||
"adapters (--lora, --lora-dir)"),
|
||||
req.peer);
|
||||
}
|
||||
if (has(body, "input_reference")) {
|
||||
/* JSON: a data URL, as a string or an image_url object. */
|
||||
const json& v = body["input_reference"];
|
||||
std::string u;
|
||||
if (v.is_string()) u = v.get<std::string>();
|
||||
else if (v.is_object() && v.contains("image_url") && v["image_url"].is_string())
|
||||
u = v["image_url"].get<std::string>();
|
||||
else if (v.is_object() && v.contains("image_url") && v["image_url"].is_object() &&
|
||||
v["image_url"].contains("url") && v["image_url"]["url"].is_string())
|
||||
u = v["image_url"]["url"].get<std::string>();
|
||||
else
|
||||
return bad("input_reference", "a picture is a file, a data: URL, or an object with an "
|
||||
"image_url");
|
||||
ApiError err;
|
||||
if (decode_media_url(u, "input_reference", &ref_bytes, &err) < 0)
|
||||
return error_response(err, req.peer);
|
||||
has_ref = true;
|
||||
}
|
||||
if (has_ref && !info.image_cond)
|
||||
return error_response(err_unsupported("input_reference", takes_refs
|
||||
? "this server reads reference media as ref_image_N "
|
||||
"file parts"
|
||||
: "this server makes video from text only"),
|
||||
req.peer);
|
||||
/* The task: text always; reference conditioning for a model that takes reference media. */
|
||||
: "this model makes video from text only"), req.peer);
|
||||
/* With a picture the task is upstream's: t2va names none, i2va names the one. */
|
||||
if (has_ref && has(body, "task") && (!body["task"].is_string() ||
|
||||
body["task"].get<std::string>() != "i2va")) {
|
||||
ApiError e = err_unsupported("task", "a video from a picture is i2va");
|
||||
e.supported = { "i2va" };
|
||||
return error_response(e, req.peer);
|
||||
}
|
||||
/* The task without a picture: text always; reference conditioning for a model that takes
|
||||
* reference media; keyframe completion on a model with a video encoder. */
|
||||
bool ref2va = false;
|
||||
std::string kf_task; /* an explicitly named keyframe task (i2va / l2va / fl2va), if any */
|
||||
if (has(body, "task")) {
|
||||
if (!has_ref && has(body, "task")) {
|
||||
const std::string task = body["task"].is_string() ? body["task"].get<std::string>() : "";
|
||||
if (task == "ref2va" && takes_refs) ref2va = true;
|
||||
/* The keyframe-completion tasks: a first and/or last frame pinned at the output's ends.
|
||||
* They are recognised whatever a model declares (any model with a video encoder can pin a
|
||||
* keyframe); which frames are actually present is decided by the file parts, cross-checked
|
||||
* against this name below. t2va with a first_frame part is I2VA; a named task missing its
|
||||
* frame is refused there. */
|
||||
else if (task == "i2va" || task == "l2va" || task == "fl2va") kf_task = task;
|
||||
/* The keyframe-completion tasks: a first and/or last frame pinned at the output's ends,
|
||||
* which only a model with a video encoder can pin. Which frames are actually present is
|
||||
* decided by the file parts, cross-checked against this name below. t2va with a
|
||||
* first_frame part is I2VA; a named task missing its frame is refused there. */
|
||||
else if (info.encodes && (task == "i2va" || task == "l2va" || task == "fl2va"))
|
||||
kf_task = task;
|
||||
else if (task != "t2va") {
|
||||
ApiError e = err_unsupported("task", takes_refs
|
||||
? "this server makes video from text, from reference "
|
||||
"media, or between keyframes: t2va, ref2va, i2va, l2va, "
|
||||
"fl2va"
|
||||
: "this server makes video from text or between keyframes: "
|
||||
"t2va, i2va, l2va, fl2va");
|
||||
e.supported = takes_refs
|
||||
? std::vector<std::string>{ "t2va", "ref2va", "i2va", "l2va", "fl2va" }
|
||||
: std::vector<std::string>{ "t2va", "i2va", "l2va", "fl2va" };
|
||||
std::string what = "this server makes video from text";
|
||||
std::vector<std::string> sup{ "t2va" };
|
||||
if (info.image_cond) { what += ", from a picture"; sup.push_back("i2va"); }
|
||||
if (info.encodes) {
|
||||
what += ", or between keyframes";
|
||||
for (const char* k : { "i2va", "l2va", "fl2va" })
|
||||
if (std::find(sup.begin(), sup.end(), std::string(k)) == sup.end())
|
||||
sup.push_back(k);
|
||||
}
|
||||
if (takes_refs) { what += ", from reference media"; sup.push_back("ref2va"); }
|
||||
what += ": ";
|
||||
for (size_t i = 0; i < sup.size(); ++i) what += (i ? ", " : "") + sup[i];
|
||||
ApiError e = err_unsupported("task", what);
|
||||
e.supported = sup;
|
||||
return error_response(e, req.peer);
|
||||
}
|
||||
}
|
||||
@@ -533,7 +607,13 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
|
||||
const bool has_sec = has(body, "seconds"), has_dur = has(target, "duration_seconds");
|
||||
if (has_sec && has_dur)
|
||||
return bad("seconds", "give seconds or target's duration_seconds, not both");
|
||||
if (has_sec || has_dur) {
|
||||
/* A model with a length head chooses the length of a request that names none, or `auto`. */
|
||||
const bool auto_len = info.length_head &&
|
||||
(!(has_sec || has_dur) ||
|
||||
(has_sec && body["seconds"].is_string() && body["seconds"].get<std::string>() == "auto"));
|
||||
if (auto_len) {
|
||||
chunks = 0;
|
||||
} else if (has_sec || has_dur) {
|
||||
double sec = 0;
|
||||
if (!number(has_sec ? body["seconds"] : target["duration_seconds"], &sec) || !(sec > 0))
|
||||
return bad(has_sec ? "seconds" : "target", "the length is a positive number of seconds");
|
||||
@@ -546,24 +626,52 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
|
||||
"this model makes " + rad::fmt("%.2f", min_s) + " to " +
|
||||
rad::fmt("%.2f", max_s) + " seconds");
|
||||
}
|
||||
const int64_t frames = info.frames_per_chunk * chunks + info.frames_tail;
|
||||
/* The length the job reports until the model has chosen one. */
|
||||
const int64_t frames =
|
||||
info.frames_per_chunk * (chunks > 0 ? chunks : info.default_chunks) + info.frames_tail;
|
||||
|
||||
std::unique_ptr<gen::VideoRequest> r = std::make_unique<gen::VideoRequest>();
|
||||
r->width = (int32_t)W;
|
||||
r->height = (int32_t)H;
|
||||
r->chunks = (int32_t)chunks;
|
||||
/* ---- the decoder, by name, the model's first when absent */
|
||||
std::string decoder;
|
||||
if (has(body, "decoder")) {
|
||||
if (!body["decoder"].is_string())
|
||||
return bad("decoder", "the decoder is a name");
|
||||
decoder = body["decoder"].get<std::string>();
|
||||
std::string names;
|
||||
int32_t idx = -1;
|
||||
for (size_t i = 0; i < info.decoders.size(); ++i) {
|
||||
names += (i ? ", " : "") + info.decoders[i];
|
||||
if (info.decoders[i] == decoder) idx = (int32_t)i;
|
||||
}
|
||||
if (idx < 0)
|
||||
return bad("decoder", info.decoders.empty()
|
||||
? std::string("this model has one decoder and takes no name")
|
||||
: "this model decodes with " + names);
|
||||
if (W * H > info.decoder_max_area[(size_t)idx])
|
||||
return bad("decoder", "the " + decoder + " decoder makes frames of " +
|
||||
std::to_string(info.decoder_max_area[(size_t)idx]) +
|
||||
" pixels at most");
|
||||
r->decoder = idx;
|
||||
if (idx == 0) decoder.clear();
|
||||
}
|
||||
if (has(body, "num_inference_steps")) {
|
||||
double v = 0;
|
||||
const char* unit = info.step_evals ? " model evaluations"
|
||||
: " sigma grid points, the last one 0";
|
||||
const int64_t lo = info.step_evals ? 1 : 2;
|
||||
if (info.fixed_steps && (!number(body["num_inference_steps"], &v) ||
|
||||
v != (double)info.max_steps))
|
||||
return bad("num_inference_steps",
|
||||
"this model runs the schedule it was trained on: " +
|
||||
std::to_string(info.max_steps) + " sigma grid points, the last one 0");
|
||||
if (!number(body["num_inference_steps"], &v) || v != std::floor(v) || v < 2 ||
|
||||
std::to_string(info.max_steps) + unit);
|
||||
if (!number(body["num_inference_steps"], &v) || v != std::floor(v) || v < lo ||
|
||||
v > (double)info.max_steps)
|
||||
return bad("num_inference_steps", "expected an integer in 2.." +
|
||||
std::to_string(info.max_steps) +
|
||||
" (sigma grid points, the last one 0)");
|
||||
return bad("num_inference_steps", "expected an integer in " + std::to_string(lo) +
|
||||
".." + std::to_string(info.max_steps) + " (" +
|
||||
(unit + 1) + ")");
|
||||
r->steps = (int32_t)v;
|
||||
}
|
||||
if (has(body, "sampler")) {
|
||||
@@ -596,6 +704,33 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
|
||||
rad::fmt("%g", info.shift_audio));
|
||||
r->shift_audio = v;
|
||||
}
|
||||
/* ---- guidance */
|
||||
static const char* kGuide[8] = {
|
||||
"guidance_scale", "stg_scale", "modality_scale", "guidance_rescale",
|
||||
"audio_guidance_scale", "audio_stg_scale", "audio_modality_scale", "audio_guidance_rescale",
|
||||
};
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
if (!has(body, kGuide[i])) continue;
|
||||
if (!info.guidance)
|
||||
return error_response(err_unsupported(kGuide[i], "this model takes no guidance"),
|
||||
req.peer);
|
||||
double v = 0;
|
||||
const bool rescale = i % 4 == 3;
|
||||
if (!number(body[kGuide[i]], &v) || !(v >= 0.0) || v > (rescale ? 1.0 : 100.0))
|
||||
return bad(kGuide[i], rescale ? "expected a number from 0 to 1"
|
||||
: "expected a number from 0 to 100");
|
||||
r->guidance[i] = v;
|
||||
}
|
||||
std::string negative = info.default_negative;
|
||||
if (has(body, "negative_prompt")) {
|
||||
if (!info.guidance)
|
||||
return error_response(err_unsupported("negative_prompt", "this model takes no "
|
||||
"guidance"), req.peer);
|
||||
if (!body["negative_prompt"].is_string())
|
||||
return bad("negative_prompt", "expected a string");
|
||||
negative = body["negative_prompt"].get<std::string>();
|
||||
r->has_neg = true;
|
||||
}
|
||||
if (has(body, "latent_upscale")) {
|
||||
double v = 0;
|
||||
if (!(info.upscale_max > 0.0))
|
||||
@@ -649,10 +784,15 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
|
||||
static const std::string kSlot = "{prompt}";
|
||||
const std::string& t = info.tmpl;
|
||||
const size_t p = t.find(kSlot);
|
||||
auto put = [&](const std::string& s, bool special) {
|
||||
auto put = [&](std::vector<int32_t>* out, const std::string& s, bool special) {
|
||||
if (s.empty()) return;
|
||||
const auto ids = deps_.tok->encode(s, false, special);
|
||||
r->tokens.insert(r->tokens.end(), ids.begin(), ids.end());
|
||||
out->insert(out->end(), ids.begin(), ids.end());
|
||||
};
|
||||
auto render = [&](const std::string& text, std::vector<int32_t>* out) {
|
||||
put(out, t.substr(0, p), true);
|
||||
put(out, text, false);
|
||||
put(out, t.substr(p + kSlot.size()), true);
|
||||
};
|
||||
/* The reference media are presented between the template's head and the prompt. Only the
|
||||
* images reach the language model as soft-token rows, so only they are decoded and placed
|
||||
@@ -700,13 +840,13 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
|
||||
if (m.kind == gen::VideoRefMedia::VIDEO_AUDIO && m.index == idx) return true;
|
||||
return false;
|
||||
};
|
||||
put(t.substr(0, p), true);
|
||||
put(&r->tokens, t.substr(0, p), true);
|
||||
std::shared_ptr<mm::PromptMedia> media;
|
||||
if (!pics.empty()) media = std::make_shared<mm::PromptMedia>();
|
||||
size_t i = 0;
|
||||
for (const gen::VideoRefMedia& m : r->refs) { /* sorted by (kind, index): images first */
|
||||
if (!anchor(m)) continue;
|
||||
put("<Picture " + std::to_string(m.index) + ">: ", false);
|
||||
put(&r->tokens, "<Picture " + std::to_string(m.index) + ">: ", false);
|
||||
mm::Placed pl;
|
||||
pl.item = pics[i++];
|
||||
pl.tok = (int32_t)r->tokens.size();
|
||||
@@ -718,20 +858,18 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
|
||||
for (const gen::VideoRefMedia& m : r->refs) {
|
||||
if (m.kind != gen::VideoRefMedia::VIDEO) continue;
|
||||
if (has_soundtrack(m.index))
|
||||
put("<Audio " + std::to_string(++audio_ord) + ">: ", false);
|
||||
put("<Video " + std::to_string(m.index) + ">: ", false);
|
||||
put(&r->tokens, "<Audio " + std::to_string(++audio_ord) + ">: ", false);
|
||||
put(&r->tokens, "<Video " + std::to_string(m.index) + ">: ", false);
|
||||
}
|
||||
for (const gen::VideoRefMedia& m : r->refs) {
|
||||
if (m.kind != gen::VideoRefMedia::AUDIO) continue;
|
||||
put("<Audio " + std::to_string(++audio_ord) + ">: ", false);
|
||||
put(&r->tokens, "<Audio " + std::to_string(++audio_ord) + ">: ", false);
|
||||
}
|
||||
if (media) { media->layout(); r->media = std::move(media); }
|
||||
put(prompt, false);
|
||||
put(t.substr(p + kSlot.size()), true);
|
||||
put(&r->tokens, prompt, false);
|
||||
put(&r->tokens, t.substr(p + kSlot.size()), true);
|
||||
} else {
|
||||
put(t.substr(0, p), true);
|
||||
put(prompt, false);
|
||||
put(t.substr(p + kSlot.size()), true);
|
||||
render(prompt, &r->tokens);
|
||||
}
|
||||
if ((int64_t)r->tokens.size() > info.max_text)
|
||||
return bad("prompt", "the prompt" + std::string((ref2va || has_keys)
|
||||
@@ -739,6 +877,50 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
|
||||
" is " + std::to_string(r->tokens.size()) +
|
||||
" tokens; this model takes at most " +
|
||||
std::to_string(info.max_text));
|
||||
if (info.guidance) {
|
||||
render(negative, &r->neg_tokens);
|
||||
if ((int64_t)r->neg_tokens.size() > info.max_text)
|
||||
return bad("negative_prompt", "the negative prompt is " +
|
||||
std::to_string(r->neg_tokens.size()) +
|
||||
" tokens; this model takes at most " +
|
||||
std::to_string(info.max_text));
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- the first frame, at the size the first steps run at */
|
||||
if (has_ref) {
|
||||
int32_t fw = r->width, fh = r->height;
|
||||
if (r->upscale > 1.0) {
|
||||
RadVideoGenDecl geo{}; /* video_small_size reads the size multiple only */
|
||||
geo.size_multiple = info.size_multiple;
|
||||
gen::video_small_size(geo, r->width, r->height, r->upscale, &fw, &fh);
|
||||
}
|
||||
mm::Frame f;
|
||||
std::string why;
|
||||
if (mm::decode_image(ref_bytes.data(), ref_bytes.size(), kMaxRefPixels, &f, &why) < 0)
|
||||
return bad("input_reference", "the picture could not be read: " + why);
|
||||
if (info.image_crf > 0) {
|
||||
mm::Frame rt;
|
||||
const int e = mm::h264_roundtrip(f, info.image_crf, &rt, &why);
|
||||
if (e < 0) {
|
||||
ApiError err = err_bad("input_reference", "the picture could not be prepared: " + why);
|
||||
if (e != RAD_E_INVAL) { err.status = 503; err.type = "server_error"; }
|
||||
return error_response(err, req.peer);
|
||||
}
|
||||
f = std::move(rt);
|
||||
}
|
||||
mm::FrameRGBA a, sized;
|
||||
a.w = f.w;
|
||||
a.h = f.h;
|
||||
a.rgba.resize((size_t)f.w * f.h * 4);
|
||||
for (size_t i = 0, n = (size_t)f.w * f.h; i < n; ++i) {
|
||||
std::memcpy(&a.rgba[4 * i], &f.rgb[3 * i], 3);
|
||||
a.rgba[4 * i + 3] = 255;
|
||||
}
|
||||
mm::resize_bilinear_rgba(a, fw, fh, &sized);
|
||||
r->image.resize((size_t)fw * fh * 3);
|
||||
for (size_t i = 0, n = (size_t)fw * fh; i < n; ++i)
|
||||
std::memcpy(&r->image[3 * i], &sized.rgba[4 * i], 3);
|
||||
}
|
||||
|
||||
/* ---- the encoder's own view of every reference the VAEs consume: pictures and videos through
|
||||
@@ -820,12 +1002,22 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
|
||||
}
|
||||
|
||||
/* ---- admitted and queued: the job holds its place until its file is written */
|
||||
if (!loras.empty()) {
|
||||
std::string why, note;
|
||||
const int s = opt_.gen_lora_acquire(loras, &r->lora_slot, &r->lora_hold, ¬e, &why);
|
||||
if (s < 0) {
|
||||
ApiError e = err_bad("loras", why);
|
||||
if (s == RAD_E_NOTFOUND) { e.status = 404; e.type = "not_found_error"; }
|
||||
else if (s != RAD_E_INVAL) { e.status = 503; e.type = "server_error"; }
|
||||
return error_response(e, req.peer);
|
||||
}
|
||||
}
|
||||
if (auto no = admit(1, req.peer)) return *no;
|
||||
auto j = std::make_shared<VideoJob>();
|
||||
j->id = new_video_id();
|
||||
j->model = opt_.model_id;
|
||||
j->prompt = prompt;
|
||||
j->seconds = rad::fmt("%.2f", (double)frames / fps);
|
||||
j->seconds = auto_len ? std::string("auto") : rad::fmt("%.2f", (double)frames / fps);
|
||||
j->size = std::to_string(W) + "x" + std::to_string(H);
|
||||
j->created_at = unix_now();
|
||||
j->seed = r->seed;
|
||||
@@ -838,6 +1030,13 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
|
||||
r->ticket = j->ticket;
|
||||
const int64_t n_tok = (int64_t)r->tokens.size();
|
||||
const int32_t steps = r->steps;
|
||||
j->guided = info.guidance;
|
||||
for (int i = 0; i < 8; ++i)
|
||||
j->guidance[i] = std::isnan(r->guidance[i]) ? info.guidance_default[i] : r->guidance[i];
|
||||
j->has_negative = info.guidance && (j->guidance[0] != 1.0 || j->guidance[4] != 1.0);
|
||||
if (j->has_negative) j->negative = negative;
|
||||
j->from_image = !r->image.empty();
|
||||
j->decoder = decoder;
|
||||
const double upscale = r->upscale;
|
||||
{
|
||||
std::string w;
|
||||
@@ -855,8 +1054,10 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
|
||||
j->refine = tk.refine;
|
||||
j->upscale_from = std::to_string(tk.small_width) + "x" + std::to_string(tk.small_height);
|
||||
}
|
||||
RAD_INFO("video %s: %s, %lld frames (%s s), %lld prompt tokens, %d steps%s%s, seed=%llu",
|
||||
j->id.c_str(), j->size.c_str(), (long long)frames, j->seconds.c_str(),
|
||||
RAD_INFO("video %s: %s, %s, %lld prompt tokens, %d steps%s%s, seed=%llu",
|
||||
j->id.c_str(), j->size.c_str(),
|
||||
auto_len ? "the length the model chooses"
|
||||
: rad::fmt("%lld frames (%s s)", (long long)frames, j->seconds.c_str()).c_str(),
|
||||
(long long)n_tok, steps > 0 ? steps : (int)tk.steps,
|
||||
tk.refine > 0 ? rad::fmt(" (the first %d at %dx%d, upscaled for the last %d)",
|
||||
(int)(tk.steps - tk.refine), (int)tk.small_width,
|
||||
@@ -897,6 +1098,9 @@ void Server::video_work(std::shared_ptr<VideoJob> j) {
|
||||
std::lock_guard<std::mutex> lk(videos_m_);
|
||||
j->status = "in_progress";
|
||||
j->progress = t.steps > 0 ? (int)(90LL * e.steps_done / t.steps) : 0;
|
||||
} else if (e.kind == gen::VideoEvent::LENGTH) {
|
||||
std::lock_guard<std::mutex> lk(videos_m_);
|
||||
j->seconds = rad::fmt("%.2f", (double)e.n * info.fps_den / info.fps_num);
|
||||
} else if (e.kind == gen::VideoEvent::AUDIO) {
|
||||
if (t.channels > 0)
|
||||
st = vw.add_audio(e.samples.data(), (int64_t)e.samples.size() / t.channels, &why);
|
||||
@@ -1029,6 +1233,17 @@ json Server::video_json(const VideoJob& j) {
|
||||
o["task"] = "ref2va";
|
||||
o["refs"] = j.refs; /* the reference parts, in conditioning order */
|
||||
}
|
||||
if (j.guided) {
|
||||
static const char* kGuide[8] = {
|
||||
"guidance_scale", "stg_scale", "modality_scale", "guidance_rescale",
|
||||
"audio_guidance_scale", "audio_stg_scale", "audio_modality_scale",
|
||||
"audio_guidance_rescale",
|
||||
};
|
||||
for (int i = 0; i < 8; ++i) o[kGuide[i]] = j.guidance[i];
|
||||
if (j.has_negative) o["negative_prompt"] = j.negative;
|
||||
}
|
||||
if (j.from_image) o["input_reference"] = true;
|
||||
if (!j.decoder.empty()) o["decoder"] = j.decoder;
|
||||
o["remixed_from_video_id"] = nullptr;
|
||||
if (j.failed) {
|
||||
json e;
|
||||
|
||||
Reference in new issue
Block a user