radiance 1.8.0

- video: MiniMax-H3 and FastVideo's FastH3 8-Step V2, a video with its stereo soundtrack from text
  on OpenAI's /v1/videos, block fp8 on two cards
- music: MiniMax-Music3, songs from lyrics and a description on /v1/audio/speech
- speech: Breeze-TTS-2 on /v1/audio/speech and vLLM-Omni's realtime WebSocket
- runtime LoRA adapters beside the base model, picked per request by `model` (baKon, #105)
- several agent streams keep their cached history: --checkpoint-slots auto, the new default, sizes
  the snapshot store by --max-num-seqs (#108)
- the Swift 1.5 27B W4 releases convert and serve: compressed-tensors AWQ and GPTQ int4, AutoRound,
  ModelOpt NVFP4 (#110)
- the image's host tests pass where perf_event_open is refused, as in BuildKit's sandbox (#106)
- plugin ABI 21: out-of-tree plugins must be rebuilt
This commit is contained in:
Deadcode committed 2026-10-18 11:38:37 +02:00
1 parent 91127395ee
commit 7a7707a955
179 files changed
+37542 -1892

No files matched your search

+8 -3
View File
@@ -8,8 +8,9 @@
*
* Deliberately absent, answering 404: vLLM's /pooling, /classify, /score and /rerank (no
* classifier or cross-encoder head), /sleep, /wake_up and /is_sleeping (no sleep mode; weights
* are placed once, spec §5), the LoRA endpoints (no LoRA), /invocations (a SageMaker envelope),
* stored Responses-API responses (would need a conversation store), and llama-server's /slots.
* are placed once, spec §5), /invocations (a SageMaker envelope), stored Responses-API responses
* (would need a conversation store), and llama-server's /slots and /lora-adapters (a runtime LoRA
* adapter is chosen per request by `model`; vLLM's load and unload routes are in server.cpp).
*/
#include "server.h"
@@ -311,6 +312,8 @@ HttpResponse Server::handle_props(const HttpRequest&) {
params["backend_sampling"] = false;
params["timings_per_token"] = false;
params["post_sampling_probs"] = false;
/* The adapters a request runs with when it names none: never any, since an adapter is chosen
* by `model` (they are listed on /v1/models). */
params["lora"] = json::array();
json gen;
@@ -385,7 +388,7 @@ json Server::capabilities() const {
caps["reasoning"] = deps_.chat && deps_.chat->supports_reasoning();
/* An image model reads pictures only for edits and writes no text a grammar could constrain,
* whatever its conditioning network's processor would take. */
const bool img = opt_.image_model;
const bool img = opt_.image_model || opt_.video_model;
caps["grammar"] = !img && deps_.grammar != nullptr;
caps["embedding"] = deps_.embed != nullptr;
caps["image"] = deps_.mm && deps_.mm->accepts(MediaKind::Image);
@@ -394,6 +397,8 @@ json Server::capabilities() const {
caps["logprobs"] = opt_.supports_logprobs;
caps["image_generation"] = deps_.images != nullptr;
caps["image_edit"] = deps_.images != nullptr && deps_.images->info().max_refs > 0;
caps["audio_generation"] = deps_.audio != nullptr;
caps["video_generation"] = deps_.videos != nullptr;
/* The efforts a chat request may send, probed from the template at startup; null when it
* takes any word. "none" and "minimal" are this server's and turn thinking off. */
if (lim_.reasoning_efforts.empty()) {
+442
View File
@@ -0,0 +1,442 @@
/* audio_gen.cpp -- POST /v1/audio/speech over an audio generator (core/gen/audio_driver.h): music
* from a description and lyrics, or speech from text and a description of the voice.
*
* The request is OpenAI's speech request: `input` is the text the audio carries (a song's lyrics,
* as SGLang-Omni reads it for a music model, or the words to speak) and `instructions` describes
* it (the piece, or the voice). A model with a template for requests without instructions takes
* them as optional. `voice` is accepted and ignored (the instructions say who sings or speaks),
* `speed` must be 1. The length is `max_new_tokens`, in the model's frames as SGLang-Omni counts
* it, or `duration` in seconds; without either the audio may run to the model's longest, and the
* model usually ends it before that. Also read: `seed` (-1 or absent picks one),
* `guidance_scale` (the model's guidance: the denoiser's for a music model, the frame model's for
* a speech one) and, for a model with a denoiser, `num_inference_steps`.
*
* Prompt: the plugin's template with its slots filled, each text first rewritten by the plugin
* into the form the model was trained on (rad_arch_text_prepare). The template is tokenised with
* its special tokens and the texts without, so a caller cannot write the model's control tokens
* into a lyric. A model that declares the unconditional branch's own template gets that one
* rendered from the same texts.
*
* Response: the whole piece, once it is finished, as `response_format` wav (16-bit PCM, the
* model's rate and channels) or pcm (the same samples raw, little-endian). Streamed as the
* vocoder plays each window, in two forms (vLLM-Omni's reading of OpenAI's `stream_format`):
* `stream_format` "audio" sends the bytes themselves as they are made (a wav's header then states
* no length, as a stream's cannot), and `stream` true or `stream_format` "sse" sends Server-Sent
* Events, `speech.audio.delta` with a chunk of base64 PCM and `speech.audio.done` with the usage,
* or `speech.audio.error`.
*/
#include "server.h"
#include "oai.h"
#include "gen/audio.h"
#include "rad_internal.h"
#include <nlohmann/json.hpp>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <map>
#include <random>
namespace rad {
namespace server {
namespace {
void put_le(std::string* s, uint32_t v, int bytes) {
for (int i = 0; i < bytes; ++i) s->push_back((char)((v >> (8 * i)) & 0xff));
}
} /* namespace */
/* Samples in [-1, 1] as 16-bit PCM, as libsndfile writes float data to PCM_16 (scaled by 32767,
* rounded, clipped). */
void append_pcm16(const std::vector<float>& x, std::string* out) {
const size_t at = out->size();
out->resize(at + 2 * x.size());
char* p = &(*out)[at];
for (size_t i = 0; i < x.size(); ++i) {
const float v = std::min(1.0f, std::max(-1.0f, x[i]));
const int16_t q = (int16_t)std::lrint(v * 32767.0f);
std::memcpy(p + 2 * i, &q, 2);
}
}
/* A RIFF/WAVE header for `bytes` of 16-bit PCM; -1 states no length, as a stream's header must,
* with both sizes at their largest (how ffmpeg and libsndfile read a WAV of unknown length). */
std::string wav_header(int64_t bytes, int64_t rate, int64_t channels) {
std::string h;
h += "RIFF";
put_le(&h, bytes < 0 ? 0xffffffffu : (uint32_t)(36 + bytes), 4);
h += "WAVEfmt ";
put_le(&h, 16, 4);
put_le(&h, 1, 2); /* PCM */
put_le(&h, (uint32_t)channels, 2);
put_le(&h, (uint32_t)rate, 4);
put_le(&h, (uint32_t)(rate * channels * 2), 4); /* byte rate */
put_le(&h, (uint32_t)(channels * 2), 2); /* block align */
put_le(&h, 16, 2); /* bits a sample */
h += "data";
put_le(&h, bytes < 0 ? 0xffffffffu : (uint32_t)bytes, 4);
return h;
}
/* The request's description of the audio, `text` its input: the instructions, the tempo, the
* length, the denoiser's steps, the guidance and the seed, and the prompt rendered from the
* model's templates. */
int Server::speech_request(const json& body, const std::string& text,
std::unique_ptr<gen::AudioRequest>* out, ApiError* err) {
const AudioGenInfo& info = deps_.audio->info();
auto fail = [&](ApiError e) {
*err = std::move(e);
return -1;
};
auto str = [&](const char* k, std::string* v) -> int {
if (!body.contains(k) || body[k].is_null()) return 0;
if (!body[k].is_string()) return -1;
*v = body[k].get<std::string>();
return 1;
};
auto blank = [](const std::string& t) {
return t.find_first_not_of(" \t\r\n") == std::string::npos;
};
std::string inst;
const int has_inst = str("instructions", &inst);
if (has_inst < 0) return fail(err_bad("instructions", "expected a string"));
if (has_inst > 0 && blank(inst)) inst.clear();
if (inst.empty() && info.tmpl_plain.empty())
return fail(err_bad("instructions", "this model needs instructions, as a non-empty "
"string: for a song its genre, mood, vocals and "
"instruments"));
if (body.contains("speed") && !body["speed"].is_null() &&
!(body["speed"].is_number() && body["speed"].get<double>() == 1.0))
return fail(err_unsupported("speed", "this model keeps its own tempo; the instructions "
"set it"));
auto r = std::make_unique<gen::AudioRequest>();
/* The length: frames, or seconds, or the model's longest. */
const bool has_frames = body.contains("max_new_tokens") && !body["max_new_tokens"].is_null();
const bool has_dur = body.contains("duration") && !body["duration"].is_null();
if (has_frames && has_dur)
return fail(err_bad("duration", "give max_new_tokens or duration, not both"));
r->max_frames = info.max_frames;
if (has_frames) {
if (!body["max_new_tokens"].is_number_integer() ||
body["max_new_tokens"].get<int64_t>() < 1 ||
body["max_new_tokens"].get<int64_t>() > info.max_frames)
return fail(err_bad("max_new_tokens", "expected an integer in 1.." +
std::to_string(info.max_frames) + " (frames, " +
rad::fmt("%g", (double)info.frame_rate_num /
(double)info.frame_rate_den) +
" a second)"));
r->max_frames = body["max_new_tokens"].get<int64_t>();
}
if (has_dur) {
const double max_s = (double)info.max_frames * info.frame_rate_den / info.frame_rate_num;
if (!body["duration"].is_number() || !(body["duration"].get<double>() > 0) ||
body["duration"].get<double>() > max_s)
return fail(err_bad("duration", "expected seconds in (0, " +
std::to_string((int64_t)max_s) + "]"));
r->max_frames = std::max<int64_t>(
1, std::min<int64_t>(info.max_frames,
(int64_t)std::ceil(body["duration"].get<double>() *
info.frame_rate_num / info.frame_rate_den)));
}
if (body.contains("num_inference_steps") && !body["num_inference_steps"].is_null()) {
if (info.default_steps <= 0)
return fail(err_unsupported("num_inference_steps", "this model has no denoiser"));
if (!body["num_inference_steps"].is_number_integer() ||
body["num_inference_steps"].get<int64_t>() < 1 ||
body["num_inference_steps"].get<int64_t>() > 1000)
return fail(err_bad("num_inference_steps", "expected an integer in 1..1000"));
r->steps = (int32_t)body["num_inference_steps"].get<int64_t>();
}
if (body.contains("guidance_scale") && !body["guidance_scale"].is_null()) {
if (!body["guidance_scale"].is_number() || !(body["guidance_scale"].get<double>() >= 1.0) ||
body["guidance_scale"].get<double>() > 30.0)
return fail(err_bad("guidance_scale", "expected a number in [1, 30]"));
r->cfg = (float)body["guidance_scale"].get<double>();
}
bool seed_given = false;
if (body.contains("seed") && !body["seed"].is_null()) {
if (!body["seed"].is_number_integer()) return fail(err_bad("seed", "expected an integer"));
r->seed = (uint64_t)body["seed"].get<int64_t>();
seed_given = body["seed"].is_number_unsigned() || body["seed"].get<int64_t>() != -1;
}
if (!seed_given) {
/* 53 bits, as the images endpoints choose one: JavaScript reads a number as a double. */
std::random_device rd;
r->seed = (((uint64_t)rd() << 32) ^ rd()) & (((uint64_t)1 << 53) - 1);
}
/* ---- the prompt */
std::string i2, t2, why;
if (!inst.empty() && deps_.audio->prepare(RAD_TEXT_INSTRUCTIONS, inst, &i2, &why) < 0)
return fail(err_bad("instructions", why));
if (deps_.audio->prepare(RAD_TEXT_INPUT, text, &t2, &why) < 0)
return fail(err_bad("input", why));
/* A template a segment at a time: its own text with special tokens, each slot without. */
auto render = [&](const std::string& t, std::vector<int32_t>* ids_out) {
static const std::string kInst = "{instructions}", kInput = "{input}";
size_t at = 0;
while (at <= t.size()) {
const size_t a = t.find(kInst, at), b = t.find(kInput, at);
const size_t p = std::min(a, b);
const std::string lit =
t.substr(at, p == std::string::npos ? std::string::npos : p - at);
if (!lit.empty()) {
const auto ids = deps_.tok->encode(lit, false, /*parse_special=*/true);
ids_out->insert(ids_out->end(), ids.begin(), ids.end());
}
if (p == std::string::npos) break;
const bool is_inst = p == a;
const auto ids = deps_.tok->encode(is_inst ? i2 : t2, false, /*parse_special=*/false);
ids_out->insert(ids_out->end(), ids.begin(), ids.end());
at = p + (is_inst ? kInst : kInput).size();
}
};
render(inst.empty() ? info.tmpl_plain : info.tmpl, &r->tokens);
if (!info.neg_tmpl.empty()) render(info.neg_tmpl, &r->neg_tokens);
const size_t n_prompt = std::max(r->tokens.size(), r->neg_tokens.size());
if ((int64_t)n_prompt > info.max_prompt)
return fail(err_bad("input", "the prompt is " + std::to_string(n_prompt) +
" tokens; this model takes at most " +
std::to_string(info.max_prompt)));
*out = std::move(r);
return 0;
}
HttpResponse Server::handle_speech(const HttpRequest& req) {
if (!deps_.audio || !deps_.tok)
return error_response(err_not_implemented(
opt_.image_model ? "/v1/audio/speech requires an audio generation model; this one "
"makes images"
: "/v1/audio/speech requires an audio generation model; this one "
"generates text"), req.peer);
const AudioGenInfo& info = deps_.audio->info();
json body = json::object();
{
ApiError err;
if (parse_request_object(req.body, lim_, &body, &err) < 0)
return error_response(err, req.peer);
}
static const char* kKnown[] = {
"model", "input", "instructions", "voice", "response_format", "speed", "stream",
"stream_format", "seed", "max_new_tokens", "duration", "num_inference_steps",
"guidance_scale", "user",
};
for (auto it = body.begin(); it != body.end(); ++it) {
bool known = false;
for (const char* k : kKnown) known = known || it.key() == k;
if (!known)
return error_response(err_bad(it.key(), "'" + it.key() + "' is not a field of "
"/v1/audio/speech"), req.peer);
}
auto str = [&](const char* k, std::string* out) -> int {
if (!body.contains(k) || body[k].is_null()) return 0;
if (!body[k].is_string()) return -1;
*out = body[k].get<std::string>();
return 1;
};
std::string text, fmt;
if (str("input", &text) <= 0 || text.find_first_not_of(" \t\r\n") == std::string::npos)
return error_response(err_bad("input", "the text is required, as a non-empty string"),
req.peer);
/* How the audio comes back: whole, as raw bytes while it is made, or as events. */
bool stream = false;
if (body.contains("stream") && !body["stream"].is_null()) {
if (!body["stream"].is_boolean())
return error_response(err_bad("stream", "expected a boolean"), req.peer);
stream = body["stream"].get<bool>();
}
std::string sfmt;
if (str("stream_format", &sfmt) < 0 || (!sfmt.empty() && sfmt != "sse" && sfmt != "audio")) {
ApiError e = err_unsupported("stream_format", "a stream is sent as sse or audio");
e.supported = { "sse", "audio" };
return error_response(e, req.peer);
}
if (stream && sfmt == "audio")
return error_response(err_bad("stream", "stream sends Server-Sent Events and "
"stream_format audio sends the bytes themselves; "
"give one"), req.peer);
const bool sse = stream || sfmt == "sse", raw = sfmt == "audio";
if (str("response_format", &fmt) < 0) fmt = "?";
if (fmt.empty()) fmt = sse ? "pcm" : "wav";
if (fmt != "wav" && fmt != "pcm") {
ApiError e = err_unsupported("response_format", "this server writes wav or pcm");
e.supported = { "wav", "pcm" };
return error_response(e, req.peer);
}
if (sse && fmt != "pcm")
return error_response(err_unsupported("response_format", "an event carries raw PCM; set "
"response_format pcm"), req.peer);
std::unique_ptr<gen::AudioRequest> r;
{
ApiError err;
if (speech_request(body, text, &r, &err) < 0) return error_response(err, req.peer);
}
/* ---- admitted and queued */
if (auto no = admit(1, req.peer)) return *no;
r->ticket = std::make_shared<gen::AudioTicket>();
std::shared_ptr<gen::AudioTicket> ticket = r->ticket;
const int64_t frames_max = r->max_frames;
const uint64_t seed = r->seed;
const int64_t n_tok = (int64_t)r->tokens.size();
{
std::string w;
const int s = deps_.audio->submit(std::move(r), &w);
if (s < 0) {
release(1);
ApiError e = err_bad("", w.empty() ? std::string(rad_strerror(s)) : w);
if (s != RAD_E_INVAL) { e.status = 503; e.type = "server_error"; }
return error_response(e, req.peer);
}
}
RAD_INFO("audio: %lld prompt tokens, up to %lld frames, seed=%llu", (long long)n_tok,
(long long)frames_max, (unsigned long long)seed);
if (sse || raw) return stream_speech(ticket, info, n_tok, seed, sse, fmt == "wav");
/* ---- the windows as they are played, in order */
std::vector<gen::AudioChunk> chunks;
for (;;) {
gen::AudioChunk c;
bool to = false;
if (ticket->next(&c, 200, &to)) {
chunks.push_back(std::move(c));
continue;
}
if (!to) break;
if (req.peer_gone()) {
ticket->cancel.store(true);
release(1);
metrics_.observe_http(499);
return HttpResponse::text(499, "client closed request\n");
}
if (stopping_.load()) {
ticket->cancel.store(true);
release(1);
return error_response(err_overloaded("the server is shutting down"), req.peer);
}
}
release(1);
if (ticket->status() < 0 || chunks.empty()) {
/* RAD_E_INVAL is the driver's refusal of this request (or the model ending the piece
* before it began), so a 400; anything else failed while running. */
ApiError e;
const bool client = ticket->status() == RAD_E_INVAL;
e.status = client ? 400 : 500;
e.type = client ? "invalid_request_error" : "server_error";
e.message = ticket->why().empty() ? "the audio generator failed" : ticket->why();
return error_response(e, req.peer);
}
std::sort(chunks.begin(), chunks.end(), [](const gen::AudioChunk& a, const gen::AudioChunk& b) {
return a.window < b.window;
});
std::string pcm;
for (const gen::AudioChunk& c : chunks) append_pcm16(c.samples, &pcm);
const double secs = (double)pcm.size() / 2.0 / (double)(info.channels * info.sample_rate);
RAD_INFO("audio: %.1f s from %lld frames in %lld windows, %.1f s%s", secs,
(long long)ticket->frames, (long long)ticket->windows,
(double)(ticket->t_done_ns - ticket->t_submit_ns) * 1e-9,
ticket->model_ended ? "" : " (the request's length)");
HttpResponse res;
res.status = 200;
if (fmt == "wav") {
res.content_type = "audio/wav";
res.body = wav_header((int64_t)pcm.size(), info.sample_rate, info.channels) + pcm;
} else {
res.content_type = "audio/pcm";
res.body = std::move(pcm);
}
res.set_header("X-Audio-Sample-Rate", std::to_string(info.sample_rate));
res.set_header("X-Audio-Channels", std::to_string(info.channels));
res.set_header("X-Seed", std::to_string(seed));
metrics_.observe_http(200);
return res;
}
/* The piece as it is played: each window's samples once every earlier window has gone (the driver
* may finish them out of order), as bytes or as `speech.audio.delta` events. */
HttpResponse Server::stream_speech(std::shared_ptr<gen::AudioTicket> ticket,
const AudioGenInfo& info, int64_t n_tok, uint64_t seed,
bool sse, bool wav) {
HttpResponse res;
res.status = 200;
res.content_type = sse ? "text/event-stream" : wav ? "audio/wav" : "audio/pcm";
if (sse) res.set_header("Cache-Control", "no-cache");
res.set_header("X-Audio-Sample-Rate", std::to_string(info.sample_rate));
res.set_header("X-Audio-Channels", std::to_string(info.channels));
res.set_header("X-Seed", std::to_string(seed));
struct State {
std::map<int32_t, std::vector<float>> held; /* windows ahead of the next one */
int32_t next = 0;
bool header = false, finished = false, released = false;
};
auto st = std::make_shared<State>();
st->header = !wav || sse;
const int64_t rate = info.sample_rate, channels = info.channels;
res.next = [this, ticket, st, sse, rate, channels, n_tok](std::string& chunk) -> bool {
if (st->finished) return false;
chunk.clear();
if (!st->header) {
chunk = wav_header(-1, rate, channels);
st->header = true;
}
gen::AudioChunk c;
bool to = false;
if (ticket->next(&c, 100, &to)) {
st->held[c.window] = std::move(c.samples);
std::string pcm;
for (auto it = st->held.find(st->next); it != st->held.end();
it = st->held.find(st->next)) {
append_pcm16(it->second, &pcm);
st->held.erase(it);
++st->next;
}
if (pcm.empty()) return true;
if (!sse) {
chunk += pcm;
return true;
}
json ev;
ev["type"] = "speech.audio.delta";
ev["audio"] = base64_encode(pcm.data(), pcm.size());
ev["response_format"] = "pcm";
ev["sample_rate"] = rate;
ev["channels"] = channels;
chunk += "event: speech.audio.delta\ndata: " + json_dump(ev) + "\n\n";
return true;
}
if (to) return !stopping_.load();
st->finished = true;
if (!st->released) { st->released = true; release(1); }
if (!sse) return !chunk.empty();
json ev;
if (ticket->status() < 0 || st->next == 0) {
ev["type"] = "speech.audio.error";
ev["error"] = json{
{ "message", ticket->why().empty() ? "the audio generator failed" : ticket->why() },
{ "type", ticket->status() == RAD_E_INVAL ? "invalid_request_error"
: "server_error" } };
} else {
ev["type"] = "speech.audio.done";
ev["usage"] = json{ { "input_tokens", n_tok }, { "output_tokens", ticket->frames },
{ "total_tokens", n_tok + ticket->frames } };
}
chunk += "event: " + ev["type"].get<std::string>() + "\ndata: " + json_dump(ev) + "\n\n";
return true;
};
res.on_close = [this, ticket, st](bool ok) {
if (!ok) ticket->cancel.store(true);
if (!st->released) { st->released = true; release(1); }
};
metrics_.observe_http(200);
return res;
}
} /* namespace server */
} /* namespace rad */
+3
View File
@@ -417,6 +417,9 @@ public:
return true;
}
bool send(const std::string& text) override { return ws_.send(text); }
bool send_binary(const std::string& bytes) override {
return ws_.send(bytes.data(), bytes.size());
}
void close(int code, const std::string& reason) override {
ws_.close((httplib::ws::CloseStatus)code, reason);
}
+6
View File
@@ -90,6 +90,12 @@ public:
virtual bool read(std::string* msg, bool* binary) = 0;
/* A text message. Safe from any thread; false once the connection is gone. */
virtual bool send(const std::string& text) = 0;
/* A binary message (raw audio). Safe from any thread; false once the connection is gone, or
* for a connection that carries text only. */
virtual bool send_binary(const std::string& bytes) {
(void)bytes;
return false;
}
/* Ends the connection with a close code and reason (RFC 6455 §7.4); a read() blocked on it
* returns false once the peer has answered or gone. Safe from any thread. */
virtual void close(int code, const std::string& reason) = 0;
+55 -1
View File
@@ -20,7 +20,7 @@
#include <vector>
namespace rad {
namespace gen { struct Request; }
namespace gen { struct Request; struct AudioRequest; class AudioTicket; struct VideoRequest; class VideoTicket; }
namespace mm { struct Frame; struct Item; }
namespace server {
@@ -599,5 +599,59 @@ public:
virtual int64_t running() const = 0;
};
/* The audio generator (core/gen/audio_driver.h), for a model that makes music or other audio from
* text: its declared prompt template and limits, the plugin's rewrite of a request's texts into
* the form it was trained on, and its request queue. The server renders and tokenises the prompt
* and reads the audio back off the ticket, a window at a time. */
struct AudioGenInfo {
/* The prompt templates (RadAudioGenDecl): with instructions, without them ("" makes them
* required), and the unconditional branch's own ("" derives it from the conditional prompt). */
std::string name, tmpl, tmpl_plain, neg_tmpl;
int64_t max_prompt = 0, max_frames = 0, frame_rate_num = 1, frame_rate_den = 1;
int64_t sample_rate = 0, channels = 0;
int64_t default_steps = 0, max_lanes = 1; /* default_steps 0: no denoiser */
double default_cfg = 1.0;
};
class IAudioGen {
public:
virtual ~IAudioGen() = default;
virtual const AudioGenInfo& info() const = 0;
/* `in` rewritten as the model wants text for `field` (RAD_TEXT_*); the text unchanged when the
* plugin states no rewrite. RAD_E_INVAL with `why` for text the model cannot take. */
virtual int prepare(int field, const std::string& in, std::string* out,
std::string* why) const = 0;
/* Queue a request; refused at once, with `why`, when it can never run. */
virtual int submit(std::unique_ptr<gen::AudioRequest> r, std::string* why) = 0;
virtual int64_t queued() const = 0;
virtual int64_t running() const = 0;
};
/* The video generator (core/gen/video_driver.h), for a model that makes a video and its
* soundtrack from text: its declared prompt template, sizes and lengths, and its request queue.
* The server renders and tokenises the prompt, queues the request as a job, and turns what the
* ticket hands back into an MP4 file. */
struct VideoGenInfo {
std::string name, tmpl;
int64_t max_text = 0;
int64_t fps_num = 1, fps_den = 1;
int64_t frames_per_chunk = 1, frames_tail = 0, min_chunks = 1, max_chunks = 1;
int64_t size_multiple = 32, min_side = 0, max_area = 0, max_aspect = 1;
int64_t default_width = 0, default_height = 0, default_chunks = 1;
int64_t sample_rate = 0, channels = 0;
int64_t default_steps = 0, max_steps = 0, max_lanes = 1;
bool fixed_steps = false; /* a trained schedule: max_steps grid points and no other */
};
class IVideoGen {
public:
virtual ~IVideoGen() = default;
virtual const VideoGenInfo& info() const = 0;
/* Queue a request; refused at once, with `why`, when it can never run. */
virtual int submit(std::unique_ptr<gen::VideoRequest> r, std::string* why) = 0;
virtual int64_t queued() const = 0;
virtual int64_t running() const = 0;
};
} /* namespace server */
} /* namespace rad */
+3 -1
View File
@@ -313,7 +313,9 @@ const Guarded kGuarded[] = {
"implemented" },
{ "suffix", empty_value, "an empty string", "infilling through /v1/completions is not "
"implemented" },
{ "lora", empty_value, "an empty list", "LoRA is explicitly out of scope (spec, Scope)" },
{ "lora", empty_value, "an empty list",
"a per-request adapter list is not served; a runtime LoRA adapter is chosen by `model` "
"(--lora)" },
{ "modalities", text_only, "[\"text\"]", "output modalities other than text are not "
"implemented" },
{ "audio", empty_value, "null", "audio output is not implemented" },
+42 -13
View File
@@ -96,6 +96,14 @@ void Server::register_routes() {
router_.post("/v1/images/edits", [this](const HttpRequest& q) { return handle_images(q, true); });
router_.post("/v1/systemone", [this](const HttpRequest& q) { return handle_systemone(q); });
/* Speech to text, for a model whose plugin says how it transcribes (RadAudioFormat). */
router_.post("/v1/audio/speech", [this](const HttpRequest& q) { return handle_speech(q); });
router_.post("/v1/videos", [this](const HttpRequest& q) { return handle_video_create(q); });
router_.get ("/v1/videos", [this](const HttpRequest& q) { return handle_video_list(q); });
router_.get ("/v1/videos/:id", [this](const HttpRequest& q) { return handle_video_get(q); });
router_.add ("DELETE", "/v1/videos/:id",
[this](const HttpRequest& q) { return handle_video_delete(q); });
router_.get ("/v1/videos/:id/content",
[this](const HttpRequest& q) { return handle_video_content(q); });
router_.post("/v1/audio/transcriptions",
[this](const HttpRequest& q) { return handle_transcription(q); });
/* The same, live over a WebSocket (OpenAI's realtime transcription session). A plain GET
@@ -110,6 +118,19 @@ void Server::register_routes() {
r.set_header("Upgrade", "websocket");
return r;
});
/* Speech made while its text is still being written (vLLM-Omni's realtime speech session). */
router_.socket("/v1/audio/speech/stream",
[this](const HttpRequest& q, WsConn& c) { handle_speech_stream(q, c); });
router_.get ("/v1/audio/speech/stream", [this](const HttpRequest& q) {
ApiError e;
e.status = 426;
e.type = "invalid_request_error";
e.message = "/v1/audio/speech/stream is a WebSocket: connect with an Upgrade: websocket "
"request";
HttpResponse r = error_response(e, q.peer);
r.set_header("Upgrade", "websocket");
return r;
});
router_.get ("/v1/models", [this](const HttpRequest& q) { return handle_models(q); });
router_.get ("/v1/models/*id", [this](const HttpRequest& q) { return handle_models(q); });
router_.post("/v1/load_lora_adapter", [this](const HttpRequest& q) { return handle_lora_admin(q, true); });
@@ -126,6 +147,7 @@ void Server::register_routes() {
router_.post("/images/generations", [this](const HttpRequest& q) { return handle_images(q, false); });
router_.post("/images/edits", [this](const HttpRequest& q) { return handle_images(q, true); });
router_.post("/audio/transcriptions", [this](const HttpRequest& q) { return handle_transcription(q); });
router_.post("/audio/speech", [this](const HttpRequest& q) { return handle_speech(q); });
router_.get ("/models", [this](const HttpRequest& q) { return handle_models(q); });
/* llama-server's: the prompt a chat request renders to, and how many tokens it is. */
router_.post("/apply-template", [this](const HttpRequest& q) { return handle_apply_template(q); });
@@ -281,6 +303,7 @@ std::string Server::check_thinking_budget() const {
void Server::stop() {
stopping_.store(true);
transport_.stop();
stop_videos();
drain_graveyard(2000);
}
@@ -390,9 +413,9 @@ int Server::submit_all(const OaiRequest& r, std::vector<Generation>* gens, ApiEr
}
}
/* RUNTIME LoRA: `model` picks the adapter. The served model's own name, or no name, is the
* base; with adapters enabled anything else must be a loaded adapter -- a typo served by the
* base would answer as the wrong model and say nothing. */
/* Runtime LoRA: `model` picks the adapter. The served model's own name, or no name, is the
* base; with adapters enabled anything else must be a loaded adapter, since a typo served by
* the base would answer as the wrong model without a word. */
int32_t lora_slot = -1;
uint64_t lora_uid = 0;
std::shared_ptr<void> lora_hold;
@@ -1269,6 +1292,10 @@ std::optional<HttpResponse> Server::refuse_text(const std::string& peer, ApiShap
"generates no text"
: opt_.image_model ? "this is an image model: it serves /v1/images/generations "
"and /v1/images/edits and generates no text"
: opt_.audio_model ? "this is an audio model: it serves /v1/audio/speech and "
"generates no text"
: opt_.video_model ? "this is a video model: it serves /v1/videos and generates "
"no text"
: nullptr;
if (!why) return std::nullopt;
return error_response(err_not_implemented(why), peer, shape);
@@ -1536,8 +1563,10 @@ HttpResponse Server::handle_embeddings(const HttpRequest& req) {
if (!deps_.embed)
return error_response(err_not_implemented(
opt_.image_model ? "/v1/embeddings requires an embedding model; this one makes images"
: "/v1/embeddings requires an embedding model; this one generates "
"text"), req.peer);
: opt_.audio_model ? "/v1/embeddings requires an embedding model; this one makes audio"
: opt_.video_model ? "/v1/embeddings requires an embedding model; this one makes video"
: "/v1/embeddings requires an embedding model; this one generates "
"text"), req.peer);
OaiRequest r;
ApiError err;
@@ -1775,7 +1804,7 @@ HttpResponse Server::handle_systemone(const HttpRequest& req) {
HttpResponse Server::handle_models(const HttpRequest& req) {
const std::string id = req.param("id");
/* RUNTIME LoRA: each loaded adapter is a model of its own, whose parent is the served one. */
/* Runtime LoRA: each loaded adapter is a model of its own, whose parent is the served one. */
std::vector<std::string> adapters;
if (opt_.lora_names) adapters = opt_.lora_names();
const bool is_adapter = !id.empty() && std::find(adapters.begin(), adapters.end(), id) != adapters.end();
@@ -1805,9 +1834,9 @@ HttpResponse Server::handle_models(const HttpRequest& req) {
return HttpResponse::json_body(200, id.empty() ? models_body(cards) : model_body(c));
}
/* 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. */
/* 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. */
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) {
@@ -1845,10 +1874,10 @@ HttpResponse Server::handle_lora_admin(const HttpRequest& req, bool load) {
if (s == RAD_E_STATE) return fail(409, "conflict_error", err);
if (s == RAD_E_FULL) return fail(503, "service_unavailable", err);
if (s < 0) return fail(400, "invalid_request_error", err.empty() ? std::string(rad_strerror(s)) : err);
/* AN UNLOAD OF AN ADAPTER IN USE DRAINS IT (lora/slots.h): accepted, not done. New requests
* naming it are already refused as an unknown model and it is off /v1/models; the requests
* counted here finish normally, and the last of them frees the slot. Asking again answers
* the same with the count as it is then, and a 404 once it is gone. */
/* An unload of an adapter in use drains it (lora/slots.h): accepted, not done. New requests
* naming it are refused as an unknown model and it is off /v1/models; the requests counted
* here finish, and the last of them frees the slot. Asking again answers with the count as it
* is then, and 404 once it is gone. */
if (!load && in_flight > 0) {
metrics_.observe_http(202);
return HttpResponse::json_body(202, json{ { "action", "draining" }, { "lora_name", name },
+53 -1
View File
@@ -39,6 +39,8 @@ struct Deps {
IEmbedder* embed = nullptr; /* absent -> /v1/embeddings is 501 */
IMultimodal* mm = nullptr; /* absent -> image and audio parts are 501 */
IImageGen* images = nullptr; /* absent -> the images endpoints are 501 */
IAudioGen* audio = nullptr; /* absent -> /v1/audio/speech is 501 */
IVideoGen* videos = nullptr; /* absent -> /v1/videos is 501 */
const SpeechFormat* speech = nullptr; /* absent -> /v1/audio/transcriptions is 501 */
/* Engine-side state the server cannot see (per-card VRAM, the expert plane), as a snapshot
@@ -56,6 +58,16 @@ struct ServerOptions {
/* An image generator (rad_declare_generator) generates no text: the text endpoints answer
* 501 naming /v1/images/generations and /v1/images/edits. */
bool image_model = false;
/* An audio generator (rad_declare_audio_generator) generates no text either: the text
* endpoints answer 501 naming /v1/audio/speech. */
bool audio_model = false;
/* A video generator (rad_declare_video_generator) generates no text either: the text
* endpoints answer 501 naming /v1/videos. */
bool video_model = false;
/* How long a finished video's file is kept for /v1/videos/{id}/content, in seconds, and how
* many finished videos are kept at most (the oldest go first). */
int64_t video_ttl_s = 3600;
int64_t max_videos = 32;
/* The decision protocol from the container's `decision.type`: "d1" serves /v1/systemone
* (systemone.h); empty answers it 501. Never inferred from a name. */
std::string decision_type;
@@ -119,7 +131,7 @@ struct ServerOptions {
* clock only mean something under load: queried during a long prefill, it tells a link parked
* below its maximum from one at rest. */
std::function<std::string()> diagnostics_json;
/* RUNTIME LoRA (Engine::lora_acquire): a request's `model` naming a loaded adapter gets that
/* Runtime LoRA (Engine::lora_acquire): a request's `model` naming a loaded adapter gets that
* adapter's slot, load uid and a hold on it. Unset with LoRA off, and then any `model` is
* served by the base. `lora_names` lists the adapters a request may name (not the draining
* ones). */
@@ -183,6 +195,8 @@ private:
struct Generation;
struct TranscriptionJob; /* speech.cpp */
struct RealtimeSession; /* realtime.cpp */
struct SpeechSession; /* speech_stream.cpp */
struct VideoJob; /* videos.cpp */
struct StreamState;
static UsageOut usage_of(const OaiRequest& r, const std::vector<Generation>& gens);
@@ -226,6 +240,37 @@ private:
/* ------------------------------------------------------------------ images.cpp */
HttpResponse handle_images(const HttpRequest& req, bool edit);
/* ------------------------------------------------------------------ audio_gen.cpp */
HttpResponse handle_speech(const HttpRequest& req);
/* The audio a speech request describes, `text` its input, as the generator's request; -1 with
* `err` naming the field. Shared by the route and the realtime session. */
int speech_request(const json& body, const std::string& text,
std::unique_ptr<gen::AudioRequest>* out, ApiError* err);
HttpResponse stream_speech(std::shared_ptr<gen::AudioTicket> ticket, const AudioGenInfo& info,
int64_t n_tok, uint64_t seed, bool sse, bool wav);
/* ------------------------------------------------------------------ videos.cpp
* OpenAI's video jobs: created by POST, made in the background, polled and downloaded. */
HttpResponse handle_video_create(const HttpRequest& req);
HttpResponse handle_video_list(const HttpRequest& req);
HttpResponse handle_video_get(const HttpRequest& req);
HttpResponse handle_video_delete(const HttpRequest& req);
HttpResponse handle_video_content(const HttpRequest& req);
/* A job's thread: the ticket's events into progress and an MP4 file. */
void video_work(std::shared_ptr<VideoJob> j);
/* Drops expired and surplus finished jobs; under videos_m_. */
void sweep_videos_locked(int64_t now);
/* Cancels every job and joins its thread; at stop(). */
void stop_videos();
static json video_json(const VideoJob& j);
/* ------------------------------------------------------------------ speech_stream.cpp */
/* vLLM-Omni's realtime speech session over a WebSocket at /v1/audio/speech/stream: text
* streamed in, each sentence's audio streamed out as soon as the sentence is complete. */
void handle_speech_stream(const HttpRequest& req, WsConn& ws);
void speech_stream_run(SpeechSession& s, WsConn& ws);
bool speech_stream_loop(SpeechSession& s, WsConn& ws);
/* ------------------------------------------------------------------ admin.cpp
* vLLM's non-generation surface, answered on the HTTP thread without the step path, the
* admission queue or a Sink. */
@@ -303,6 +348,7 @@ private:
std::atomic<int64_t> in_flight_{0};
int64_t queue_depth_ = 0;
std::atomic<int64_t> realtime_sessions_{0};
std::atomic<int64_t> speech_sessions_{0};
std::atomic<bool> stopping_{false};
int64_t started_at_ = 0;
@@ -311,6 +357,12 @@ private:
* it under a running step is a use-after-free. */
std::mutex grave_m_;
std::vector<std::shared_ptr<Sink>> grave_;
/* The video jobs, oldest first, and the threads that make them (videos.cpp); deleted jobs
* wait in `videos_gone_` until their threads are done. */
std::mutex videos_m_;
std::vector<std::shared_ptr<VideoJob>> videos_;
std::vector<std::shared_ptr<VideoJob>> videos_gone_;
};
} /* namespace server */
+6
View File
@@ -86,5 +86,11 @@ size_t speech_transcript_start(const SpeechFormat& f, const std::string& text, b
* between words when there is a pause to cut in. */
int64_t speech_quiet_point(const std::vector<float>& x, int64_t lo, int64_t hi, int32_t rate);
/* ---- audio_gen.cpp: what the audio generator's routes write */
/* Samples in [-1, 1] as 16-bit little-endian PCM, appended. */
void append_pcm16(const std::vector<float>& x, std::string* out);
/* A RIFF/WAVE header for `bytes` of 16-bit PCM; -1 states no length, as a stream's must. */
std::string wav_header(int64_t bytes, int64_t rate, int64_t channels);
} /* namespace server */
} /* namespace rad */
+452
View File
@@ -0,0 +1,452 @@
/* speech_stream.cpp -- vLLM-Omni's realtime speech session, over a WebSocket at
* /v1/audio/speech/stream.
*
* The POST route (audio_gen.cpp) speaks a text it is given whole. This one is sent the text as it
* is produced, a language model's reply token by token or a typist's keystrokes, and speaks each
* sentence as soon as it is complete: the first audio waits for the first sentence, not the text.
*
* Protocol: vLLM-Omni's, in its buffered text mode. The client sends `session.config` first (the
* POST route's fields but `input`, and `response_format` pcm or wav, `stream_audio`,
* `split_granularity` none / sentence / clause, `text_input_mode` buffered), then `input.text`
* {text} pieces, `input.done` to end an utterance, and `session.close`. The server answers each
* sentence with `audio.start` {utterance_index, sentence_index, sentence_text, format,
* sample_rate, channels}, its audio as binary messages of 16-bit little-endian PCM (one with
* `stream_audio` false; several, as the vocoder plays it, with it true; a wav begins with a header
* that states its length, or none while it streams), and `audio.done` {utterance_index,
* sentence_index, total_bytes, error}; once an utterance's last sentence is spoken,
* `session.done` {utterance_index, total_sentences}. The session stays open for the next
* utterance until `session.close` or the socket's close. A refusal or failure is `error`
* {message, param}; the session goes on.
*
* A sentence is one request, built from the session's fields as the POST route builds one
* (Server::speech_request), and the sentences of a session are spoken one at a time in order.
*
* Threads: the connection's thread reads messages and queues them. The session's thread does
* everything else, so the session's state has one owner and its messages go out in the order they
* happen.
*/
#include "server.h"
#include "server_priv.h"
#include "text_split.h"
#include "gen/audio.h"
#include "rad_internal.h"
#include <nlohmann/json.hpp>
#include <algorithm>
#include <chrono>
#include <condition_variable>
#include <deque>
#include <map>
#include <mutex>
#include <thread>
namespace rad {
namespace server {
namespace {
using ojson = nlohmann::ordered_json;
/* The client messages a session may have queued and not yet taken in. */
constexpr size_t kMaxQueuedBytes = 16u << 20;
/* An utterance's text not yet spoken: a client that never ends a sentence is refused past it. */
constexpr size_t kMaxPendingBytes = 128u << 10;
ojson event(const char* type) {
ojson o;
o["type"] = type;
return o;
}
/* The fields that shape the session rather than each sentence's request. */
bool session_field(const std::string& k) {
return k == "type" || k == "stream_audio" || k == "split_granularity" ||
k == "text_input_mode" || k == "response_format";
}
} /* namespace */
struct Server::SpeechSession {
std::string id;
std::string peer;
/* The connection's thread to the session's: messages, and whether the peer is gone. */
std::mutex m;
std::condition_variable cv;
std::deque<std::pair<std::string, bool>> inbox; /* (message, binary) */
size_t inbox_bytes = 0;
bool peer_gone = false;
bool overflow = false;
/* Everything below is the session thread's alone. */
bool configured = false;
json fields = json::object(); /* every sentence's request, but its input */
bool stream_audio = false;
bool wav = false;
TextSplit split = TextSplit::Sentence;
std::string pending; /* the utterance's text not yet a sentence */
std::deque<std::string> sentences; /* complete, not yet spoken */
bool done_asked = false; /* input.done: the utterance ends once spoken */
int64_t utterance = 0;
int64_t sentence = 0; /* the utterance's next sentence index */
int64_t spoken = 0; /* sentences over the session's life */
/* The sentence being spoken. */
struct Current {
bool active = false;
std::shared_ptr<gen::AudioTicket> ticket;
int64_t index = 0;
std::map<int32_t, std::vector<float>> held; /* chunks ahead of the next one */
int32_t next = 0;
std::string pcm; /* the whole sentence, when it is sent at once */
int64_t bytes = 0; /* binary bytes sent for it */
} cur;
};
/* ------------------------------------------------------------------ the connection's thread */
void Server::handle_speech_stream(const HttpRequest& req, WsConn& ws) {
auto refuse = [&](const std::string& why, int close_code, const char* reason) {
ojson o = event("error");
o["message"] = why;
ws.send(json_dump(o));
RAD_INFO("speech stream refused from %s: %s", req.peer.c_str(), why.c_str());
ws.close(close_code, reason);
};
if (stopping_.load()) return refuse("the server is shutting down", 1001, "shutting down");
if (!deps_.audio || !deps_.tok)
return refuse("/v1/audio/speech/stream requires an audio generation model; this one "
"makes none", 1008, "model not supported");
/* A session speaks one sentence at a time: more sessions than the generator has lanes would
* only queue. */
const int64_t cap = std::max<int64_t>(1, deps_.audio->info().max_lanes);
if (speech_sessions_.fetch_add(1) >= cap) {
speech_sessions_.fetch_sub(1);
return refuse(fmt("this server holds %lld speech sessions at once; try again later",
(long long)cap), 1013, "session limit");
}
struct Count {
std::atomic<int64_t>& n;
~Count() { n.fetch_sub(1); }
} count{ speech_sessions_ };
/* One admission place for the session's whole life, as the realtime transcription session
* holds one. */
if (admit(1, req.peer))
return refuse("the admission queue is full; try again later", 1013, "rate limited");
struct Place {
Server& srv;
~Place() { srv.release(1); }
} place{ *this };
SpeechSession s;
s.id = random_id("speech_");
s.peer = req.peer;
std::thread worker([this, &s, &ws] { speech_stream_run(s, ws); });
/* The session's thread ends once the peer is gone, however this one leaves. */
struct Join {
SpeechSession& s;
std::thread& t;
~Join() {
{
std::lock_guard<std::mutex> lk(s.m);
s.peer_gone = true;
}
s.cv.notify_one();
if (t.joinable()) t.join();
}
} join{ s, worker };
std::string msg;
bool binary = false;
while (ws.read(&msg, &binary)) {
std::lock_guard<std::mutex> lk(s.m);
if (s.inbox_bytes + msg.size() > kMaxQueuedBytes) {
s.overflow = true;
s.cv.notify_one();
break;
}
s.inbox_bytes += msg.size();
s.inbox.emplace_back(std::move(msg), binary);
s.cv.notify_one();
}
}
/* ------------------------------------------------------------------ the session's thread */
void Server::speech_stream_run(SpeechSession& s, WsConn& ws) {
try {
speech_stream_loop(s, ws);
} catch (const std::exception& e) {
RAD_ERR("speech stream %s failed: %s", s.id.c_str(), e.what());
ojson o = event("error");
o["message"] = std::string("the session failed: ") + e.what();
ws.send(json_dump(o));
ws.close(1011, "internal error");
}
if (s.cur.active) s.cur.ticket->cancel.store(true);
RAD_INFO("speech stream %s closed: %lld utterances, %lld sentences", s.id.c_str(),
(long long)s.utterance, (long long)s.spoken);
}
bool Server::speech_stream_loop(SpeechSession& s, WsConn& ws) {
const AudioGenInfo& info = deps_.audio->info();
auto send = [&](const ojson& o) { ws.send(json_dump(o)); };
auto error = [&](const std::string& why, const std::string& param = std::string()) {
ojson o = event("error");
o["message"] = why;
o["param"] = param.empty() ? ojson(nullptr) : ojson(param);
send(o);
};
auto binary = [&](const std::string& bytes) {
if (bytes.empty()) return;
ws.send_binary(bytes);
s.cur.bytes += (int64_t)bytes.size();
};
/* ---- session.config: checked whole, then applied whole, between utterances only */
auto configure = [&](const json& j) {
if (s.cur.active || !s.sentences.empty() || !s.pending.empty() || s.done_asked)
return error("session.config applies between utterances; this one is still being "
"spoken");
static const char* kFields[] = {
"type", "model", "instructions", "voice", "response_format", "speed", "seed",
"max_new_tokens", "duration", "num_inference_steps", "guidance_scale", "user",
"stream_audio", "split_granularity", "text_input_mode",
};
json fields = json::object();
for (auto it = j.begin(); it != j.end(); ++it) {
bool known = false;
for (const char* k : kFields) known = known || it.key() == k;
if (it.key() == "input")
return error("the text arrives in input.text messages, not in the configuration",
"input");
if (!known)
return error("'" + it.key() + "' is not a field of session.config", it.key());
if (!session_field(it.key())) fields[it.key()] = it.value();
}
if (j.contains("text_input_mode") && !j["text_input_mode"].is_null()) {
const json& m = j["text_input_mode"];
if (!m.is_string() || (m != "buffered" && m != "commitment"))
return error("text_input_mode is buffered", "text_input_mode");
if (m == "commitment")
return error("text_input_mode commitment is not served here; buffered is",
"text_input_mode");
}
TextSplit split = TextSplit::Sentence;
if (j.contains("split_granularity") && !j["split_granularity"].is_null()) {
const json& g = j["split_granularity"];
if (g == "none") split = TextSplit::None;
else if (g == "clause") split = TextSplit::Clause;
else if (g != "sentence")
return error("split_granularity is none, sentence or clause", "split_granularity");
}
bool stream_audio = false;
if (j.contains("stream_audio") && !j["stream_audio"].is_null()) {
if (!j["stream_audio"].is_boolean())
return error("stream_audio is a boolean", "stream_audio");
stream_audio = j["stream_audio"].get<bool>();
}
bool wav = false;
if (j.contains("response_format") && !j["response_format"].is_null()) {
const json& f = j["response_format"];
if (f != "pcm" && f != "wav")
return error("response_format is pcm or wav", "response_format");
wav = f == "wav";
}
/* The request fields as every sentence will be made with them, tried on a stand-in. */
std::unique_ptr<gen::AudioRequest> probe;
ApiError err;
if (speech_request(fields, "a", &probe, &err) < 0) return error(err.message, err.param);
s.fields = std::move(fields);
s.split = split;
s.stream_audio = stream_audio;
s.wav = wav;
s.configured = true;
};
auto take = [&](bool final) {
for (std::string& u : take_text_units(&s.pending, s.split, final))
s.sentences.push_back(std::move(u));
};
/* Returns true when the session is over. */
auto handle = [&](const std::string& msg, bool bin) -> bool {
if (bin) {
error("this session takes JSON messages: session.config, input.text, input.done and "
"session.close");
return false;
}
const json j = json::parse(msg, nullptr, /*allow_exceptions=*/false);
if (j.is_discarded() || !j.is_object() || !j.contains("type") || !j["type"].is_string()) {
error("a client message is a JSON object with a string `type`");
return false;
}
const std::string type = j["type"].get<std::string>();
if (type == "session.config") {
configure(j);
return false;
}
if (type == "session.close") {
ws.close(1000, "session closed");
return true;
}
if (type != "input.text" && type != "input.done") {
error("this session takes session.config, input.text, input.done and session.close; "
"not '" + type + "'", "type");
return false;
}
if (!s.configured) {
error("send session.config before any text");
return false;
}
if (type == "input.done") {
take(true);
s.done_asked = true;
return false;
}
if (!j.contains("text") || !j["text"].is_string()) {
error("input.text carries `text`, a string", "text");
return false;
}
const std::string& t = j["text"].get_ref<const std::string&>();
if (s.pending.size() + t.size() > kMaxPendingBytes) {
error(fmt("the utterance holds more than %zu KiB of text without a sentence's end; "
"this piece was dropped", kMaxPendingBytes >> 10), "text");
return false;
}
s.pending += t;
take(false);
return false;
};
/* ---- a sentence: begun, its chunks sent as they come in order, and ended */
auto done = [&](bool failed) {
ojson o = event("audio.done");
o["utterance_index"] = s.utterance;
o["sentence_index"] = s.cur.index;
o["total_bytes"] = s.cur.bytes;
o["error"] = failed;
send(o);
s.cur = SpeechSession::Current{};
++s.spoken;
};
auto begin = [&]() {
const std::string text = std::move(s.sentences.front());
s.sentences.pop_front();
s.cur = SpeechSession::Current{};
s.cur.index = s.sentence++;
ojson o = event("audio.start");
o["utterance_index"] = s.utterance;
o["sentence_index"] = s.cur.index;
o["sentence_text"] = text;
o["format"] = s.wav ? "wav" : "pcm";
o["sample_rate"] = info.sample_rate;
o["channels"] = info.channels;
send(o);
std::unique_ptr<gen::AudioRequest> r;
ApiError err;
if (speech_request(s.fields, text, &r, &err) < 0) {
error(err.message, err.param);
return done(true);
}
r->ticket = std::make_shared<gen::AudioTicket>();
std::shared_ptr<gen::AudioTicket> ticket = r->ticket;
std::string why;
const int st = deps_.audio->submit(std::move(r), &why);
if (st < 0) {
error(why.empty() ? std::string(rad_strerror(st)) : why);
return done(true);
}
s.cur.active = true;
s.cur.ticket = std::move(ticket);
if (s.stream_audio && s.wav) binary(wav_header(-1, info.sample_rate, info.channels));
};
auto poll = [&](int wait_ms) {
gen::AudioChunk c;
bool to = false;
for (int ms = wait_ms;; ms = 0) {
if (s.cur.ticket->next(&c, ms, &to)) {
s.cur.held[c.window] = std::move(c.samples);
std::string pcm;
for (auto it = s.cur.held.find(s.cur.next); it != s.cur.held.end();
it = s.cur.held.find(s.cur.next)) {
append_pcm16(it->second, &pcm);
s.cur.held.erase(it);
++s.cur.next;
}
if (s.stream_audio) binary(pcm);
else s.cur.pcm += pcm;
continue;
}
if (to) return;
/* The sentence has ended. */
gen::AudioTicket& t = *s.cur.ticket;
if (t.status() < 0 || s.cur.next == 0) {
error(t.why().empty() ? "the audio generator failed" : t.why());
return done(true);
}
if (!s.stream_audio) {
const std::string& pcm = s.cur.pcm;
binary(s.wav ? wav_header((int64_t)pcm.size(), info.sample_rate, info.channels) +
pcm
: pcm);
}
return done(false);
}
};
/* ---- the loop */
RAD_INFO("speech stream %s open from %s", s.id.c_str(), s.peer.c_str());
for (;;) {
std::deque<std::pair<std::string, bool>> got;
bool gone = false, overflow = false;
{
std::unique_lock<std::mutex> lk(s.m);
const bool work = s.cur.active || !s.sentences.empty() || s.done_asked;
if (s.inbox.empty() && !s.peer_gone && !s.overflow && !work)
s.cv.wait_for(lk, std::chrono::milliseconds(100));
got.swap(s.inbox);
s.inbox_bytes = 0;
gone = s.peer_gone;
overflow = s.overflow;
}
if (overflow) {
error(fmt("the session fell more than %zu MiB of messages behind",
kMaxQueuedBytes >> 20));
ws.close(1008, "buffer overflow");
return true;
}
for (const auto& m : got)
if (handle(m.first, m.second)) return true;
if (gone) return false;
if (stopping_.load()) {
error("the server is shutting down");
ws.close(1001, "closing");
return true;
}
if (!s.cur.active && !s.sentences.empty()) begin();
if (s.cur.active) {
bool idle;
{
std::lock_guard<std::mutex> lk(s.m);
idle = s.inbox.empty() && !s.peer_gone;
}
poll(idle ? 10 : 0);
}
if (!s.cur.active && s.sentences.empty() && s.done_asked) {
ojson o = event("session.done");
o["utterance_index"] = s.utterance;
o["total_sentences"] = s.sentence;
send(o);
++s.utterance;
s.sentence = 0;
s.done_asked = false;
}
}
}
} /* namespace server */
} /* namespace rad */
+195
View File
@@ -0,0 +1,195 @@
/* text_split.cpp -- sentence and clause units of text that arrives in pieces (text_split.h). */
#include "text_split.h"
#include <cctype>
#include <cstdint>
namespace rad {
namespace server {
namespace {
/* The code point at `i` and its length in bytes; a byte that starts no valid sequence is read as
* itself, one byte long, so malformed text still advances. */
uint32_t cp_at(const std::string& s, size_t i, size_t* len) {
const unsigned char c = (unsigned char)s[i];
auto cont = [&](size_t k) {
return i + k < s.size() && ((unsigned char)s[i + k] & 0xC0) == 0x80;
};
if (c < 0x80) { *len = 1; return c; }
if ((c & 0xE0) == 0xC0 && cont(1)) {
*len = 2;
return ((uint32_t)(c & 0x1F) << 6) | ((unsigned char)s[i + 1] & 0x3F);
}
if ((c & 0xF0) == 0xE0 && cont(1) && cont(2)) {
*len = 3;
return ((uint32_t)(c & 0x0F) << 12) | ((uint32_t)((unsigned char)s[i + 1] & 0x3F) << 6) |
((unsigned char)s[i + 2] & 0x3F);
}
if ((c & 0xF8) == 0xF0 && cont(1) && cont(2) && cont(3)) {
*len = 4;
return ((uint32_t)(c & 0x07) << 18) | ((uint32_t)((unsigned char)s[i + 1] & 0x3F) << 12) |
((uint32_t)((unsigned char)s[i + 2] & 0x3F) << 6) | ((unsigned char)s[i + 3] & 0x3F);
}
*len = 1;
return c;
}
bool ends_sentence(uint32_t c) {
switch (c) {
case '.': case '!': case '?':
case 0x3002: /* 。 */
case 0xFF01: /* ! */
case 0xFF1F: /* ? */
case 0xFF0E: /* . */
case 0x2026: /* … */
case 0x0964: /* । */
case 0x0965: /* ॥ */
case 0x061F: /* ؟ */
return true;
default:
return false;
}
}
bool ends_clause(uint32_t c) {
switch (c) {
case ',': case ';':
case 0xFF0C: /* , */
case 0xFF1B: /* ; */
case 0x060C: /* ، */
case 0x061B: /* ؛ */
return true;
default:
return false;
}
}
/* What may follow a unit's closing punctuation and still belong to it. */
bool closes(uint32_t c) {
switch (c) {
case ')': case ']': case '}': case '"': case '\'':
case 0x201D: case 0x2019: case 0x00BB: /* ” ’ » */
case 0x300D: case 0x300F: case 0xFF09: case 0x3011: /* 」 』 ) 】 */
case 0x300B: case 0x3009: case 0x3015: case 0xFF3D: /* 》 〉 〕 ] */
case 0xFF5D: /* } */
return true;
default:
return false;
}
}
bool space_cp(uint32_t c) {
return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' || c == '\v' ||
c == 0x00A0 || c == 0x3000;
}
/* A full stop that ends no sentence: one closing a common abbreviation or an initial. `word` is
* the text from the last whitespace to the stop, the stop included. */
bool no_stop(std::string word) {
while (!word.empty() && (word[0] == '(' || word[0] == '"' || word[0] == '\'' ||
word[0] == '['))
word.erase(0, 1);
std::string low;
for (char ch : word) low += (char)std::tolower((unsigned char)ch);
static const char* const kAbbrev[] = {
"mr.", "mrs.", "ms.", "dr.", "prof.", "sr.", "jr.", "st.", "mt.", "vs.", "etc.", "e.g.",
"i.e.", "inc.", "ltd.", "co.", "no.", "fig.", "approx.", "dept.", "est.",
};
for (const char* a : kAbbrev)
if (low == a) return true;
/* An initial or a run of them: "J." or "J.R.", each an upper-case letter and a stop. */
if (word.size() >= 2 && word.size() % 2 == 0 && std::isupper((unsigned char)word[0])) {
bool initials = true;
for (size_t k = 0; k < word.size(); k += 2)
initials = initials && std::isalpha((unsigned char)word[k]) && word[k + 1] == '.';
if (initials) return true;
}
return false;
}
std::string trim(const std::string& s, size_t a, size_t b) {
while (a < b) {
size_t n = 1;
if (!space_cp(cp_at(s, a, &n))) break;
a += n;
}
while (b > a && std::isspace((unsigned char)s[b - 1])) --b;
return s.substr(a, b - a);
}
/* Whether a unit carries anything to say: some character that is no punctuation or space. */
bool says_something(const std::string& u) {
for (size_t i = 0; i < u.size();) {
size_t n = 1;
const uint32_t c = cp_at(u, i, &n);
i += n;
if (space_cp(c) || ends_sentence(c) || ends_clause(c) || closes(c)) continue;
if (c < 0x80 && std::ispunct((int)c)) continue;
return true;
}
return false;
}
} /* namespace */
std::vector<std::string> take_text_units(std::string* pending, TextSplit mode, bool final) {
std::vector<std::string> out;
std::string& s = *pending;
auto push = [&](std::string u) {
if (says_something(u)) out.push_back(std::move(u));
};
size_t start = 0;
if (mode != TextSplit::None) {
size_t i = 0;
while (i < s.size()) {
size_t n = 1;
const uint32_t c = cp_at(s, i, &n);
const bool term = ends_sentence(c) || (mode == TextSplit::Clause && ends_clause(c));
if (!term) { i += n; continue; }
/* The punctuation run: further stops and closing quotes or brackets. */
size_t j = i + n;
while (j < s.size()) {
size_t m = 1;
const uint32_t d = cp_at(s, j, &m);
if (!(ends_sentence(d) || ends_clause(d) || closes(d))) break;
j += m;
}
if (j == s.size()) {
/* Whether the unit ended shows only in what comes next. */
if (!final) break;
i = j;
continue;
}
size_t m = 1;
const uint32_t next = cp_at(s, j, &m);
const bool ascii = c < 0x80;
bool boundary = ascii ? space_cp(next) : true;
if (boundary && c == '.') {
size_t w = i;
while (w > start && !std::isspace((unsigned char)s[w - 1])) --w;
boundary = !no_stop(s.substr(w, i + 1 - w));
}
if (!boundary) { i = j; continue; }
push(trim(s, start, j));
/* The next unit starts at its first character. */
while (j < s.size()) {
size_t k = 1;
if (!space_cp(cp_at(s, j, &k))) break;
j += k;
}
start = j;
i = j;
}
}
if (final) {
push(trim(s, start, s.size()));
s.clear();
} else {
s.erase(0, start);
}
return out;
}
} /* namespace server */
} /* namespace rad */
+35
View File
@@ -0,0 +1,35 @@
/* text_split.h -- text that arrives in pieces, cut into the units a speech model reads one at a
* time: sentences, or clauses (text_split.cpp).
*
* The realtime speech session (speech_stream.cpp) is sent text as a client produces it, a language
* model's tokens or a typist's keystrokes, and speaks each unit as soon as it is complete, so the
* first audio does not wait for the whole text. A unit is complete once the text after its closing
* punctuation shows that it ended; the end of the input ends the last one.
*/
#pragma once
#include <string>
#include <vector>
namespace rad {
namespace server {
enum class TextSplit {
None, /* no cutting: the whole input is one unit */
Sentence, /* after . ! ? and their CJK, Indic and Arabic forms */
Clause, /* also after , ; and their full-width and Arabic forms */
};
/* The complete units at the front of `*pending`, trimmed, in order; `*pending` keeps the rest.
* With `final` (the input has ended) the rest is a unit too and `*pending` is left empty.
*
* A unit ends at its closing punctuation together with any run of punctuation and closing quotes
* or brackets after it ("Really?!", "he said.”"). After ASCII punctuation the end needs
* whitespace to follow, so "3.14" and "a.b" do not end one; after full-width, CJK, Indic or Arabic
* punctuation any next character does, since those scripts put no space there. A full stop after a
* common abbreviation (Dr., Mr., e.g., etc.) or an initial (J., J.R.) ends nothing. A unit with
* nothing to say (only punctuation) is dropped. */
std::vector<std::string> take_text_units(std::string* pending, TextSplit mode, bool final);
} /* namespace server */
} /* namespace rad */
+621
View File
@@ -0,0 +1,621 @@
/* videos.cpp -- OpenAI's video endpoints over a video generator (core/gen/video_driver.h): a video
* and its soundtrack from a prompt.
*
* A video takes minutes, so it is a job, as OpenAI's API has it: POST /v1/videos queues one and
* answers with the video object at once, GET /v1/videos/{id} reports its status and progress, and
* GET /v1/videos/{id}/content downloads the MP4 once it is completed (`variant` thumbnail gives
* the first frame as WebP). GET /v1/videos lists the jobs, newest first, and DELETE removes one,
* cancelling it when it is still running. A finished video is kept for `video_ttl_s` seconds
* (`expires_at`), at most `max_videos` of them.
*
* The request takes OpenAI's fields (`prompt`, `model`, `seconds`, `size`) as JSON or as a
* multipart form, and SGLang's for the same model: `task` (t2va), `target` {`short_edge`,
* `aspect_ratio`, `duration_seconds`}, `conditions` (empty), `seed`, and `num_inference_steps`.
* `size` is the frame's width x height, multiples of the model's size multiple; `aspect_ratio`
* (`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.
*
* The prompt is the model's template with `{prompt}` filled; the template is tokenised with its
* special tokens and the prompt without, so a caller cannot write control tokens into it.
*/
#include "server.h"
#include "oai.h"
#include "gen/video.h"
#include "mm/media.h"
#include "mm/mp4.h"
#include "rad_internal.h"
#include <nlohmann/json.hpp>
#include <algorithm>
#include <chrono>
#include <cmath>
#include <ctime>
#include <random>
#include <thread>
namespace rad {
namespace server {
struct Server::VideoJob {
std::string id, model, prompt, seconds, size;
int64_t created_at = 0;
uint64_t seed = 0;
std::shared_ptr<gen::VideoTicket> ticket;
std::thread worker;
/* Under Server::videos_m_ from here on. */
std::string status = "queued";
int progress = 0;
int64_t completed_at = 0, expires_at = 0;
bool failed = false;
std::string err_code, err_message;
std::string mp4;
std::vector<uint8_t> first; /* the first frame, RGB, for the thumbnail */
int32_t w = 0, h = 0;
bool worker_done = false; /* its thread has nothing left to do but return */
};
namespace {
std::string new_video_id() {
static const char* hex = "0123456789abcdef";
std::random_device rd;
std::string id = "video_";
for (int i = 0; i < 32; ++i) id.push_back(hex[rd() & 15]);
return id;
}
/* "1344x768" -> (1344, 768); false for anything else. */
bool parse_size(const std::string& s, int64_t* w, int64_t* h) {
const size_t x = s.find_first_of("xX");
if (x == std::string::npos || x == 0 || x + 1 >= s.size()) return false;
char* e = nullptr;
*w = std::strtoll(s.c_str(), &e, 10);
if (e != s.c_str() + x) return false;
*h = std::strtoll(s.c_str() + x + 1, &e, 10);
return *e == '\0' && *w > 0 && *h > 0;
}
/* "16:9" -> 16/9 as two positives; false for anything else. */
bool parse_ratio(const std::string& s, double* a, double* b) {
const size_t c = s.find(':');
if (c == std::string::npos) return false;
char* e = nullptr;
*a = std::strtod(s.c_str(), &e);
if (e != s.c_str() + c) return false;
*b = std::strtod(s.c_str() + c + 1, &e);
return *e == '\0' && *a > 0 && *b > 0;
}
/* The model's canvas for a ratio: the short edge, the area capped, both sides rounded to the
* multiple (ties to even, as the reference's float round). */
void canvas_for(double rw, double rh, int64_t short_edge, int64_t max_area, int64_t mult,
int64_t* w, int64_t* h) {
const double ratio = rw / rh;
double W = ratio >= 1.0 ? short_edge * ratio : (double)short_edge;
double H = ratio >= 1.0 ? (double)short_edge : short_edge / ratio;
if (W * H > (double)max_area) {
const double sc = std::sqrt((double)max_area / (W * H));
W *= sc;
H *= sc;
}
*w = std::max<int64_t>(mult, (int64_t)std::nearbyint(W / mult) * mult);
*h = std::max<int64_t>(mult, (int64_t)std::nearbyint(H / mult) * mult);
}
} /* namespace */
HttpResponse Server::handle_video_create(const HttpRequest& req) {
if (!deps_.videos || !deps_.tok)
return error_response(err_not_implemented(
"/v1/videos requires a video generation model; this one does not make video"),
req.peer);
const VideoGenInfo& info = deps_.videos->info();
/* 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();
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.filename.empty())
return error_response(err_bad(p.name, "'" + p.name + "' takes text, not a file"),
req.peer);
json v = p.data;
if (p.name == "target" || p.name == "conditions") {
v = json::parse(p.data, nullptr, false);
if (v.is_discarded())
return error_response(err_bad(p.name, "expected JSON"), req.peer);
}
body[p.name] = v;
}
} else {
ApiError err;
if (parse_request_object(req.body, lim_, &body, &err) < 0)
return error_response(err, req.peer);
}
static const char* kKnown[] = {
"model", "prompt", "seconds", "size", "input_reference", "seed", "num_inference_steps",
"task", "target", "conditions", "user",
};
for (auto it = body.begin(); it != body.end(); ++it) {
bool known = false;
for (const char* k : kKnown) known = known || it.key() == k;
if (!known)
return error_response(err_bad(it.key(), "'" + it.key() + "' is not a field of "
"/v1/videos"), req.peer);
}
auto bad = [&](const char* k, const std::string& why) { return error_response(err_bad(k, why), req.peer); };
auto has = [&](const json& o, const char* k) { return o.contains(k) && !o[k].is_null(); };
/* A number, or a string holding one (a form's fields are strings). */
auto number = [&](const json& v, double* out) {
if (v.is_number()) { *out = v.get<double>(); return true; }
if (!v.is_string()) return false;
const std::string s = v.get<std::string>();
char* e = nullptr;
*out = std::strtod(s.c_str(), &e);
return !s.empty() && *e == '\0';
};
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"))
return error_response(err_unsupported("input_reference", "this server 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" };
return error_response(e, req.peer);
}
if (has(body, "conditions") && (!body["conditions"].is_array() || !body["conditions"].empty()))
return error_response(err_unsupported("conditions", "this server makes video from text "
"only; conditions must be empty"), req.peer);
json target = json::object();
if (has(body, "target")) {
if (!body["target"].is_object()) return bad("target", "expected an object");
target = body["target"];
for (auto it = target.begin(); it != target.end(); ++it)
if (it.key() != "short_edge" && it.key() != "aspect_ratio" &&
it.key() != "duration_seconds")
return bad("target", "'" + it.key() + "' is not a field of target");
}
/* ---- the size */
int64_t W = info.default_width, H = info.default_height;
const int64_t short_def = std::min(info.default_width, info.default_height);
if (has(body, "size")) {
if (!body["size"].is_string() || !parse_size(body["size"].get<std::string>(), &W, &H))
return bad("size", "expected WIDTHxHEIGHT, e.g. " + std::to_string(info.default_width) +
"x" + std::to_string(info.default_height));
if (has(target, "aspect_ratio") || has(target, "short_edge"))
return bad("size", "give size or target's aspect_ratio and short_edge, not both");
} else if (has(target, "aspect_ratio") || has(target, "short_edge")) {
double rw = (double)info.default_width, rh = (double)info.default_height;
if (has(target, "aspect_ratio")) {
if (!target["aspect_ratio"].is_string())
return bad("target", "aspect_ratio is a string, w:h or auto");
const std::string ar = target["aspect_ratio"].get<std::string>();
if (ar != "auto" && !parse_ratio(ar, &rw, &rh))
return bad("target", "aspect_ratio must be w:h (16:9) or auto");
}
int64_t se = short_def;
if (has(target, "short_edge")) {
double v = 0;
if (!number(target["short_edge"], &v) || v < 1 || v != std::floor(v))
return bad("target", "short_edge must be a positive whole number of pixels");
se = (int64_t)v;
}
if (std::max(rw, rh) > (double)info.max_aspect * std::min(rw, rh))
return bad("target", "the aspect ratio may be at most " +
std::to_string(info.max_aspect) + ":1 either way");
canvas_for(rw, rh, se, info.max_area, info.size_multiple, &W, &H);
}
if (W % info.size_multiple || H % info.size_multiple || W < info.min_side ||
H < info.min_side || W * H > info.max_area ||
std::max(W, H) > info.max_aspect * std::min(W, H)) {
int64_t sw = 0, sh = 0;
canvas_for((double)W, (double)H, short_def, info.max_area, info.size_multiple, &sw, &sh);
return bad("size", std::to_string(W) + "x" + std::to_string(H) + " is not a size this "
"model makes: sides are multiples of " + std::to_string(info.size_multiple) +
" from " + std::to_string(info.min_side) + ", at most " +
std::to_string(info.max_area) + " pixels and " +
std::to_string(info.max_aspect) + ":1; its canvas at that ratio is " +
std::to_string(sw) + "x" + std::to_string(sh));
}
/* ---- the length, in whole chunks */
const double fps = (double)info.fps_num / (double)info.fps_den;
const double min_s = (double)(info.frames_per_chunk * info.min_chunks + info.frames_tail) / fps;
const double max_s = (double)(info.frames_per_chunk * info.max_chunks + info.frames_tail) / fps;
int64_t chunks = info.default_chunks;
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) {
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");
const int64_t want = (int64_t)std::ceil(sec * fps - 1e-9);
chunks = std::max<int64_t>(info.min_chunks,
(want - info.frames_tail + info.frames_per_chunk - 1) /
info.frames_per_chunk);
if (chunks > info.max_chunks)
return bad(has_sec ? "seconds" : "target",
"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;
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;
if (has(body, "num_inference_steps")) {
double v = 0;
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 ||
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)");
r->steps = (int32_t)v;
}
bool seed_given = false;
if (has(body, "seed")) {
double v = 0;
if (!number(body["seed"], &v) || v != std::floor(v)) return bad("seed", "expected an integer");
r->seed = (uint64_t)(int64_t)v;
seed_given = v != -1;
}
if (!seed_given) {
/* 53 bits, as the other generators choose one: JavaScript reads a number as a double. */
std::random_device rd;
r->seed = (((uint64_t)rd() << 32) ^ rd()) & (((uint64_t)1 << 53) - 1);
}
/* ---- the prompt: the template's text with special tokens, the prompt without */
{
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());
};
put(t.substr(0, p), true);
put(prompt, false);
put(t.substr(p + kSlot.size()), true);
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));
}
/* ---- admitted and queued: the job holds its place until its file is written */
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->size = std::to_string(W) + "x" + std::to_string(H);
j->created_at = unix_now();
j->seed = r->seed;
j->ticket = std::make_shared<gen::VideoTicket>();
r->ticket = j->ticket;
const int64_t n_tok = (int64_t)r->tokens.size();
const int32_t steps = r->steps;
{
std::string w;
const int s = deps_.videos->submit(std::move(r), &w);
if (s < 0) {
release(1);
ApiError e = err_bad("", w.empty() ? std::string(rad_strerror(s)) : w);
if (s != RAD_E_INVAL) { e.status = 503; e.type = "server_error"; }
return error_response(e, req.peer);
}
}
RAD_INFO("video %s: %s, %lld frames (%s s), %lld prompt tokens, %d steps, seed=%llu",
j->id.c_str(), j->size.c_str(), (long long)frames, j->seconds.c_str(),
(long long)n_tok, steps > 0 ? steps : (int)j->ticket->steps,
(unsigned long long)j->seed);
std::lock_guard<std::mutex> lk(videos_m_);
sweep_videos_locked(unix_now());
videos_.push_back(j);
j->worker = std::thread([this, j] { video_work(j); });
return HttpResponse::json_body(200, json_dump(video_json(*j)));
}
/* The job's thread. Progress is the steps' share of 90, then the frames' of the last 10. */
void Server::video_work(std::shared_ptr<VideoJob> j) {
gen::VideoTicket& t = *j->ticket;
const VideoGenInfo& info = deps_.videos->info();
mm::Mp4Writer mp4;
std::string why;
int st = mp4.open(t.width, t.height, info.fps_num, info.fps_den, t.sample_rate, t.channels,
&why);
int32_t frames = 0;
bool aborted = false;
while (st >= 0) {
gen::VideoEvent e;
bool to = false;
if (!t.next(&e, 500, &to)) {
if (!to) break;
if (stopping_.load()) {
t.cancel.store(true);
aborted = true;
break;
}
continue;
}
if (e.kind == gen::VideoEvent::STEP) {
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::AUDIO) {
if (t.channels > 0)
st = mp4.add_audio(e.samples.data(), (int64_t)e.samples.size() / t.channels, &why);
} else if (e.kind == gen::VideoEvent::FRAMES) {
if (e.first == 0 && e.n > 0) {
std::lock_guard<std::mutex> lk(videos_m_);
j->first.assign(e.rgb.begin(), e.rgb.begin() + (size_t)t.width * t.height * 3);
j->w = t.width;
j->h = t.height;
}
st = mp4.add_frames(e.rgb.data(), e.n, &why);
frames += e.n;
std::lock_guard<std::mutex> lk(videos_m_);
j->progress = 90 + (t.frames > 0 ? (int)(10LL * frames / t.frames) : 0);
}
}
if (st < 0) t.cancel.store(true);
std::string file;
if (st >= 0 && !aborted && t.status() >= 0 && frames == t.frames)
st = mp4.finish(&file, &why);
release(1);
std::lock_guard<std::mutex> lk(videos_m_);
const int64_t now = unix_now();
if (st >= 0 && !aborted && t.status() >= 0 && frames == t.frames) {
j->status = "completed";
j->progress = 100;
j->completed_at = now;
j->expires_at = now + opt_.video_ttl_s;
j->mp4 = std::move(file);
RAD_INFO("video %s: completed, %.1f MB (%s), %.1f s", j->id.c_str(),
(double)j->mp4.size() / 1e6, mp4.video_encoder().c_str(),
(double)(t.t_done_ns - t.t_submit_ns) / 1e9);
} else {
j->status = "failed";
j->failed = true;
j->completed_at = now;
if (st < 0) {
j->err_code = "encoding_failed";
j->err_message = "the video could not be written: " + why;
} else if (aborted || t.status() == RAD_E_CANCELLED) {
j->err_code = "cancelled";
j->err_message = aborted ? "the server is shutting down" : "the video was cancelled";
} else {
j->err_code = t.status() == RAD_E_INVAL ? "invalid_request" : "generation_failed";
j->err_message = t.why().empty() ? std::string(rad_strerror(t.status())) : t.why();
}
RAD_WARN("video %s: failed: %s", j->id.c_str(), j->err_message.c_str());
}
j->worker_done = true;
}
void Server::sweep_videos_locked(int64_t now) {
/* Deleted jobs whose threads are done are joined. */
for (size_t i = 0; i < videos_gone_.size();) {
if (!videos_gone_[i]->worker_done) { ++i; continue; }
if (videos_gone_[i]->worker.joinable()) videos_gone_[i]->worker.join();
videos_gone_.erase(videos_gone_.begin() + (std::ptrdiff_t)i);
}
/* Expired files go first, then the oldest finished jobs past the count. A running job is
* never dropped here: it holds an admission place and its thread. */
auto drop = [&](size_t i) {
if (videos_[i]->worker.joinable()) videos_[i]->worker.join();
videos_.erase(videos_.begin() + (std::ptrdiff_t)i);
};
for (size_t i = 0; i < videos_.size();) {
const VideoJob& j = *videos_[i];
const bool done = j.status == "completed" || j.status == "failed";
if (done && j.expires_at > 0 && j.expires_at <= now) drop(i);
else if (done && j.failed && j.completed_at + opt_.video_ttl_s <= now) drop(i);
else ++i;
}
int64_t finished = 0;
for (const auto& j : videos_) finished += j->status == "completed" || j->status == "failed";
for (size_t i = 0; i < videos_.size() && finished > opt_.max_videos;) {
const VideoJob& j = *videos_[i];
if (j.status == "completed" || j.status == "failed") {
drop(i);
--finished;
} else {
++i;
}
}
}
void Server::stop_videos() {
std::vector<std::shared_ptr<VideoJob>> all;
{
std::lock_guard<std::mutex> lk(videos_m_);
all = videos_;
all.insert(all.end(), videos_gone_.begin(), videos_gone_.end());
}
for (auto& j : all) j->ticket->cancel.store(true);
for (auto& j : all)
if (j->worker.joinable()) j->worker.join();
}
/* The video object, OpenAI's shape. */
json Server::video_json(const VideoJob& j) {
json o;
o["id"] = j.id;
o["object"] = "video";
o["model"] = j.model;
o["status"] = j.status;
o["progress"] = j.progress;
o["created_at"] = j.created_at;
o["completed_at"] = j.completed_at ? json(j.completed_at) : json(nullptr);
o["expires_at"] = j.expires_at ? json(j.expires_at) : json(nullptr);
o["prompt"] = j.prompt;
o["seconds"] = j.seconds;
o["size"] = j.size;
o["seed"] = j.seed;
o["remixed_from_video_id"] = nullptr;
if (j.failed) {
json e;
e["code"] = j.err_code;
e["message"] = j.err_message;
o["error"] = e;
} else {
o["error"] = nullptr;
}
return o;
}
HttpResponse Server::handle_video_get(const HttpRequest& req) {
if (!deps_.videos)
return error_response(err_not_implemented("/v1/videos requires a video generation model"),
req.peer);
const std::string id = req.param("id");
std::lock_guard<std::mutex> lk(videos_m_);
for (const auto& j : videos_)
if (j->id == id) return HttpResponse::json_body(200, json_dump(video_json(*j)));
ApiError e = err_bad("id", "no video '" + id + "'; it may have expired");
e.status = 404;
e.type = "not_found_error";
return error_response(e, req.peer);
}
HttpResponse Server::handle_video_list(const HttpRequest& req) {
if (!deps_.videos)
return error_response(err_not_implemented("/v1/videos requires a video generation model"),
req.peer);
int64_t limit = 20;
if (auto it = req.query.find("limit"); it != req.query.end()) {
char* e = nullptr;
limit = std::strtoll(it->second.c_str(), &e, 10);
if (*e || limit < 1 || limit > 100)
return error_response(err_bad("limit", "expected an integer in 1..100"), req.peer);
}
const auto ord = req.query.find("order");
const bool asc = ord != req.query.end() && ord->second == "asc";
if (ord != req.query.end() && ord->second != "asc" && ord->second != "desc")
return error_response(err_bad("order", "expected asc or desc"), req.peer);
const auto after = req.query.find("after");
std::lock_guard<std::mutex> lk(videos_m_);
sweep_videos_locked(unix_now());
std::vector<std::shared_ptr<VideoJob>> v = videos_;
if (!asc) std::reverse(v.begin(), v.end());
size_t at = 0;
if (after != req.query.end()) {
while (at < v.size() && v[at]->id != after->second) ++at;
if (at == v.size())
return error_response(err_bad("after", "no video '" + after->second + "'"), req.peer);
++at;
}
json data = json::array();
for (size_t i = at; i < v.size() && (int64_t)data.size() < limit; ++i)
data.push_back(video_json(*v[i]));
json o;
o["object"] = "list";
o["data"] = data;
o["first_id"] = data.empty() ? json(nullptr) : data.front()["id"];
o["last_id"] = data.empty() ? json(nullptr) : data.back()["id"];
o["has_more"] = at + data.size() < v.size();
return HttpResponse::json_body(200, json_dump(o));
}
HttpResponse Server::handle_video_delete(const HttpRequest& req) {
if (!deps_.videos)
return error_response(err_not_implemented("/v1/videos requires a video generation model"),
req.peer);
const std::string id = req.param("id");
std::lock_guard<std::mutex> lk(videos_m_);
std::shared_ptr<VideoJob> j;
for (size_t i = 0; i < videos_.size(); ++i)
if (videos_[i]->id == id) {
j = videos_[i];
videos_.erase(videos_.begin() + (std::ptrdiff_t)i);
break;
}
if (!j) {
ApiError e = err_bad("id", "no video '" + id + "'");
e.status = 404;
e.type = "not_found_error";
return error_response(e, req.peer);
}
/* A running job is cancelled, and its thread ends once the driver has seen that (at its next
* pass, which may be seconds away); it is joined then. */
j->ticket->cancel.store(true);
videos_gone_.push_back(j);
sweep_videos_locked(unix_now());
json o;
o["id"] = id;
o["object"] = "video.deleted";
o["deleted"] = true;
return HttpResponse::json_body(200, json_dump(o));
}
HttpResponse Server::handle_video_content(const HttpRequest& req) {
if (!deps_.videos)
return error_response(err_not_implemented("/v1/videos requires a video generation model"),
req.peer);
const std::string id = req.param("id");
std::string variant = "video";
if (auto it = req.query.find("variant"); it != req.query.end()) variant = it->second;
if (variant != "video" && variant != "thumbnail") {
ApiError e = err_unsupported("variant", "this server gives the video or its thumbnail");
e.supported = { "video", "thumbnail" };
return error_response(e, req.peer);
}
std::lock_guard<std::mutex> lk(videos_m_);
for (const auto& j : videos_) {
if (j->id != id) continue;
if (variant == "thumbnail") {
if (j->first.empty())
return error_response(err_bad("id", "video '" + id + "' has no frames yet"),
req.peer);
std::vector<uint8_t> file;
std::string why;
if (mm::encode_image(j->first.data(), j->w, j->h, 3, "webp", 90, &file, &why) < 0)
return error_response(err_internal("the thumbnail could not be encoded: " + why),
req.peer);
HttpResponse res;
res.content_type = "image/webp";
res.body.assign((const char*)file.data(), file.size());
return res;
}
if (j->status != "completed")
return error_response(err_bad("id", "video '" + id + "' is " + j->status +
(j->failed ? ": " + j->err_message : "")),
req.peer);
HttpResponse res;
res.content_type = "video/mp4";
res.body = j->mp4;
return res;
}
ApiError e = err_bad("id", "no video '" + id + "'; it may have expired");
e.status = 404;
e.type = "not_found_error";
return error_response(e, req.peer);
}
} /* namespace server */
} /* namespace rad */