Archived
radiance 1.9.0
New models: - LTX-2.5 (base and distilled): video with a stereo soundtrack from text or from text and a first frame, on one card, with its duration head, tiled VAE decoding, the diffusion decoder and the x2 latent upsampler - Krea 2 Raw and Turbo, and FLUX.3 [klein] and its base: text to image, and for FLUX.3 edits from up to ten reference pictures, on one card - GLM-5.3-Flash from AMD's Quark MXFP4 export, on eight cards (John McDonough, Nunze) - Gemma 3 / TranslateGemma 27B with an optional DFlash2 drafter (mici81) Engine: - --kv-cache-dtype fp8_v4 and k6_v4 for Gemma 3 and Qwen3.8-Flash-Next (mici81) - the rotated int8 trunk (i8a8h) for Qwen3.8-27B (eddie168168) - eight-rank all-reduce bands, weighted shards and pieces (Nunze); --host-headroom-mib (sfjes) - the dashboard shows the single-stream decode floor and its most recent window (Memoria) Fixes: prefix-cache reservations kept until their save lands (baKon), tool calls in Responses namespaces (#119), system messages merged when a template refuses several (#137), a prefill continued with no open step (#127), calibration of a Gram accumulation (#122), JSON Schema patterns read unanchored (davetha), GLM-style tool calls, the KV floor counting every sequence's state. Plugin ABI 24.
This commit is contained in:
1 parent
778cbf315e
commit
685ec5bd85
136 files changed
+18917
-3821
No files matched your search
+19
-68
@@ -125,10 +125,7 @@ HttpResponse Server::handle_stats(const HttpRequest&) {
|
||||
o["model"] = opt_.model_id;
|
||||
o["version"] = opt_.version;
|
||||
o["uptime_s"] = unix_now() - started_at_;
|
||||
/* How long this process took to come up, measured on this machine. Raw figure: a restart's
|
||||
* real cost, for whoever is deciding whether one is worth it. 0 before the server listens.
|
||||
* The page no longer consumes it -- see the note on the decode-step detail line for why the
|
||||
* payback arithmetic that used to live there was removed. */
|
||||
/* 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_;
|
||||
@@ -1363,31 +1360,18 @@ for (const k of METRICS) {
|
||||
* 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.
|
||||
*
|
||||
* THE ENDS OF THAT RANGE ARE PERCENTILES, not the extremes. On a min/max axis one rare spike
|
||||
* owns the whole box and the typical variation is squeezed into a couple of pixels: measured over
|
||||
* real /stats samples, prefill sits at zero on a third of polls and spikes past 4,000 on the rest,
|
||||
* which leaves its middle band 0.1px of the 15px available -- a flat line for a metric that is
|
||||
* anything but. Taking the 5th and 95th percentiles and clamping to them gives the ordinary
|
||||
* movement the height it was being denied (the same samples' middle band rises 1.2x to 3.9x
|
||||
* depending on the metric). The cost is stated rather than hidden: a spike beyond the 95th now
|
||||
* draws pinned to the top of the box instead of towering over the line, so the box shows how the
|
||||
* metric has been behaving and not how bad its worst poll was. The number above still carries the
|
||||
* level, and the detail line still carries the extremes.
|
||||
*
|
||||
* THE INSET IS ONE UNIT, not two and three. The stroke is 1.25 units wide, so a half-unit of
|
||||
* clearance keeps it off the edge of the box; the extra it used to leave was a fifth of the
|
||||
* height spent on nothing, and on a 17px box that is the difference between a line that moves
|
||||
* and one that merely shifts. */
|
||||
* 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 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);
|
||||
/* WHEN THE PERCENTILES COLLAPSE, fall back to the extremes. If nine tenths of the window holds
|
||||
* one value, the 5th and 95th land on it and carry nothing -- and a metric that is constant
|
||||
* apart from rare spikes has those spikes as its ONLY news, so pinning them outside the axis
|
||||
* would draw a flat line where the old axis at least showed them. */
|
||||
/* 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);
|
||||
@@ -1686,35 +1670,16 @@ function renderRequests(list, poolTokens) {
|
||||
let prev = null, prevAt = 0, bars = [], devs = [], layerBars = [];
|
||||
let lastStepMs = null, lastTps = null;
|
||||
|
||||
/* THE SINGLE-STREAM FLOOR and the engine's most recent window, shown as two numbers and
|
||||
* interpreted by nobody. 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); the page states
|
||||
* both and draws no conclusion. Neither is asked of a human: a typed ruler goes stale and
|
||||
* mis-advises silently, and a browser meter sees only the steps taken while this tab is open. On
|
||||
* an engine too old to emit the floor, the page falls back to the fastest single-stream step this
|
||||
* tab has seen.
|
||||
*
|
||||
* THERE IS DELIBERATELY NO RESTART ADVICE HERE, and it was not never-built -- it was built,
|
||||
* deployed, measured, and removed the same day (2026-10-18). It compared the floor against the
|
||||
* recent window, called the gap drift, and priced a payback from startup_s. The gap is not drift.
|
||||
* On a HEALTHY shared lane the floor sat flat at 14.79 ms while the recent window moved between
|
||||
* 15.2 and 16.5 ms -- 3% to 11% -- tracking what else the lane was doing: it froze when the lane
|
||||
* went idle and ROSE on a fresh short request, so it was neither context length nor engine age.
|
||||
* The payback formula assumes a restart's improvement is permanent, so acting on it pays the 49 s
|
||||
* bringup and re-drifts within minutes; the line was telling the operator to restart every 12-19
|
||||
* minutes forever, for a gain that was never there. What best-vs-recent actually measures is the
|
||||
* distance between the lane's most favorable moment and its typical one.
|
||||
*
|
||||
* A verdict could go back here IF someone first observes the thing none of today's data shows:
|
||||
* step time rising with ENGINE AGE and STAYING up. Every excursion seen so far was load. The
|
||||
* full chain, including the estimator that survives this, is in patches/CHANGELOG-SOURCE.md. */
|
||||
/* 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 */
|
||||
let bestEver = 0; /* the best engine floor ever seen here, across restarts */
|
||||
try { bestEver = parseFloat(localStorage.getItem("radiance.c1best")) || 0; } catch (e) {}
|
||||
const bestAt = {}; /* fastest step seen at each concurrency, this process */
|
||||
|
||||
|
||||
function update(s, dt) {
|
||||
$("ver").textContent = s.version + " · up " + dur(s.uptime_s);
|
||||
|
||||
@@ -1734,35 +1699,21 @@ function update(s, dt) {
|
||||
M.step.u.textContent = st.u;
|
||||
setMetric("step", lastStepMs, st.n);
|
||||
|
||||
/* THE FLOOR, single-stream on both sides of the engine's own measurement. The floor is a
|
||||
* single-sequence window, so the engine keys it to one row deliberately: a decode step at eight
|
||||
* sequences is a different measurement, and reading it against a single-sequence floor would
|
||||
* report a batch arriving as a slowdown. */
|
||||
/* 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;
|
||||
if (engBestMs > 0 && (bestEver === 0 || engBestMs < bestEver)) {
|
||||
bestEver = engBestMs;
|
||||
try { localStorage.setItem("radiance.c1best", String(bestEver)); } catch (e) {}
|
||||
}
|
||||
const floorMs = engBestMs > 0 ? engBestMs : (c1hist.length ? Math.min(...c1hist) : 0);
|
||||
/* The two engine figures, stated plainly. Painted every poll: without a verdict there is
|
||||
* nothing for a fast repaint to make unactionable, and `recent` only moves when a window of 32
|
||||
* single-sequence steps completes anyway. */
|
||||
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 THIS PROCESS HAS DONE AT THIS CONCURRENCY: ~99% is the fastest the lane has done, anything slower a percentage of it. Keyed by
|
||||
* concurrency on purpose: a c8 step read against the single-stream floor would report the batch
|
||||
* arriving as a slowdown -- the mistake that took the old drift line out. Raw ratio, no
|
||||
* threshold, no colour: the number is the statement. Capped at ~99 (shown with a tilde): `now` is a ~500 ms poll mean while
|
||||
* `best` is a 32-step window mean, so a fast stretch shorter than a window can read faster than the
|
||||
* recorded floor. That is "at your best", not a new record -- the engine only ratchets the floor on a
|
||||
* completed 32-step window, and a sub-window blip is not one. The cap is 99, not 100: a 500 ms window that briefly beats the
|
||||
* floor is not a sustained record, and 100% would claim a floor the window cannot confirm -- it
|
||||
* would read as a bug. ~99% says "at your best" without overclaiming. */
|
||||
/* 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. */
|
||||
if (s.running > 0 && lastStepMs != null) {
|
||||
const k = s.running;
|
||||
if (!(k in bestAt) || lastStepMs < bestAt[k]) bestAt[k] = lastStepMs;
|
||||
|
||||
+29
-4
@@ -127,11 +127,8 @@ struct SchedMetrics {
|
||||
* a decode step regardless of load. */
|
||||
int64_t step_ns = 0;
|
||||
int64_t step_ns_decode = 0;
|
||||
/* The fastest single-sequence decode step this process has measured, nanoseconds; 0 until one
|
||||
* runs. The dashboard reads this instead of asking a human to type a ruler (see the same field
|
||||
* on rad::SchedMetrics, where it is recorded). */
|
||||
/* The single-sequence decode floor and most recent window (rad::SchedMetrics). */
|
||||
int64_t step_ns_decode_best = 0;
|
||||
/* The most recent completed single-sequence decode window mean; see SchedMetrics. */
|
||||
int64_t step_ns_decode_recent = 0;
|
||||
};
|
||||
|
||||
@@ -589,7 +586,19 @@ 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;
|
||||
};
|
||||
|
||||
class IImageGen {
|
||||
@@ -650,6 +659,22 @@ struct VideoGenInfo {
|
||||
/* A latent upscaler: the largest factor (0: none) and the full-size evaluations by default. */
|
||||
double upscale_max = 0.0;
|
||||
int64_t upscale_refine = 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 {
|
||||
|
||||
+92
-31
@@ -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.
|
||||
*
|
||||
@@ -77,7 +79,7 @@ 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);
|
||||
@@ -107,18 +109,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,6 +234,7 @@ 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",
|
||||
"guidance_scale",
|
||||
"num_inference_steps", "width", "height",
|
||||
};
|
||||
for (auto it = body.begin(); it != body.end(); ++it) {
|
||||
@@ -274,6 +293,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);
|
||||
@@ -323,21 +344,35 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
|
||||
}
|
||||
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 in the reference pipeline), 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()) 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 +407,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;
|
||||
@@ -437,17 +472,40 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
|
||||
g->steps = r.steps;
|
||||
g->seed = r.seed;
|
||||
g->previews = r.previews;
|
||||
g->cfg = (float)r.cfg;
|
||||
/* 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 +523,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);
|
||||
@@ -567,12 +625,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 {
|
||||
|
||||
+77
-20
@@ -13,6 +13,7 @@
|
||||
#include <ctime>
|
||||
#include <limits>
|
||||
#include <random>
|
||||
#include <set>
|
||||
#include <type_traits>
|
||||
|
||||
namespace rad {
|
||||
@@ -3854,9 +3855,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 +3889,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 +3993,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 +4053,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 +4176,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 +4232,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 +4264,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));
|
||||
|
||||
+8
-2
@@ -109,6 +109,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 +503,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. */
|
||||
|
||||
+28
-11
@@ -170,7 +170,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);
|
||||
@@ -210,9 +215,7 @@ 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();
|
||||
/* Only a start in the past is a duration. A stamp that arrives out of order is ignored rather
|
||||
* than written as zero: a zero cost would price every restart as free in any payback formula
|
||||
* that divides by it. */
|
||||
/* 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);
|
||||
}
|
||||
@@ -264,20 +267,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;
|
||||
}
|
||||
@@ -1548,10 +1563,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);
|
||||
|
||||
@@ -181,6 +181,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;
|
||||
@@ -198,6 +201,7 @@ public:
|
||||
void note_ready(uint64_t begin_ns);
|
||||
|
||||
private:
|
||||
std::string template_default_effort_;
|
||||
struct Generation;
|
||||
struct TranscriptionJob; /* speech.cpp */
|
||||
struct RealtimeSession; /* realtime.cpp */
|
||||
@@ -357,8 +361,8 @@ 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 -- the
|
||||
* cost of a restart, measured on this machine rather than guessed. 0 until note_ready(). */
|
||||
/* 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
|
||||
|
||||
+212
-27
@@ -15,8 +15,19 @@
|
||||
* (`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.
|
||||
* Nothing that conditions on media is served: `input_reference` and non-empty `conditions` are
|
||||
* refused.
|
||||
* 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
|
||||
@@ -31,6 +42,7 @@
|
||||
#include "oai.h"
|
||||
|
||||
#include "gen/video.h"
|
||||
#include "mm/imaging.h"
|
||||
#include "mm/media.h"
|
||||
#include "mm/mp4.h"
|
||||
#include "rad_internal.h"
|
||||
@@ -40,6 +52,7 @@
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <ctime>
|
||||
#include <random>
|
||||
#include <thread>
|
||||
@@ -66,12 +79,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;
|
||||
@@ -130,11 +155,15 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
|
||||
/* JSON, or a form whose fields are strings (OpenAI's clients send the create call as a form,
|
||||
* since it may carry a file). */
|
||||
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", "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.filename.empty())
|
||||
return error_response(err_bad(p.name, "'" + p.name + "' takes text, not a file"),
|
||||
req.peer);
|
||||
@@ -154,6 +183,10 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
|
||||
static const char* kKnown[] = {
|
||||
"model", "prompt", "seconds", "size", "input_reference", "seed", "num_inference_steps",
|
||||
"task", "target", "conditions", "user", "latent_upscale", "upscale_refine_steps",
|
||||
"negative_prompt", "decoder",
|
||||
/* 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;
|
||||
@@ -178,12 +211,33 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
|
||||
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"))
|
||||
return error_response(err_unsupported("input_reference", "this server makes video from "
|
||||
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", "this model makes video from "
|
||||
"text only"), req.peer);
|
||||
if (has(body, "task") && (!body["task"].is_string() || body["task"].get<std::string>() != "t2va")) {
|
||||
ApiError e = err_unsupported("task", "this server makes video from text: t2va");
|
||||
e.supported = { "t2va" };
|
||||
const std::string task_want = has_ref ? "i2va" : "t2va";
|
||||
if (has(body, "task") && (!body["task"].is_string() ||
|
||||
body["task"].get<std::string>() != task_want)) {
|
||||
ApiError e = err_unsupported("task", has_ref ? "a video from a picture is i2va"
|
||||
: "this request makes video from text: t2va");
|
||||
e.supported = { task_want };
|
||||
return error_response(e, req.peer);
|
||||
}
|
||||
if (has(body, "conditions") && (!body["conditions"].is_array() || !body["conditions"].empty()))
|
||||
@@ -250,7 +304,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");
|
||||
@@ -263,26 +323,81 @@ 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;
|
||||
}
|
||||
/* ---- 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))
|
||||
@@ -320,18 +435,65 @@ 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) {
|
||||
if (s.empty()) return;
|
||||
const auto ids = deps_.tok->encode(s, false, special);
|
||||
r->tokens.insert(r->tokens.end(), ids.begin(), ids.end());
|
||||
auto render = [&](const std::string& text, std::vector<int32_t>* out) {
|
||||
auto put = [&](const std::string& s, bool special) {
|
||||
if (s.empty()) return;
|
||||
const auto ids = deps_.tok->encode(s, false, special);
|
||||
out->insert(out->end(), ids.begin(), ids.end());
|
||||
};
|
||||
put(t.substr(0, p), true);
|
||||
put(text, false);
|
||||
put(t.substr(p + kSlot.size()), true);
|
||||
};
|
||||
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 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);
|
||||
}
|
||||
|
||||
/* ---- admitted and queued: the job holds its place until its file is written */
|
||||
@@ -340,7 +502,7 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
|
||||
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;
|
||||
@@ -348,6 +510,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;
|
||||
@@ -365,8 +534,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, 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, 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,
|
||||
@@ -406,6 +577,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 = mp4.add_audio(e.samples.data(), (int64_t)e.samples.size() / t.channels, &why);
|
||||
@@ -530,6 +704,17 @@ json Server::video_json(const VideoJob& j) {
|
||||
o["upscale_refine_steps"] = j.refine;
|
||||
o["upscale_from"] = j.upscale_from;
|
||||
}
|
||||
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