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 -6
View File
@@ -127,6 +127,8 @@ public:
int drafter_shared_kv(int pos_offset);
int declare_encoder(const RadEncoderDecl* d);
int declare_generator(const RadGeneratorDecl* d);
int declare_audio_generator(const RadAudioGenDecl* d);
int declare_video_generator(const RadVideoGenDecl* d);
void note_v (const char* f, va_list ap);
/* An op's buffer operands (rad_op_reads/rad_op_writes in rad_builder.h), which give the
@@ -159,13 +161,13 @@ public:
* an io_uring ring, which must not stop a sandboxed conversion. */
void set_instances(bool on) { instances_ = on; }
/* RUNTIME LoRA (core/lora/): the HF module leaves an adapter may target. Set before the
* plugin declares, so a FUSED GEMM over a targeted weight -- a GEMM no adapter delta can ride
* on, the gated gate_up fold -- is declined as it is declared and the plugin emits the unfused
* chain it already has for a library without the fused kernel. Null: nothing is declined. */
/* Runtime LoRA (core/lora/): the HF module leaves an adapter may target. Set before the plugin
* declares, so a fused GEMM over a targeted weight (the gated gate_up fold), which leaves no
* output for the delta, is declined as it is declared and the plugin emits the unfused chain it
* has for a library without the fused kernel. Null: nothing is declined. */
void set_lora_targets(const std::set<std::string>* t) { lora_targets_ = t; }
/* The read and write sets an op declared (rad_op_reads / rad_op_writes), for the LoRA declare,
* which needs the dtypes of the activation and the output a targeted GEMM was declared over. */
/* The read and write sets an op declared (rad_op_reads / rad_op_writes): the LoRA declare reads
* the dtypes of a targeted GEMM's activation and output from them. */
const std::vector<rad_buf>& op_read_set (rad_op h) const { return op_bufs_[h].reads; }
const std::vector<rad_buf>& op_write_set(rad_op h) const { return op_bufs_[h].writes; }
+331 -21
View File
@@ -703,12 +703,12 @@ rad_op Builder::decl_op(const char* opname, const RadParam* p, int n_p,
}
}
/* RUNTIME LoRA: A FUSED GEMM OVER A TARGETED WEIGHT IS DECLINED. Every `gemm_*` op other than
* the four an adapter delta can follow (lora::op_is_site) fuses something into its epilogue --
* the gated fold quantises the SiLU product in place -- so the delta has no y to land in. The
* op is recorded resolved to nothing, exactly as a library without the kernel would leave it,
* and the plugin falls back to the unfused chain it emits for that library. The decision reads
* only the weight's own declaration and name map, so the sizing declare makes the same one. */
/* Runtime LoRA: a fused GEMM over a targeted weight is declined. Every `gemm_*` op other than
* the four an adapter delta can follow (lora::op_is_site) fuses something into its epilogue
* (the gated fold quantises the SiLU product in place), so the delta has no y to land in. The
* op is recorded unresolved, as a library without the kernel would leave it, and the plugin
* runs its unfused chain. The decision reads only the weight's own declaration and name map,
* so the sizing declare makes the same one. */
bool lora_declined = false;
if (lora_targets_ && n_w > 0 && oi.op.rfind("gemm_", 0) == 0 && oi.op != "gemm_nt" &&
oi.op != "gemm_nt_bias" && oi.op != "gemm_nt_q" && oi.op != "gemm_nt_q_bias") {
@@ -726,10 +726,10 @@ rad_op Builder::decl_op(const char* opname, const RadParam* p, int n_p,
"output for the adapter's delta (the plugin runs the unfused chain)";
oi.bands.assign(1, none);
oi.lora_declined = true;
/* AND IT OWNS NO WEIGHT. The planner, the layout pass and the weight-use bookkeeping all
* read an op's weights, and an op with no kernel anywhere would tell the planner the weight
* cannot be read on the card -- moving the gate_up the unfused chain multiplies on the card
* off it. The op stays in the list, by name, so the sizing declare lines up. */
/* It owns no weight: the planner reads an op's weights, and an op with no kernel anywhere
* would tell it the weight cannot be read on the card, moving the gate_up the unfused
* chain multiplies off the card. The op stays in the list by name so the sizing declare
* lines up. */
oi.weights.clear();
oi.weight_opd.clear();
prog_.ops.push_back(std::move(oi));
@@ -939,10 +939,23 @@ int Builder::decl_name_map(const RadNameMap* m) {
err(RAD_E_INVAL, "name map for '%s': %d source tensors, 1..8 allowed", m->declared, m->n_src);
return RAD_E_INVAL;
}
if (m->mode != RAD_MAP_COPY && m->mode != RAD_MAP_CONCAT) {
if (m->mode != RAD_MAP_COPY && m->mode != RAD_MAP_CONCAT && m->mode != RAD_MAP_WNORM &&
m->mode != RAD_MAP_ROWS && m->mode != RAD_MAP_TRANSPOSE && m->mode != RAD_MAP_EMA) {
err(RAD_E_INVAL, "name map for '%s': unknown mode %d", m->declared, m->mode);
return RAD_E_INVAL;
}
if ((m->mode == RAD_MAP_WNORM || m->mode == RAD_MAP_EMA) && m->n_src != 2) {
err(RAD_E_INVAL, "name map for '%s': a %s map names two sources (%s), not %d",
m->declared, m->mode == RAD_MAP_EMA ? "codebook" : "weight-norm",
m->mode == RAD_MAP_EMA ? "the embedding sums and the cluster usage"
: "the magnitude and the direction", m->n_src);
return RAD_E_INVAL;
}
if (m->mode == RAD_MAP_TRANSPOSE && m->n_src != 1) {
err(RAD_E_INVAL, "name map for '%s': a transpose map names one source, not %d",
m->declared, m->n_src);
return RAD_E_INVAL;
}
RadNameMap c{};
c.declared = intern(scoped(m->declared));
@@ -961,6 +974,14 @@ int Builder::decl_name_map(const RadNameMap* m) {
* also map_base() in arch/common/rad_arch.h), so every map would ask for slice 0. */
for (int i = 0; i < m->n_src; ++i) c.src_index[i] = m->src_index[i];
for (int i = m->n_src; i < 8; ++i) c.src_index[i] = -1;
for (int i = 0; i < 8; ++i) c.src_rows[i] = i < m->n_src ? m->src_rows[i] : 0;
if (m->mode == RAD_MAP_ROWS)
for (int i = 0; i < m->n_src; ++i)
if (m->src_index[i] < 0 || m->src_rows[i] <= 0) {
err(RAD_E_INVAL, "name map for '%s': row piece %d starts at %d and holds %lld rows",
m->declared, i, m->src_index[i], (long long)m->src_rows[i]);
return RAD_E_INVAL;
}
/* A CONCAT map may be declared in pieces; any other repeat is an error.
*
@@ -975,10 +996,12 @@ int Builder::decl_name_map(const RadNameMap* m) {
auto seen = name_map_first_.find(c.declared);
if (seen != name_map_first_.end()) {
const RadNameMap& first = prog_.name_map[seen->second];
if (c.mode != RAD_MAP_CONCAT || first.mode != RAD_MAP_CONCAT) {
err(RAD_E_INVAL, "name map for '%s': declared twice, and only a CONCAT map may be "
"extended -- a repeated COPY map means two sources for one weight, and "
"which one wins is not something a declaration can express",
const bool joins = (c.mode == RAD_MAP_CONCAT && first.mode == RAD_MAP_CONCAT) ||
(c.mode == RAD_MAP_EMA && first.mode == RAD_MAP_EMA);
if (!joins) {
err(RAD_E_INVAL, "name map for '%s': declared twice, and only a CONCAT or EMA map may "
"be extended -- a repeated COPY map means two sources for one weight, "
"and which one wins is not something a declaration can express",
c.declared);
return RAD_E_INVAL;
}
@@ -1022,6 +1045,16 @@ int Builder::declare_logits(rad_buf b) {
prog_.gen_str.name.c_str());
return RAD_E_STATE;
}
if (prog_.is_audio_generator()) {
err(RAD_E_STATE, "declare_logits: this program already declared the audio generator '%s'",
prog_.agen_str.name.c_str());
return RAD_E_STATE;
}
if (prog_.is_video_generator()) {
err(RAD_E_STATE, "declare_logits: this program already declared the video generator '%s'",
prog_.vgen_str.name.c_str());
return RAD_E_STATE;
}
prog_.logits_buf = b;
return RAD_OK;
}
@@ -1052,6 +1085,16 @@ int Builder::declare_pooled(rad_buf b) {
prog_.gen_str.name.c_str());
return RAD_E_STATE;
}
if (prog_.is_audio_generator()) {
err(RAD_E_STATE, "declare_pooled: this program already declared the audio generator '%s'",
prog_.agen_str.name.c_str());
return RAD_E_STATE;
}
if (prog_.is_video_generator()) {
err(RAD_E_STATE, "declare_pooled: this program already declared the video generator '%s'",
prog_.vgen_str.name.c_str());
return RAD_E_STATE;
}
const RadBufDecl& d = prog_.buffers[b].decl;
if (d.dtype != RAD_F32 || d.domain != RAD_DOMAIN_DEVICE || d.rank != 2 ||
d.shape[0] < prog_.ctx.max_seqs || d.shape[1] <= 0) {
@@ -1140,10 +1183,13 @@ int Builder::declare_generator(const RadGeneratorDecl* d) {
prog_.gen_str.name.c_str(), nm);
return RAD_E_STATE;
}
if (prog_.logits_buf != RAD_NULL_HANDLE || prog_.pooled_buf != RAD_NULL_HANDLE) {
if (prog_.logits_buf != RAD_NULL_HANDLE || prog_.pooled_buf != RAD_NULL_HANDLE ||
prog_.is_audio_generator() || prog_.is_video_generator()) {
err(RAD_E_STATE, "declare_generator '%s': this program already declared %s; a program "
"generates text, embeds or makes images -- one of the three", nm,
prog_.logits_buf != RAD_NULL_HANDLE ? "logits" : "a pooled output");
"generates text, embeds, makes images, audio or video -- one of the five",
nm, prog_.logits_buf != RAD_NULL_HANDLE ? "logits"
: prog_.pooled_buf != RAD_NULL_HANDLE ? "a pooled output"
: prog_.is_audio_generator() ? "an audio generator" : "a video generator");
return RAD_E_STATE;
}
if (d->layout != RAD_GEN_LAYOUT_JOINT_GRID) {
@@ -1224,6 +1270,258 @@ int Builder::declare_generator(const RadGeneratorDecl* d) {
return RAD_OK;
}
/* Validated at declare for the reason the image generator is: a buffer too small for the longest
* window, or a window that never ends, would otherwise show at the first request. */
int Builder::declare_audio_generator(const RadAudioGenDecl* d) {
if (finished_) {
err(RAD_E_STATE, "declare_audio_generator after declare finished");
return RAD_E_STATE;
}
if (!d) { err(RAD_E_INVAL, "declare_audio_generator: null declaration"); return RAD_E_INVAL; }
const char* nm = d->name && *d->name ? d->name : "(unnamed)";
if (prog_.is_audio_generator()) {
err(RAD_E_STATE, "declare_audio_generator: '%s' was already declared; '%s' is a second one",
prog_.agen_str.name.c_str(), nm);
return RAD_E_STATE;
}
if (prog_.logits_buf != RAD_NULL_HANDLE || prog_.pooled_buf != RAD_NULL_HANDLE ||
prog_.generator.layout != 0 || prog_.is_video_generator()) {
err(RAD_E_STATE, "declare_audio_generator '%s': this program already declared %s; a "
"program generates text, embeds, makes images, audio or video -- one of "
"the five", nm,
prog_.logits_buf != RAD_NULL_HANDLE ? "logits"
: prog_.pooled_buf != RAD_NULL_HANDLE ? "a pooled output"
: prog_.generator.layout != 0 ? "an image generator" : "a video generator");
return RAD_E_STATE;
}
if (!d->tmpl || !std::strstr(d->tmpl, "{input}") || !std::strstr(d->tmpl, "{instructions}")) {
err(RAD_E_INVAL, "declare_audio_generator '%s': tmpl needs {instructions} and {input}", nm);
return RAD_E_INVAL;
}
if (d->tmpl_plain &&
(!std::strstr(d->tmpl_plain, "{input}") || std::strstr(d->tmpl_plain, "{instructions}"))) {
err(RAD_E_INVAL, "declare_audio_generator '%s': tmpl_plain is the prompt without "
"instructions and needs {input} alone", nm);
return RAD_E_INVAL;
}
if (d->neg_tmpl && !d->prompt_whole) {
err(RAD_E_INVAL, "declare_audio_generator '%s': an unconditional template makes branches "
"of different lengths, which step together only as whole prompts; set "
"prompt_whole", nm);
return RAD_E_INVAL;
}
if (d->max_prompt <= 0 || d->first_frame < 0 ||
(!d->neg_tmpl && (d->neg_keep_head < 0 || d->neg_keep_tail < 0 || d->neg_token < 0 ||
d->neg_keep_head + d->neg_keep_tail >= d->max_prompt))) {
err(RAD_E_INVAL, "declare_audio_generator '%s': the prompt is out of range (at most %lld "
"tokens, unconditional branch token %d keeping %d + %d)", nm,
(long long)d->max_prompt, (int)d->neg_token, (int)d->neg_keep_head,
(int)d->neg_keep_tail);
return RAD_E_INVAL;
}
const bool chunked = d->voc_chunk > 0;
if (chunked && (d->voc_context < 0 || d->lat_num != 1 || d->lat_den != 1)) {
err(RAD_E_INVAL, "declare_audio_generator '%s': a vocoder that plays frames as they are "
"made reads a frame as one latent (lat_num = lat_den = 1) and a context "
"of >= 0 frames; got %lld/%lld and %lld", nm, (long long)d->lat_num,
(long long)d->lat_den, (long long)d->voc_context);
return RAD_E_INVAL;
}
if (d->max_frames <= 0 || d->frame_rate_num <= 0 || d->frame_rate_den <= 0 ||
(!chunked && (d->win_frames <= 0 || d->win_hop <= 0 || d->win_hop > d->win_frames ||
d->win_lead < 0 || d->latent_channels <= 0 || d->win_crop_left < 0 ||
d->win_crop_right < 0)) ||
d->lat_num <= 0 || d->lat_den <= 0 || d->samples_per_latent <= 0 || d->sample_rate <= 0 ||
d->channels <= 0 || d->max_lanes <= 0) {
err(RAD_E_INVAL, "declare_audio_generator '%s': a geometry field is out of range (%lld "
"frames at %lld/%lld a second, windows of %lld every %lld, %lld lead "
"rows, %lld/%lld latents a frame of %lld channels, crops %lld + %lld, "
"%lld samples a latent at %lld Hz x %lld, %lld lanes)", nm,
(long long)d->max_frames, (long long)d->frame_rate_num, (long long)d->frame_rate_den,
(long long)d->win_frames, (long long)d->win_hop, (long long)d->win_lead,
(long long)d->lat_num, (long long)d->lat_den, (long long)d->latent_channels,
(long long)d->win_crop_left, (long long)d->win_crop_right,
(long long)d->samples_per_latent, (long long)d->sample_rate, (long long)d->channels,
(long long)d->max_lanes);
return RAD_E_INVAL;
}
/* A middle window plays what is left after both crops, so they must leave some of it. */
if (!chunked &&
d->win_crop_left + d->win_crop_right >= d->win_frames * d->lat_num / d->lat_den) {
err(RAD_E_INVAL, "declare_audio_generator '%s': the crops (%lld + %lld latents) leave a "
"window of %lld latents nothing to play", nm, (long long)d->win_crop_left,
(long long)d->win_crop_right, (long long)(d->win_frames * d->lat_num / d->lat_den));
return RAD_E_INVAL;
}
if ((!chunked && d->default_steps <= 0) || !(d->default_cfg >= 1.0)) {
err(RAD_E_INVAL, "declare_audio_generator '%s': the sampler is incomplete (%lld default "
"steps, guidance %g)", nm, (long long)d->default_steps, d->default_cfg);
return RAD_E_INVAL;
}
auto buf_ok = [&](rad_buf h, uint32_t dtype, int64_t numel, const char* what) {
if (h == RAD_NULL_HANDLE || (size_t)h >= prog_.buffers.size()) {
err(RAD_E_INVAL, "declare_audio_generator '%s': %s %u is not a declared buffer", nm,
what, (unsigned)h);
return false;
}
const RadBufDecl& ob = prog_.buffers[h].decl;
if (ob.dtype != dtype || ob.domain != RAD_DOMAIN_DEVICE ||
decl_numel(ob.rank, ob.shape) < numel) {
err(RAD_E_INVAL, "declare_audio_generator '%s': %s '%s' must be a device %s buffer of "
"at least %lld elements", nm, what, prog_.buffers[h].name.c_str(),
dtype == RAD_I32 ? "i32" : "f32", (long long)numel);
return false;
}
return true;
};
/* audio_out holds what one VOCODE pass plays: a window, or a chunk of frames. */
const int64_t win_samples = (chunked ? d->voc_chunk : d->win_frames * d->lat_num / d->lat_den) *
d->samples_per_latent;
if (!buf_ok(d->status, RAD_I32, d->max_lanes, "status") ||
!buf_ok(d->audio_out, RAD_F32, win_samples * d->channels, "audio_out"))
return RAD_E_INVAL;
prog_.agen_str.name = nm;
prog_.agen_str.tmpl = d->tmpl;
prog_.agen_str.tmpl_plain = d->tmpl_plain ? d->tmpl_plain : "";
prog_.agen_str.neg_tmpl = d->neg_tmpl ? d->neg_tmpl : "";
prog_.audio_gen = *d;
/* As for the image generator: the Program is moved after declare; strings live in agen_str. */
prog_.audio_gen.name = nullptr;
prog_.audio_gen.tmpl = nullptr;
prog_.audio_gen.tmpl_plain = nullptr;
prog_.audio_gen.neg_tmpl = nullptr;
return RAD_OK;
}
/* Validated at declare for the reasons the other generators are: an output buffer too small for
* the largest chunk or the longest soundtrack, or a geometry whose frame count does not follow
* from its chunks, would otherwise show at the first request. */
int Builder::declare_video_generator(const RadVideoGenDecl* d) {
if (finished_) {
err(RAD_E_STATE, "declare_video_generator after declare finished");
return RAD_E_STATE;
}
if (!d) { err(RAD_E_INVAL, "declare_video_generator: null declaration"); return RAD_E_INVAL; }
const char* nm = d->name && *d->name ? d->name : "(unnamed)";
if (prog_.is_video_generator()) {
err(RAD_E_STATE, "declare_video_generator: '%s' was already declared; '%s' is a second one",
prog_.vgen_str.name.c_str(), nm);
return RAD_E_STATE;
}
if (prog_.logits_buf != RAD_NULL_HANDLE || prog_.pooled_buf != RAD_NULL_HANDLE ||
prog_.generator.layout != 0 || prog_.is_audio_generator()) {
err(RAD_E_STATE, "declare_video_generator '%s': this program already declared %s; a "
"program generates text, embeds, makes images, audio or video -- one of "
"the five", nm,
prog_.logits_buf != RAD_NULL_HANDLE ? "logits"
: prog_.pooled_buf != RAD_NULL_HANDLE ? "a pooled output"
: prog_.generator.layout != 0 ? "an image generator" : "an audio generator");
return RAD_E_STATE;
}
if (!d->tmpl || !std::strstr(d->tmpl, "{prompt}") || d->max_text <= 0) {
err(RAD_E_INVAL, "declare_video_generator '%s': tmpl needs {prompt} and max_text a "
"length (%lld)", nm, (long long)d->max_text);
return RAD_E_INVAL;
}
if (d->fps_num <= 0 || d->fps_den <= 0 || d->frames_per_chunk <= 0 || d->frames_tail < 0 ||
d->latents_per_chunk <= 0 || d->latents_tail < 0 || d->dec_latents < d->latents_per_chunk ||
d->min_chunks <= 0 || d->max_chunks < d->min_chunks || d->default_chunks < d->min_chunks ||
d->default_chunks > d->max_chunks ||
d->latents_per_chunk * (d->max_chunks - 1) + d->dec_latents >
d->latents_per_chunk * d->max_chunks + d->latents_tail) {
err(RAD_E_INVAL, "declare_video_generator '%s': the temporal geometry is out of range "
"(%lld/%lld fps, %lld n + %lld frames over %lld n + %lld latents, chunks of "
"%lld latents, %lld..%lld chunks, %lld by default)", nm,
(long long)d->fps_num, (long long)d->fps_den, (long long)d->frames_per_chunk,
(long long)d->frames_tail, (long long)d->latents_per_chunk, (long long)d->latents_tail,
(long long)d->dec_latents, (long long)d->min_chunks, (long long)d->max_chunks,
(long long)d->default_chunks);
return RAD_E_INVAL;
}
const int64_t unit = d->latent_scale * d->patch;
if (d->latent_scale <= 0 || d->latent_channels <= 0 || d->patch <= 0 ||
d->size_multiple <= 0 || d->size_multiple % unit != 0 || d->min_side < d->size_multiple ||
d->max_area < d->min_side * d->min_side || d->max_aspect < 1 ||
d->default_width % d->size_multiple != 0 || d->default_height % d->size_multiple != 0 ||
d->default_width < d->min_side || d->default_height < d->min_side ||
d->default_width * d->default_height > d->max_area) {
err(RAD_E_INVAL, "declare_video_generator '%s': the spatial geometry is out of range "
"(latents of %lld px in %lld x %lld patches, sides multiples of %lld from "
"%lld, area to %lld, aspect to %lld, %lld x %lld by default)", nm,
(long long)d->latent_scale, (long long)d->patch, (long long)d->patch,
(long long)d->size_multiple, (long long)d->min_side, (long long)d->max_area,
(long long)d->max_aspect, (long long)d->default_width, (long long)d->default_height);
return RAD_E_INVAL;
}
if (d->sample_rate <= 0 || d->audio_rate <= 0 || d->sample_rate % d->audio_rate != 0 ||
d->audio_channels <= 0 || d->audio_latent_channels <= 0) {
err(RAD_E_INVAL, "declare_video_generator '%s': the soundtrack is out of range (%lld Hz "
"at %lld latents a second, %lld channels of %lld)", nm,
(long long)d->sample_rate, (long long)d->audio_rate, (long long)d->audio_channels,
(long long)d->audio_latent_channels);
return RAD_E_INVAL;
}
if (d->default_steps <= 0 || d->max_steps < d->default_steps || !(d->shift_video > 0.0) ||
!(d->shift_audio > 0.0) || d->max_lanes <= 0) {
err(RAD_E_INVAL, "declare_video_generator '%s': the sampler is incomplete (%lld steps by "
"default, %lld at most, shifts %g and %g, %lld lanes)", nm,
(long long)d->default_steps, (long long)d->max_steps, d->shift_video, d->shift_audio,
(long long)d->max_lanes);
return RAD_E_INVAL;
}
if (d->n_rungs < 0 || (d->n_rungs > 0 && !d->rungs) ||
(d->n_rungs > 0 && (d->default_steps != d->n_rungs + 1 || d->max_steps != d->n_rungs + 1))) {
err(RAD_E_INVAL, "declare_video_generator '%s': a trained schedule of %d rungs runs %d grid "
"points, which default_steps and max_steps must both be (%lld, %lld)", nm,
(int)d->n_rungs, (int)d->n_rungs + 1, (long long)d->default_steps,
(long long)d->max_steps);
return RAD_E_INVAL;
}
for (int i = 0; i < d->n_rungs; ++i)
if (!(d->rungs[i] > 0.0 && d->rungs[i] <= 1.0) ||
(i > 0 && !(d->rungs[i] < d->rungs[i - 1]))) {
err(RAD_E_INVAL, "declare_video_generator '%s': rung %d (%g) is outside (0, 1] or not "
"below the one before it", nm, i, d->rungs[i]);
return RAD_E_INVAL;
}
auto buf_ok = [&](rad_buf h, uint32_t dtype, int64_t numel, const char* what) {
if (h == RAD_NULL_HANDLE || (size_t)h >= prog_.buffers.size()) {
err(RAD_E_INVAL, "declare_video_generator '%s': %s %u is not a declared buffer", nm,
what, (unsigned)h);
return false;
}
const RadBufDecl& ob = prog_.buffers[h].decl;
if (ob.dtype != dtype || ob.domain != RAD_DOMAIN_DEVICE ||
decl_numel(ob.rank, ob.shape) < numel) {
err(RAD_E_INVAL, "declare_video_generator '%s': %s '%s' must be a device %s buffer of "
"at least %lld elements", nm, what, prog_.buffers[h].name.c_str(),
dtype == RAD_U8 ? "u8" : "f32", (long long)numel);
return false;
}
return true;
};
/* frames_out holds the last chunk, the largest, at the largest area; audio_out the longest
* soundtrack. */
const int64_t chunk_px = (d->frames_per_chunk + d->frames_tail) * d->max_area * 3;
const int64_t max_frames = d->frames_per_chunk * d->max_chunks + d->frames_tail;
const int64_t max_lat = (max_frames * d->fps_den * d->audio_rate * 2 + d->fps_num) /
(2 * d->fps_num) + 1;
const int64_t max_samples = max_lat * (d->sample_rate / d->audio_rate);
if (!buf_ok(d->frames_out, RAD_U8, chunk_px, "frames_out") ||
!buf_ok(d->audio_out, RAD_F32, max_samples * d->audio_channels, "audio_out"))
return RAD_E_INVAL;
prog_.vgen_str.name = nm;
prog_.vgen_str.tmpl = d->tmpl;
prog_.vgen_str.rungs.assign(d->rungs, d->rungs + d->n_rungs);
prog_.video_gen = *d;
/* As for the other generators: the Program is moved after declare; strings and the rungs live
* in vgen_str. */
prog_.video_gen.name = nullptr;
prog_.video_gen.tmpl = nullptr;
prog_.video_gen.rungs = nullptr;
return RAD_OK;
}
/* Validates the draft head at declare rather than at the first draft pass, where a bad decl would
* only show as zero acceptance. `depth` must equal RadBuildCtx::max_spec, which the plugin sized
* its buffers with. */
@@ -1524,10 +1822,12 @@ void Builder::finish_layouts() {
for (size_t h = 1; h < prog_.weights.size(); ++h) {
const WeightInfo& w = prog_.weights[h];
if (w.n_sel <= 1 || !w.identity || !claimant[h].empty()) continue;
char en[256];
rad_enc_format(&w.enc, en, sizeof en);
if (unjoined[h].empty())
err(RAD_E_SHAPE, "'%s' takes %d planes of '%s' as one weight and no op reads it, so "
"nothing says how they are stored", w.name.c_str(), w.n_sel,
w.source.c_str());
err(RAD_E_SHAPE, "'%s' takes %d planes of '%s' (%s) as one weight and no op reads it, "
"so nothing says how they are stored", w.name.c_str(), w.n_sel,
w.source.c_str(), en);
else
err(RAD_E_SHAPE, "'%s' takes %d planes of '%s' as one weight, and the host kernels "
"reading it (%s) have no layout that joins them (abi/rad_planes.h)",
@@ -1814,6 +2114,16 @@ int rad_declare_generator(RadBuilder* b, const RadGeneratorDecl* d) {
return B(b)->declare_generator(d);
}
int rad_declare_audio_generator(RadBuilder* b, const RadAudioGenDecl* d) {
if (!b) return RAD_E_INVAL;
return B(b)->declare_audio_generator(d);
}
int rad_declare_video_generator(RadBuilder* b, const RadVideoGenDecl* d) {
if (!b) return RAD_E_INVAL;
return B(b)->declare_video_generator(d);
}
void rad_note(RadBuilder* b, const char* f, ...) {
if (!b) return;
va_list ap;
+31 -5
View File
@@ -258,6 +258,32 @@ const RadChatFormat* rad_tools_chat_format(const LoadedPlugins& lp, const RadMod
return ap->arch_chat_format(&meta);
}
int rad_tools_text_prepare(const LoadedPlugins& lp, int field, const std::string& in,
std::string* out) {
const Plugin* ap = rad_tools_registry().plugin(lp.arch_plugin);
if (!ap || !ap->arch_text_prepare) {
*out = in;
return RAD_OK;
}
std::string buf(in.size() * 2 + 64, '\0');
for (int tries = 0; tries < 2; ++tries) {
const int64_t n = ap->arch_text_prepare(field, in.c_str(), &buf[0], (int64_t)buf.size());
if (n < 0) return (int)n;
if (n < (int64_t)buf.size()) {
buf.resize((size_t)n);
*out = std::move(buf);
return RAD_OK;
}
buf.assign((size_t)n + 1, '\0');
}
return RAD_E_STATE;
}
VideoPositionsFn rad_tools_video_positions(const LoadedPlugins& lp) {
const Plugin* ap = rad_tools_registry().plugin(lp.arch_plugin);
return ap ? ap->arch_video_positions : nullptr;
}
const RadAudioFormat* rad_tools_audio_format(const LoadedPlugins& lp, const RadModelMeta& meta) {
const Plugin* ap = rad_tools_registry().plugin(lp.arch_plugin);
if (!ap || !ap->arch_audio_format) return nullptr;
@@ -368,8 +394,8 @@ int rad_tools_declare(const LoadedPlugins& lp, const RadModelMeta& meta, const R
return s;
}
/* RUNTIME LoRA, after the plugin and before the sampler: the sites read the plugin's finished
* graph, and the appended ops go through the same resolution as everything else. */
/* Runtime LoRA, after the plugin and before the sampler: the sites read the plugin's finished
* graph, and the appended ops go through the same resolution as every other op. */
if (with_lora) {
b.set_lora_targets(nullptr);
s = lora_declare(b, *lora);
@@ -381,9 +407,9 @@ int rad_tools_declare(const LoadedPlugins& lp, const RadModelMeta& meta, const R
/* The sampler declares into the same builder before finish(). An unresolved sampler op is not
* a declare failure (a deployment that never sends `typical_p` needs no typical kernel), so a
* negative return here is structural. Skipped for embedding programs and image generators,
* which sample no token. */
if (also && b.program().pooled_buf == RAD_NULL_HANDLE && !b.program().is_generator()) {
* negative return here is structural. Skipped for embedding programs and generators, which
* sample through no token sampler (an audio generator samples its frames itself). */
if (also && b.program().pooled_buf == RAD_NULL_HANDLE && !b.program().is_pass_driven()) {
/* This rank's vocabulary width, taken from the declared logits buffer rather than
* re-derived from n_vocab and world_size, which would break when a plugin does not split
* the vocabulary (arch/common/rad_arch.h does not). A wrong width does not crash; it
+11
View File
@@ -88,6 +88,17 @@ const RadChatFormat* rad_tools_chat_format(const LoadedPlugins& plugins, const R
* small to hold a field reads that field as null. */
const RadAudioFormat* rad_tools_audio_format(const LoadedPlugins& plugins, const RadModelMeta& meta);
/* A request's text rewritten by the architecture plugin for the audio generator's prompt
* (rad_arch_text_prepare): RAD_OK with the result in `*out` (the text unchanged when the plugin
* states no rewrite), or the plugin's negative status. */
int rad_tools_text_prepare(const LoadedPlugins& plugins, int field, const std::string& in,
std::string* out);
/* The architecture plugin's video positions (rad_arch_video_positions), or null when it exports
* none. */
using VideoPositionsFn = int64_t (*)(int, const RadVideoGeom*, float*, int64_t);
VideoPositionsFn rad_tools_video_positions(const LoadedPlugins& plugins);
/* Run declare.
*
* `also` declares into the same builder after the architecture plugin, which is how the sampler
+79 -15
View File
@@ -14,12 +14,14 @@
#include <nlohmann/json.hpp>
#include <algorithm>
#include <cctype>
#include <cerrno>
#include <climits>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <set>
#include <sstream>
namespace rad {
@@ -104,9 +106,9 @@ static const Flag g_flags[] = {
" --lora). Each slot holds one adapter's A/B on the card"},
{ "--max-lora-rank", "R", "the rank each slot is sized for (default 16); a smaller\n"
" adapter is zero-padded, a larger one refused"},
{ "--lora-target-modules", "LIST", "comma-separated HF module names adapters may target\n"
" (q_proj,k_proj,...). Default: what the --lora adapters\n"
" target. Needed with --max-loras and no --lora"},
{ "--lora-target-modules", "LIST", "comma-separated HF module leaf names adapters may\n"
" target (q_proj,k_proj,...). Default: what the --lora\n"
" adapters target. Needed with --max-loras and no --lora"},
{ "--placement", "MODE", "all_vram | layer_offload | expert_tiered | auto" },
{ "--deterministic", nullptr, "pin placement to the plan the loader made, so the resident\n"
@@ -122,12 +124,12 @@ static const Flag g_flags[] = {
" intervals, and the checkpoints inside a span are not\n"
" written" },
/* A total, not per sequence: the snapshot store is one pool of N slots
* (KVManager::set_checkpoint_store). The default 8 gives one per sequence at 8 sequences,
* enough for append-only chat, where the next turn hits at the end of the last. */
{ "--checkpoint-slots", "N", "linear-state or sliding-window snapshots "
"retained IN TOTAL (not "
"per sequence), in pinned host memory; compare "
"against --max-num-seqs" },
* (KVManager::set_checkpoint_store). */
{ "--checkpoint-slots", "N", "linear-state or sliding-window snapshots the server holds in\n"
" total, in pinned host memory. Default `auto`: what\n"
" --checkpoint-policy keeps for a --max-model-len session, plus\n"
" one, for each of --max-num-seqs, within an eighth of host\n"
" memory. N fixes the total; 0 keeps none" },
{ "--no-prefix-cache", nullptr, "disable prefix caching" },
{ "--checkpoint-policy", "NAME", "which snapshots a session retains: geometric-backoff "
"(default), tip-only, keep-all" },
@@ -515,20 +517,29 @@ int config_parse(int argc, char** argv, Config* c) {
else if (S("--max-loras")) { if (!num(0, 64, &c->lora.max_loras)) return RAD_E_INVAL; }
else if (S("--max-lora-rank")) { if (!num(1, 512, &c->lora.max_rank)) return RAD_E_INVAL; }
else if (S("--lora-target-modules")) {
/* Module leaf names, as PEFT's target_modules lists them: a dotted path or a pattern
* would match no leaf and target nothing without a word. */
if (!(v = need(i))) return RAD_E_INVAL;
c->lora.targets.clear();
std::set<std::string> leaves;
std::string cur;
for (const char* q = v;; ++q) {
if (*q == ',' || !*q) {
if (!cur.empty()) c->lora.targets.insert(cur);
if (!cur.empty()) leaves.insert(cur);
cur.clear();
if (!*q) break;
} else if (*q != ' ') cur += *q;
} else if (std::isalnum((unsigned char)*q) || *q == '_') {
cur += *q;
} else if (*q != ' ') {
RAD_ERR("--lora-target-modules takes module leaf names (q_proj,k_proj,...); "
"'%s' holds '%c'", v, *q);
return RAD_E_INVAL;
}
}
if (c->lora.targets.empty()) {
if (leaves.empty()) {
RAD_ERR("--lora-target-modules names no module");
return RAD_E_INVAL;
}
c->lora.targets.assign(leaves.begin(), leaves.end());
}
/* The prefix cache has no disk tier; the removed flags name their replacements. */
else if (S("--prefix-cache-host-mib")) {
@@ -555,7 +566,17 @@ int config_parse(int argc, char** argv, Config* c) {
else if (S("--deterministic")) c->deterministic = true;
else if (S("--checkpoint-interval")) { if (!num(0, INT64_MAX, &c->checkpoint_interval)) return RAD_E_INVAL; }
else if (S("--prefill-span")) { if (!num(1, INT32_MAX, &c->prefill_span)) return RAD_E_INVAL; }
else if (S("--checkpoint-slots")) { if (!num(0, INT64_MAX, &c->checkpoint_slots)) return RAD_E_INVAL; }
else if (S("--checkpoint-slots")) {
if (!(v = need(i))) return RAD_E_INVAL;
if (!std::strcmp(v, "auto")) {
c->checkpoint_slots = -1;
} else if (!*v || std::strspn(v, "0123456789") != std::strlen(v)) {
RAD_ERR("--checkpoint-slots takes auto or a whole number, not '%s'", v);
return RAD_E_INVAL;
} else if (!parse_int(a.c_str(), v, 0, INT64_MAX, &c->checkpoint_slots)) {
return RAD_E_INVAL;
}
}
else if (S("--no-prefix-cache")) c->prefix_cache = false;
else if (S("--checkpoint-policy")) {
if (!(v = need(i))) return RAD_E_INVAL;
@@ -844,6 +865,48 @@ int config_parse(int argc, char** argv, Config* c) {
return RAD_E_INVAL;
}
/* Runtime LoRA: the slot flags need slots, the named adapters must fit them, and KL mode's
* adapter is one of them. */
{
const LoraConfig& L = c->lora;
std::set<std::string> names;
for (const auto& [name, path] : L.adapters)
if (!names.insert(name).second) {
RAD_ERR("--lora names the adapter '%s' twice", name.c_str());
return RAD_E_INVAL;
}
if (L.max_loras > 0 && L.max_loras < (int)L.adapters.size()) {
RAD_ERR("--max-loras %d holds fewer adapters than the %zu that --lora names",
L.max_loras, L.adapters.size());
return RAD_E_INVAL;
}
const bool rank_given = c->given.count("--max-lora-rank") != 0;
if (!L.enabled() && (rank_given || !L.targets.empty())) {
RAD_ERR("%s sizes runtime LoRA slots, and there are none: give --lora or --max-loras",
rank_given ? "--max-lora-rank" : "--lora-target-modules");
return RAD_E_INVAL;
}
if (L.adapters.empty() && L.max_loras > 0 && L.targets.empty()) {
RAD_ERR("--max-loras with no --lora names no module an adapter may target; give "
"--lora-target-modules (q_proj,k_proj,v_proj,o_proj,...)");
return RAD_E_INVAL;
}
if (!c->kld_lora.empty() && !c->kld()) {
RAD_ERR("--kld-lora scores through an adapter in KL mode; give --kld-record or "
"--kld-ref");
return RAD_E_INVAL;
}
if (!c->kld_lora.empty() && !names.count(c->kld_lora)) {
RAD_ERR("--kld-lora '%s' is not one of the adapters --lora names", c->kld_lora.c_str());
return RAD_E_INVAL;
}
if (!c->kld_lora_sources.empty() && c->kld_lora.empty()) {
RAD_ERR("--kld-lora-sources picks the documents that run through --kld-lora's adapter; "
"give --kld-lora");
return RAD_E_INVAL;
}
}
/* --reasoning-effort is a template variable ("none" also sets enable_thinking false), so
* either key in --chat-template-kwargs as well would give two defaults for one setting. */
if (!c->reasoning_effort.empty() &&
@@ -960,7 +1023,8 @@ const ShowRow kShow[] = {
{ "--deterministic", [](const Config& c) { return onoff(c.deterministic); } },
{ "--checkpoint-interval", [](const Config& c) { return num(c.checkpoint_interval); } },
{ "--prefill-span", [](const Config& c) { return num(c.prefill_span); } },
{ "--checkpoint-slots", [](const Config& c) { return num(c.checkpoint_slots); } },
{ "--checkpoint-slots", [](const Config& c) {
return c.checkpoint_slots < 0 ? std::string("auto") : num(c.checkpoint_slots); } },
{ "--no-prefix-cache", [](const Config& c) {
return std::string(c.prefix_cache ? "not given: prefix caching on" : "prefix caching off"); } },
{ "--checkpoint-policy", [](const Config& c) { return c.checkpoint_policy; } },
+27 -25
View File
@@ -618,6 +618,9 @@ void on_queue_error(hsa_status_t st, hsa_queue_t*, void* data) {
* nothing will decrement, or a kernel that faulted silently); the packet at the read index says
* which. */
/* Sum of every queue's read index. It only grows, so an unchanged sum means no queue moved. */
/* How long a host wait may see no queue advance before it reports the queues; see dump_queues. */
constexpr uint32_t kStallMs = 5000;
uint64_t read_progress() {
std::lock_guard<std::mutex> lk(G().streams_mu);
uint64_t n = 0;
@@ -630,7 +633,7 @@ void (*g_dump_lanes)() = nullptr;
void dump_queues(const char* where) {
std::lock_guard<std::mutex> lk(G().streams_mu);
RAD_ERR("device: %s has waited 5 s; the queues:", where);
RAD_ERR("device: %s has seen no queue advance for %u s; the queues:", where, kStallMs / 1000);
for (Stream* s : G().streams) {
const uint64_t rd = hsa_queue_load_read_index_scacquire(s->q);
const uint64_t wr = hsa_queue_load_write_index_scacquire(s->q);
@@ -829,45 +832,44 @@ hsa_status_t on_system_event(const hsa_amd_event_t* e, void*) {
"exiting so a restart can bring the server back", card);
}
/* How long a host wait goes before it reports the queues; see dump_queues. */
constexpr uint32_t kStallMs = 5000;
/* Stall detector for a spin loop. tick() reads the clock every 64k iterations, a few thousand
* times a second at most.
*
* The dump alone cannot tell slow from stuck: a long prefill at deep context can hold one wait
* past 5 s while the queue drains, and a hung kernel holds it with the read index frozen. So the
* read indices are sampled with the dump and again one stall period later: advanced means a long
* wait, unchanged means the GPU is not running the queue. */
* A long wait is not a fault: a long prefill at deep context holds one wait for seconds, and a
* video generator's denoising pass for tens of them. So the queues' read indices are sampled once
* every stall period and only a period in which none advanced reports, with the packet each queue
* is on: a hung kernel, or a queue the driver evicted and could not restore. A wait that keeps
* moving says nothing. */
struct Stall {
const char* where;
uint32_t n = 0;
int told = 0; /* 0 nothing said, 1 the dump, 2 the verdict */
bool told = false;
bool sampled = false;
uint64_t progress = 0;
std::chrono::steady_clock::time_point t0 = std::chrono::steady_clock::now();
std::chrono::steady_clock::time_point next =
std::chrono::steady_clock::now() + std::chrono::milliseconds(kStallMs);
explicit Stall(const char* w) : where(w) {}
void tick() {
if (told == 2 || (++n & 0xffff)) return;
if (told || (++n & 0xffff)) return;
check();
}
/* Checks on every call, for a loop that sleeps between calls. */
void check() {
if (told == 2) return;
const auto waited = std::chrono::steady_clock::now() - t0;
if (told == 0 && waited > std::chrono::milliseconds(kStallMs)) {
told = 1;
progress = read_progress();
if (told) return;
const auto now = std::chrono::steady_clock::now();
if (now < next) return;
next = now + std::chrono::milliseconds(kStallMs);
const uint64_t p = read_progress();
if (sampled && p == progress) {
told = true;
dump_queues(where);
} else if (told == 1 && waited > std::chrono::milliseconds(2 * kStallMs)) {
told = 2;
if (read_progress() != progress)
RAD_WARN("device: the queues advanced in the %u s since; %s is long, not stuck",
kStallMs / 1000, where);
else
RAD_ERR("device: no queue has advanced in the %u s since: the GPU is not running "
"the packet named above -- a hung kernel, or a queue the driver evicted and "
"could not restore (amdgpu cwsr_enable=0 is one cause)", kStallMs / 1000);
RAD_ERR("device: no queue has advanced in the %u s since: the GPU is not running the "
"packet named above -- a hung kernel, or a queue the driver evicted and could "
"not restore (amdgpu cwsr_enable=0 is one cause)", kStallMs / 1000);
return;
}
sampled = true;
progress = p;
}
};
+177 -18
View File
@@ -4,6 +4,8 @@
*/
#include "engine_priv.h"
#include "gen/driver.h"
#include "gen/audio_driver.h"
#include "gen/video_driver.h"
#include "kld.h"
#include "mm/processor.h"
@@ -1343,28 +1345,39 @@ int Engine::serve(std::unique_ptr<StallWatch> watch) {
return RAD_E_STATE;
}
embedding_ = ranks_[0]->program.pooled_buf != RAD_NULL_HANDLE;
const bool generator = ranks_[0]->program.is_generator();
const bool audio_gen = ranks_[0]->program.is_audio_generator();
const bool video_gen = ranks_[0]->program.is_video_generator();
const bool generator = ranks_[0]->program.is_pass_driven();
if (ranks_[0]->program.logits_buf == RAD_NULL_HANDLE && !embedding_ && !generator) {
RAD_ERR("the '%s' plugin declared no logits buffer (rad_declare_logits), no pooled output "
"(rad_declare_pooled) and no image generator (rad_declare_generator), so a step "
"produces nothing anyone can read. An encoder-only plugin cannot serve.",
"(rad_declare_pooled) and no generator (rad_declare_generator, "
"rad_declare_audio_generator, rad_declare_video_generator), so a step produces "
"nothing anyone can read. An encoder-only plugin cannot serve.",
plugins_.arch_plugin.c_str());
return RAD_E_UNSUPPORTED;
}
if (generator) {
const char* const what = audio_gen ? "audio" : video_gen ? "video" : "images";
if (cfg_.kld() || cfg_.n_spec > 0) {
RAD_ERR("the '%s' plugin makes images: --kld and speculative decoding have no tokens to "
"work on", plugins_.arch_plugin.c_str());
RAD_ERR("the '%s' plugin makes %s: --kld and speculative decoding have no tokens to "
"work on", plugins_.arch_plugin.c_str(), what);
return RAD_E_UNSUPPORTED;
}
for (size_t i = 1; i < ranks_.size(); ++i)
if (!ranks_[i]->program.is_generator()) {
RAD_ERR("rank %zu declared no image generator and rank 0 did", i);
if (ranks_[i]->program.is_audio_generator() != audio_gen ||
ranks_[i]->program.is_video_generator() != video_gen ||
!ranks_[i]->program.is_pass_driven()) {
RAD_ERR("rank %zu declared a different generator from rank 0's", i);
return RAD_E_STATE;
}
cfg_.prefix_cache = false;
prefix_off_why_ = "an image generator: a conditioning is read by its own request's images "
"and by nothing after them";
prefix_off_why_ = audio_gen
? "an audio generator: a prompt is read by its own request's frames and by nothing "
"after them"
: video_gen
? "a video generator: a prompt is read by its own request's steps and keeps no KV"
: "an image generator: a conditioning is read by its own request's images and by "
"nothing after them";
decide("--no-prefix-cache", "prefix caching off", prefix_off_why_);
}
if (embedding_) {
@@ -1498,13 +1511,33 @@ int Engine::serve(std::unique_ptr<StallWatch> watch) {
rio.reserve(ranks_.size());
for (auto& rk : ranks_)
rio.push_back({ rk->device, rk->ctx.stream(), &rk->program });
if (generator) {
if (video_gen) {
/* As for the image generator below; the plugin lays out each request's rows. */
std::vector<gen::VideoDriver::RankIO> gio;
for (auto& rk : ranks_) gio.push_back({ rk->device, rk->ctx.stream() });
auto d = std::make_unique<gen::VideoDriver>();
RAD_TRY(d->init(ranks_[0]->program, rad_tools_video_positions(plugins_), gio));
vid_gen_ = d.get();
gen_ = std::move(d);
RAD_TRY(rad_dev_set(ranks_[0]->device));
} else if (audio_gen) {
/* As for the image generator below. */
std::vector<gen::AudioDriver::RankIO> gio;
for (auto& rk : ranks_) gio.push_back({ rk->device, rk->ctx.stream() });
auto d = std::make_unique<gen::AudioDriver>();
RAD_TRY(d->init(ranks_[0]->program, kv_iface_.get(), gio));
aud_gen_ = d.get();
gen_ = std::move(d);
RAD_TRY(rad_dev_set(ranks_[0]->device));
} else if (generator) {
/* The generator's driver replaces the scheduler, which is never initialised, so its
* token-step staging is never allocated. */
std::vector<gen::Driver::RankIO> gio;
for (auto& rk : ranks_) gio.push_back({ rk->device, rk->ctx.stream() });
gen_ = std::make_unique<gen::Driver>();
RAD_TRY(gen_->init(ranks_[0]->program, kv_iface_.get(), gio));
auto d = std::make_unique<gen::Driver>();
RAD_TRY(d->init(ranks_[0]->program, kv_iface_.get(), gio));
img_gen_ = d.get();
gen_ = std::move(d);
RAD_TRY(rad_dev_set(ranks_[0]->device));
} else
RAD_TRY(sched_.init(ranks_[0]->program, cfg_, kv_iface_.get(), pc_iface_.get(), rio, &geo_));
@@ -2006,7 +2039,9 @@ int Engine::run_server() {
server::ServerOptions o{};
o.embedding_model = embedding_;
o.image_model = gen_ != nullptr;
o.image_model = img_gen_ != nullptr;
o.audio_model = aud_gen_ != nullptr;
o.video_model = vid_gen_ != nullptr;
o.decision_type = rad_meta_gets(&meta_, "decision.type", "");
o.model_id = !cfg_.served_model_name.empty() ? cfg_.served_model_name
: meta_.name && *meta_.name ? meta_.name : "radiance";
@@ -2024,9 +2059,9 @@ int Engine::run_server() {
o.default_reasoning_effort = cfg_.reasoning_effort;
o.reasoning_effort_map = cfg_.reasoning_effort_map;
o.default_thinking_budget = cfg_.thinking_token_budget;
{
if (!gen_) {
/* The four sampler defaults a file can state: the served value and, per field, its
* source. */
* source. A generator samples by its own rules and serves no text requests. */
GenSampling stated;
std::string src;
o.default_sampling =
@@ -2078,6 +2113,14 @@ int Engine::run_server() {
/* Per request, from a reading at most a second old (Engine::diagnostics_json). */
o.diagnostics_json = [this] { return diagnostics_json(); };
if (cfg_.lora.enabled()) {
/* `model` picks the adapter, and the served model's own name picks the base. */
for (const auto& [name, dir] : cfg_.lora.adapters)
if (name == o.model_id) {
RAD_ERR("lora: the adapter '%s' has the served model's own name, so a request "
"naming it would run the base; rename it or give --served-model-name",
name.c_str());
return RAD_E_INVAL;
}
o.lora_acquire = [this](const std::string& m, int32_t* slot, uint64_t* uid,
std::shared_ptr<void>* hold) {
return lora_acquire(m, slot, uid, hold);
@@ -2317,7 +2360,7 @@ int Engine::run_server() {
int64_t queued() const override { return drv->queued(); }
int64_t running() const override { return drv->running(); }
} image_bridge;
if (gen_) {
if (img_gen_) {
const Program& pg = ranks_[0]->program;
const RadGeneratorDecl& gd = pg.generator;
server::ImageGenInfo& in = image_bridge.inf;
@@ -2339,11 +2382,11 @@ int Engine::run_server() {
in.default_height = gd.default_height;
in.default_steps = gd.default_steps;
in.max_lanes = gd.max_lanes;
in.max_cond_tokens = gen_->max_cond_tokens();
in.max_cond_tokens = img_gen_->max_cond_tokens();
in.fixed_schedule = !pg.gen_str.sigmas.empty();
in.fixed_steps = (int64_t)pg.gen_str.sigmas.size();
in.default_cfg = gd.default_cfg;
image_bridge.drv = gen_.get();
image_bridge.drv = img_gen_;
image_bridge.proc = mm_proc.get();
d.images = &image_bridge;
/* The served model id is the generator's own name (qwen-image-2.1), not the container's
@@ -2359,6 +2402,116 @@ int Engine::run_server() {
: (std::to_string(in.default_steps) + " steps by default").c_str());
}
/* An audio generator's endpoint: the driver's queue, the declared prompt and limits, and the
* plugin's rewrite of a request's texts. */
struct AudioBridge final : server::IAudioGen {
gen::AudioDriver* drv = nullptr;
const LoadedPlugins* plugins = nullptr;
server::AudioGenInfo inf;
const server::AudioGenInfo& info() const override { return inf; }
int prepare(int field, const std::string& in, std::string* out,
std::string* why) const override {
const int s = rad_tools_text_prepare(*plugins, field, in, out);
if (s < 0 && why)
*why = s == RAD_E_INVAL ? "the model cannot take this text"
: std::string(rad_strerror(s));
return s;
}
int submit(std::unique_ptr<gen::AudioRequest> r, std::string* why) override {
return drv->submit(std::move(r), why);
}
int64_t queued() const override { return drv->queued(); }
int64_t running() const override { return drv->running(); }
} audio_bridge;
if (aud_gen_) {
const Program& pg = ranks_[0]->program;
const RadAudioGenDecl& ad = pg.audio_gen;
server::AudioGenInfo& in = audio_bridge.inf;
in.name = pg.agen_str.name;
in.tmpl = pg.agen_str.tmpl;
in.tmpl_plain = pg.agen_str.tmpl_plain;
in.neg_tmpl = pg.agen_str.neg_tmpl;
in.max_prompt = ad.max_prompt;
in.max_frames = ad.max_frames;
in.frame_rate_num = ad.frame_rate_num;
in.frame_rate_den = ad.frame_rate_den;
in.sample_rate = ad.sample_rate;
in.channels = ad.channels;
in.default_steps = ad.voc_chunk > 0 ? 0 : ad.default_steps;
in.default_cfg = ad.default_cfg;
in.max_lanes = ad.max_lanes;
audio_bridge.drv = aud_gen_;
audio_bridge.plugins = &plugins_;
d.audio = &audio_bridge;
if (cfg_.served_model_name.empty() && !in.name.empty()) {
o.model_id = in.name;
decide("--served-model-name", o.model_id, "an audio generator: its own name");
}
RAD_INFO("audio: '%s', %lld Hz x %lld, up to %lld frames (%lld s), %lld at once, %s",
in.name.c_str(), (long long)in.sample_rate, (long long)in.channels,
(long long)in.max_frames,
(long long)(in.max_frames * in.frame_rate_den / in.frame_rate_num),
(long long)in.max_lanes,
ad.voc_chunk > 0
? fmt("played %lld frames at a time as they are made",
(long long)ad.voc_chunk).c_str()
: fmt("%lld steps a window by default", (long long)in.default_steps).c_str());
}
/* A video generator's endpoints: the driver's queue and the declared prompt, sizes and
* lengths. */
struct VideoBridge final : server::IVideoGen {
gen::VideoDriver* drv = nullptr;
server::VideoGenInfo inf;
const server::VideoGenInfo& info() const override { return inf; }
int submit(std::unique_ptr<gen::VideoRequest> r, std::string* why) override {
return drv->submit(std::move(r), why);
}
int64_t queued() const override { return drv->queued(); }
int64_t running() const override { return drv->running(); }
} video_bridge;
if (vid_gen_) {
const Program& pg = ranks_[0]->program;
const RadVideoGenDecl& vd = pg.video_gen;
server::VideoGenInfo& in = video_bridge.inf;
in.name = pg.vgen_str.name;
in.tmpl = pg.vgen_str.tmpl;
in.max_text = vd.max_text;
in.fps_num = vd.fps_num;
in.fps_den = vd.fps_den;
in.frames_per_chunk = vd.frames_per_chunk;
in.frames_tail = vd.frames_tail;
in.min_chunks = vd.min_chunks;
in.max_chunks = vd.max_chunks;
in.size_multiple = vd.size_multiple;
in.min_side = vd.min_side;
in.max_area = vd.max_area;
in.max_aspect = vd.max_aspect;
in.default_width = vd.default_width;
in.default_height = vd.default_height;
in.default_chunks = vd.default_chunks;
in.sample_rate = vd.sample_rate;
in.channels = vd.audio_channels;
in.default_steps = vd.default_steps;
in.max_steps = vd.max_steps;
in.fixed_steps = vd.n_rungs > 0;
in.max_lanes = vd.max_lanes;
video_bridge.drv = vid_gen_;
d.videos = &video_bridge;
if (cfg_.served_model_name.empty() && !in.name.empty()) {
o.model_id = in.name;
decide("--served-model-name", o.model_id, "a video generator: its own name");
}
const double fps = (double)in.fps_num / (double)in.fps_den;
RAD_INFO("video: '%s', %lldx%lld by default (up to %lld pixels), %.2f to %.2f s at %g fps "
"with %lld Hz x %lld sound, %lld steps by default",
in.name.c_str(), (long long)in.default_width, (long long)in.default_height,
(long long)in.max_area,
(double)(in.frames_per_chunk * in.min_chunks + in.frames_tail) / fps,
(double)(in.frames_per_chunk * in.max_chunks + in.frames_tail) / fps, fps,
(long long)in.sample_rate, (long long)in.channels, (long long)in.default_steps);
}
if (encd.modalities == 0 && aend.modalities == 0 && cfg_.media_flags_set())
RAD_WARN("media: the media flags do nothing here -- this model %s",
cfg_.mm_max_patches == 0 ? "is served text only (--mm-max-patches 0)"
@@ -2417,6 +2570,12 @@ int Engine::run_server() {
if (embedding_)
RAD_INFO("serving on http://%s:%d (/v1/embeddings; completions and chat are 501%s)",
o.host.c_str(), o.port, keyed);
else if (aud_gen_)
RAD_INFO("serving on http://%s:%d (/v1/audio/speech; completions and chat are 501%s)",
o.host.c_str(), o.port, keyed);
else if (vid_gen_)
RAD_INFO("serving on http://%s:%d (/v1/videos; completions and chat are 501%s)",
o.host.c_str(), o.port, keyed);
else if (gen_)
RAD_INFO("serving on http://%s:%d (/v1/images/generations%s; completions and chat are "
"501%s)", o.host.c_str(), o.port,
+18 -13
View File
@@ -44,7 +44,7 @@ namespace rad {
class Kld;
class StallWatch;
namespace gen { class Driver; }
namespace gen { class Driver; class AudioDriver; class VideoDriver; struct IPassDriver; }
struct TierPump;
struct TierJob;
struct StepSlot;
@@ -136,21 +136,19 @@ private:
int apply_rope_scaling();
int declare();
int plan();
/* RUNTIME LoRA (core/engine_lora.cpp). Targets are fixed before declare; adapters are loaded
/* Runtime LoRA (core/engine_lora.cpp). Targets are fixed before declare; adapters are loaded
* into slots after every rank's Ctx is bound, and a request's `model` names one. */
int lora_targets();
int lora_start();
public:
int lora_load(const std::string& name, const std::string& dir, std::string* err);
/* Unpublish an adapter (lora::SlotTable::unload). Idle, its slot is freed at once; in use, it
* DRAINS: *in_flight says how many requests still hold it, no new request may name it, and
* the last of them frees the slot. A freed slot is reused only once the step loop has gone
* round three times since, so no step still on the card can read bytes a later load is
* writing (the next step is issued before the last is read back). */
* drains: *in_flight says how many requests still hold it, no new request may name it, and the
* last of them frees the slot, which cools before reuse (lora/slots.h). */
int lora_unload(const std::string& name, std::string* err, int* in_flight);
/* RAD_OK with the slot, the uid of its load and a HOLD -- the adapter is not freed while the
* hold lives (the server keeps it in the request's Generation, which outlives the request in
* the scheduler). RAD_E_NOTFOUND for a name no slot holds, or one that is draining. */
/* RAD_OK with the slot, the uid of its load and a hold: the adapter is not freed while the
* hold lives (the server keeps it in the request's Generation). RAD_E_NOTFOUND for a name no
* slot holds, or one that is draining. */
int lora_acquire(const std::string& name, int32_t* slot, uint64_t* uid,
std::shared_ptr<void>* hold);
std::vector<std::string> lora_names() const;
@@ -186,6 +184,8 @@ private:
std::vector<std::pair<const void*, void*>> table_copy_of_;
int load_weights();
int configure_kv();
/* Resolves --checkpoint-slots auto for snapshots of `slot` bytes (`what` names their kind). */
int size_checkpoint_store(int64_t slot, const char* what);
/* Maps the step's logits rows back to the sequences that wanted them. Not the identity: a
* mid-prompt prefill chunk produces no row, and a speculative verify produces 1 + n_spec. */
struct StepOut {
@@ -310,10 +310,15 @@ private:
float* pooled_host_ = nullptr;
int collect_pooled_issue(const RadBatch* b, StepOut& so);
int collect_pooled(const RadBatch* b, StepOut& so);
/* Image generator (rad_declare_generator): the driver that turns requests into passes and the
* loop that runs them, replacing the scheduler and step loop (engine_gen.cpp). Null for every
* other program. */
std::unique_ptr<gen::Driver> gen_;
/* A generator (rad_declare_generator, rad_declare_audio_generator,
* rad_declare_video_generator): the driver that turns requests into passes and the loop that
* runs them, replacing the scheduler and step loop (engine_gen.cpp). Null for every other
* program. `img_gen_`, `aud_gen_` and `vid_gen_` are the same driver by its kind, for the
* endpoints; one of them is set when `gen_` is. */
std::unique_ptr<gen::IPassDriver> gen_;
gen::Driver* img_gen_ = nullptr;
gen::AudioDriver* aud_gen_ = nullptr;
gen::VideoDriver* vid_gen_ = nullptr;
int gen_loop();
bool serial_drafting() const;
int advance_all(int mode, int round, bool from_proposal, int rows = -1);
+232 -64
View File
@@ -7,6 +7,8 @@
#include "engine_priv.h"
#include "engine_hostmem.h"
#include "gen/driver.h"
#include "gen/audio_driver.h"
#include "gen/video_driver.h"
#include "build/startup.h"
#include "build/rad_build.h"
@@ -205,12 +207,27 @@ static int64_t meminfo_bytes(const char* key) {
return -1;
}
/* The amdgpu driver's cap on the memory every process together pins: RAM less 1/64 and 1.5 GiB
* (half of RAM less 1/64 below 3 GiB), unless amdgpu.no_system_mem_limit lifts it;
* ttm.pages_limit does not apply. -1 when lifted (`*lifted` set) or MemTotal is unreadable. */
static int64_t amdgpu_pin_cap(bool* lifted) {
{
std::ifstream f("/sys/module/amdgpu/parameters/no_system_mem_limit");
std::string v;
*lifted = (f >> v) && (v == "Y" || v == "1");
}
const int64_t total = meminfo_bytes("MemTotal");
if (*lifted || total <= 0) return -1;
const int64_t reserve = (int64_t)3 << 29;
const int64_t cap = total - (total >> 6);
return cap < 2 * reserve ? cap >> 1 : cap - reserve;
}
/* Explain a refused pool allocation from the machine's current state.
*
* A card pool refused after the budget was measured (once, before any rank allocates) usually
* lost the memory to another process. A host pool is pinned, once per rank. Pinned memory counts
* against amdgpu's system-wide cap: RAM less 1/64 and 1.5 GiB (half of RAM less 1/64 below
* 3 GiB), unless amdgpu.no_system_mem_limit lifts it; ttm.pages_limit does not apply. */
* lost the memory to another process. A host pool is pinned, once per rank, and counts against
* amdgpu_pin_cap. */
static void report_pool_refusal(int rank, int device, const Pools& pools, const Config& cfg) {
bool card = false, host = false;
for (const Shortfall& f : pools.shortfalls()) (f.pool == "host_pool" ? host : card) = true;
@@ -226,19 +243,9 @@ static void report_pool_refusal(int rank, int device, const Pools& pools, const
int64_t pinned = 0, mapped = 0;
rad_dev_alloc_totals(RAD_MEM_HOST_PINNED, &pinned, nullptr);
rad_dev_alloc_totals(RAD_MEM_HOST_MAPPED, &mapped, nullptr);
const int64_t total = meminfo_bytes("MemTotal"), avail = meminfo_bytes("MemAvailable");
const int64_t avail = meminfo_bytes("MemAvailable");
bool lifted = false;
{
std::ifstream f("/sys/module/amdgpu/parameters/no_system_mem_limit");
std::string v;
lifted = (f >> v) && (v == "Y" || v == "1");
}
const int64_t reserve = (int64_t)3 << 29;
int64_t cap = -1;
if (total > 0 && !lifted) {
cap = total - (total >> 6);
cap = cap < 2 * reserve ? cap >> 1 : cap - reserve;
}
const int64_t cap = amdgpu_pin_cap(&lifted);
/* With room under both limits the refusal is not about size; do not advise shrinking. */
const int64_t pool = cfg.host_pool_total_mib() * 1024 * 1024;
std::string tables, advice = "Lower --host-pool-mib";
@@ -273,6 +280,34 @@ static void report_pool_refusal(int rank, int device, const Pools& pools, const
* kernel reclaims the files the engine reads, then the OOM killer runs. */
static const int64_t kLockMargin = (int64_t)4 << 30;
/* Every level of every memory cgroup the process is in, leaf first: `visit(dir, room)` until it
* returns false (cgroup_levels). /proc/self/cgroup reads "0::/path" on v2 and "N:memory:/path"
* (or a comma list naming memory) on v1; each level up to the visible root is a limit of its
* own. */
static void memory_cgroups(const std::function<bool(const std::string&, int64_t)>& visit) {
std::ifstream f("/proc/self/cgroup");
std::string line;
bool go = true;
while (go && std::getline(f, line)) {
const size_t a = line.find(':'), b = a == std::string::npos ? a : line.find(':', a + 1);
if (b == std::string::npos) continue;
const std::string ctrl = line.substr(a + 1, b - a - 1);
std::string path = line.substr(b + 1);
const bool v2 = ctrl.empty();
bool memory = v2;
for (size_t i = 0; !memory && i < ctrl.size();) {
const size_t j = std::min(ctrl.find(',', i), ctrl.size());
memory = ctrl.compare(i, j - i, "memory") == 0;
i = j + 1;
}
if (!memory) continue;
const std::string root = v2 ? "/sys/fs/cgroup" : "/sys/fs/cgroup/memory";
cgroup_levels(root, path, v2, [&](const std::string& dir, int64_t room) {
return go = visit(dir, room);
});
}
}
/* Whether `need` more bytes fit in host memory after `still` more this process will allocate
* first, or why not. Checks MemAvailable; every memory cgroup from the process's own up to the
* visible root (Docker's --memory, enforced by the OOM killer); and, for an mlock()ed copy
@@ -307,37 +342,39 @@ static bool lockable_room(int64_t need, int64_t still, bool mlocks, std::string*
humanb(kLockMargin).c_str());
return false;
}
/* /proc/self/cgroup: "0::/path" on v2, "N:memory:/path" (or a comma list naming memory) on v1.
* Each level up to the visible root is a separate limit. */
std::ifstream f("/proc/self/cgroup");
std::string line;
while (std::getline(f, line)) {
const size_t a = line.find(':'), b = a == std::string::npos ? a : line.find(':', a + 1);
if (b == std::string::npos) continue;
const std::string ctrl = line.substr(a + 1, b - a - 1);
std::string path = line.substr(b + 1);
const bool v2 = ctrl.empty();
bool memory = v2;
for (size_t i = 0; !memory && i < ctrl.size();) {
const size_t j = std::min(ctrl.find(',', i), ctrl.size());
memory = ctrl.compare(i, j - i, "memory") == 0;
i = j + 1;
}
if (!memory) continue;
const std::string root = v2 ? "/sys/fs/cgroup" : "/sys/fs/cgroup/memory";
bool fits = true;
cgroup_levels(root, path, v2, [&](const std::string& dir, int64_t room) {
if (room - still - kLockMargin >= need) return true;
*why = fmt("the memory cgroup at %s leaves %s, %s more is still to be allocated, "
"and this wants %s with %s to spare", dir.c_str(),
humanb(room).c_str(), humanb(still).c_str(), humanb(need).c_str(),
humanb(kLockMargin).c_str());
fits = false;
return false;
});
if (!fits) return false;
bool fits = true;
memory_cgroups([&](const std::string& dir, int64_t room) {
if (room - still - kLockMargin >= need) return true;
*why = fmt("the memory cgroup at %s leaves %s, %s more is still to be allocated, "
"and this wants %s with %s to spare", dir.c_str(),
humanb(room).c_str(), humanb(still).c_str(), humanb(need).c_str(),
humanb(kLockMargin).c_str());
fits = false;
return false;
});
return fits;
}
/* The most lockable_room(need, still, false) admits, and in `limit` the bound that decides it.
* INT64_MAX when no limit can be read. */
static int64_t lockable_bytes(int64_t still, std::string* limit) {
int64_t most = INT64_MAX;
*limit = "no readable memory limit";
if (const int64_t avail = meminfo_bytes("MemAvailable"); avail >= 0) {
most = avail - still - kLockMargin;
*limit = fmt("%s of memory available, less %s still to be allocated and %s to spare",
humanb(avail).c_str(), humanb(still).c_str(), humanb(kLockMargin).c_str());
}
return true;
memory_cgroups([&](const std::string& dir, int64_t room) {
if (room - still - kLockMargin < most) {
most = room - still - kLockMargin;
*limit = fmt("the memory cgroup at %s, which leaves %s, less %s still to be allocated "
"and %s to spare", dir.c_str(), humanb(room).c_str(),
humanb(still).c_str(), humanb(kLockMargin).c_str());
}
return true;
});
return std::max<int64_t>(most, 0);
}
/* The copy is table_copy_make's (core/format/table_copy.h), or for a card, table_copy_fill into
@@ -878,7 +915,47 @@ int Engine::declare() {
{
RadArchProbe pb{};
(void)rad_tools_probe(plugins_, meta_, &pb);
if (pb.gen_rows > 0) {
if (pb.gen_rows > 0 && pb.gen_audio) {
if (!cfg_.given.count("--max-num-batched-tokens")) {
cfg_.max_tok = pb.gen_rows;
decide("--max-num-batched-tokens", std::to_string(cfg_.max_tok),
"an audio generator: a window's denoising step, both branches, and a "
"prompt chunk of half as many rows a branch");
}
if (!cfg_.given.count("--max-num-seqs")) {
cfg_.max_seqs = 8;
decide("--max-num-seqs", "8", "an audio generator: four requests at once, two "
"branches each");
}
if (!cfg_.given.count("--max-model-len") && cfg_.max_ctx == 0) {
cfg_.max_ctx = pb.gen_ctx > 0 ? pb.gen_ctx : pb.gen_rows;
decide("--max-model-len", std::to_string(cfg_.max_ctx),
"an audio generator: the longest prompt and every frame of the longest "
"piece");
}
if (cfg_.mm_max_patches < 0) cfg_.mm_max_patches = 0;
if (cfg_.n_spec < 0) cfg_.n_spec = 0;
cfg_.prefix_cache = false;
} else if (pb.gen_rows > 0 && pb.gen_video) {
if (!cfg_.given.count("--max-num-batched-tokens")) {
cfg_.max_tok = pb.gen_rows;
decide("--max-num-batched-tokens", std::to_string(cfg_.max_tok),
"a video generator: a denoising step carries the prompt, the soundtrack "
"and every patch of the largest, longest video");
}
if (!cfg_.given.count("--max-num-seqs")) {
cfg_.max_seqs = 1;
decide("--max-num-seqs", "1", "a video generator: a pass is one request's");
}
if (!cfg_.given.count("--max-model-len") && cfg_.max_ctx == 0) {
cfg_.max_ctx = pb.gen_rows;
decide("--max-model-len", std::to_string(cfg_.max_ctx),
"a video generator: a step's rows");
}
if (cfg_.mm_max_patches < 0) cfg_.mm_max_patches = 0;
if (cfg_.n_spec < 0) cfg_.n_spec = 0;
cfg_.prefix_cache = false;
} else if (pb.gen_rows > 0) {
if (!cfg_.given.count("--max-num-batched-tokens")) {
cfg_.max_tok = pb.gen_rows;
decide("--max-num-batched-tokens", std::to_string(cfg_.max_tok),
@@ -1308,8 +1385,10 @@ int Engine::plan() {
const int64_t w = probe.state_index_width((int32_t)i);
if (w > 0) kg.g[i].sidx_width = w;
}
f.staging = r->program.is_generator() ? gen::Driver::device_bytes(r->program)
: BatchBuilder::device_bytes(r->program, cfg_, kg);
f.staging = r->program.is_generator() ? gen::Driver::device_bytes(r->program)
: r->program.is_audio_generator() ? gen::AudioDriver::device_bytes(r->program)
: r->program.is_video_generator() ? gen::VideoDriver::device_bytes(r->program)
: BatchBuilder::device_bytes(r->program, cfg_, kg);
if (f.staging < 0) return RAD_E_INVAL;
late_step_bytes_ = std::max(late_step_bytes_, f.staging);
int64_t lazy = r->program.scratch_regions > 1 ? f.queue_bytes : 0;
@@ -1343,8 +1422,12 @@ int Engine::plan() {
facts[i].expert_floor = expert_vram_floor(wfs[i], std::max<int64_t>(room, 0));
}
/* Capped well below overflow, so the sums it joins stay defined: a store that large is
* refused by name in configure_kv. */
const int64_t ck_n = std::max<int64_t>(cfg_.checkpoint_slots, 0), ck_cap = INT64_MAX / 8;
* refused by name in configure_kv. Under --checkpoint-slots auto the store is sized in
* configure_kv from the memory the tables leave, and the tables leave room for the fewest
* slots auto resolves to. */
const int64_t ck_n =
cfg_.checkpoint_slots < 0 ? kCheckpointSlotsFloor : cfg_.checkpoint_slots;
const int64_t ck_cap = INT64_MAX / 8;
const int64_t ck_store = !cfg_.prefix_cache || ck_slot <= 0 ? 0
: ck_n > ck_cap / ck_slot ? ck_cap : ck_slot * ck_n;
RAD_TRY(resolve_table_placement(facts, emb_bytes, wfs, kv_floor, ngram_bytes,
@@ -2658,6 +2741,79 @@ int Engine::load_weights() {
*
* Runs after load, since it takes what the weight pool left, and before Ctx::init, which would
* otherwise resolve every RAD_OPK_KV operand to null. */
/* --checkpoint-slots auto, resolved into cfg_.checkpoint_slots once a slot's size is known
* (checkpoint_slots_auto in core/mem/prefix.h). The store is pinned for the life of the process,
* so it takes at most an eighth of host memory, leaving the rest to the page cache a model's
* mapped tables read through and to the host's other work. It is pinned before the host
* activation arenas and the prefix cache's host tier, so their bytes count as still to come;
* on a card the amdgpu pin cap bounds it too. */
int Engine::size_checkpoint_store(int64_t slot, const char* what) {
if (slot <= 0 || !cfg_.prefix_cache) {
cfg_.checkpoint_slots = 0;
decide("--checkpoint-slots", "0",
slot <= 0 ? "the model keeps no linear or sliding-window state to snapshot"
: "prefix caching is off (--no-prefix-cache)");
return RAD_OK;
}
const int64_t ctx = cfg_.max_ctx ? cfg_.max_ctx : meta_.n_ctx_train;
const int64_t interval = geo_.checkpoint_interval;
const std::unique_ptr<CheckpointPolicy> pol =
make_checkpoint_policy(cfg_.checkpoint_policy, interval);
int64_t still = cfg_.prefix_cache_mib * ((int64_t)1 << 20);
for (const auto& r : ranks_) still += arena_host_bytes(r->program);
std::string limit;
int64_t room = lockable_bytes(still, &limit);
if (!device_is_host()) {
bool lifted = false;
if (const int64_t cap = amdgpu_pin_cap(&lifted); cap > 0) {
int64_t pinned = 0, mapped = 0;
rad_dev_alloc_totals(RAD_MEM_HOST_PINNED, &pinned, nullptr);
rad_dev_alloc_totals(RAD_MEM_HOST_MAPPED, &mapped, nullptr);
const int64_t left = std::max<int64_t>(cap - pinned - mapped - still, 0);
if (left < room) {
room = left;
limit = fmt("the amdgpu driver's pin cap of %s, of which this process holds %s "
"and still pins %s", humanb(cap).c_str(),
humanb(pinned + mapped).c_str(), humanb(still).c_str());
}
}
}
const int64_t total = meminfo_bytes("MemTotal");
const int64_t share = total > 0 ? total / 8 : room;
const CheckpointSlots c = checkpoint_slots_auto(*pol, cfg_.max_seqs, ctx, interval, slot,
share, room);
cfg_.checkpoint_slots = c.slots;
const std::string need =
fmt("%lld a sequence for --max-num-seqs %lld: %s keeps %lld for a %lld-token session at "
"a %lld-token interval, and one more for a running turn", (long long)c.per_seq,
(long long)cfg_.max_seqs, pol->name(), (long long)(c.per_seq - 1), (long long)ctx,
(long long)interval);
std::string bound;
if (c.bound == CheckpointSlots::Bound::Share)
bound = fmt("; %lld wanted, held to an eighth of host memory (%s); --checkpoint-slots N "
"sets more", (long long)c.want, humanb(share).c_str());
else if (c.bound == CheckpointSlots::Bound::Room)
bound = fmt("; %lld wanted, held to what the host can pin: %s", (long long)c.want,
limit.c_str());
decide("--checkpoint-slots", std::to_string(c.slots), need + bound);
if (c.slots == 0) {
RAD_WARN("checkpoint slots: auto finds no room for one %s snapshot of %s (%s), so every "
"prefix hit on this model prefills from the start. Free host memory, or lower "
"--host-pool-mib or --prefix-cache-mib", what, humanb(slot).c_str(),
limit.c_str());
return RAD_OK;
}
const std::string line =
fmt("checkpoint slots: auto: %lld %s snapshot(s) of %s in pinned host memory (%s), none of "
"it on the card; %s%s", (long long)c.slots, what, humanb(slot).c_str(),
humanb(slot * c.slots).c_str(), need.c_str(), bound.c_str());
if (c.bound == CheckpointSlots::Bound::Room) RAD_WARN("%s", line.c_str());
else RAD_INFO("%s", line.c_str());
return RAD_OK;
}
int Engine::configure_kv() {
/* Resolved once, for the cache below and Scheduler::init later (see Engine::geo_). */
RAD_TRY(chunk_geometry_resolve(ranks_[0]->program, cfg_, &geo_));
@@ -2726,9 +2882,11 @@ int Engine::configure_kv() {
shard_off[i] = slot;
slot += ranks_[i]->kv.checkpoint_bytes();
}
const int64_t n = cfg_.checkpoint_slots > 0 ? cfg_.checkpoint_slots : 0;
/* A slot holds linear state or a trunk's window, never both (KVGroupPlan::win_snap). */
const char* what = ranks_[0]->kv.has_window_snapshot() ? "sliding-window" : "linear-state";
const bool sized_auto = cfg_.checkpoint_slots < 0;
if (sized_auto) RAD_TRY(size_checkpoint_store(slot, what));
const int64_t n = cfg_.checkpoint_slots > 0 ? cfg_.checkpoint_slots : 0;
if (slot > 0 && n > 0 && cfg_.prefix_cache) {
/* Pinned all at once and outside every pool. A store larger than the memory left would
* push the process into reclaim, which stalls it without a word; one that cannot be had
@@ -2736,13 +2894,14 @@ int Engine::configure_kv() {
* makes visible. Either stops startup. */
const bool sized = n <= INT64_MAX / slot;
auto refuse = [&](const std::string& reason) {
RAD_ERR("checkpoint slots: %lld %s snapshot(s) of %s are %s of pinned host memory, "
"which %s. Lower --checkpoint-slots (a larger --checkpoint-interval needs "
"fewer for the same context), or pass --checkpoint-slots 0 to serve with "
"no %s snapshot, every prefix hit on this model then prefilling from the "
"start", (long long)n, what, humanb(slot).c_str(),
sized ? humanb(slot * n).c_str() : "more than 8 EiB", reason.c_str(),
what);
RAD_ERR("checkpoint slots: %lld %s snapshot(s)%s of %s are %s of pinned host "
"memory, which %s. Lower --checkpoint-slots (a larger "
"--checkpoint-interval needs fewer for the same context), or pass "
"--checkpoint-slots 0 to serve with no %s snapshot, every prefix hit on "
"this model then prefilling from the start", (long long)n, what,
sized_auto ? " (auto)" : "",
humanb(slot).c_str(), sized ? humanb(slot * n).c_str() : "more than 8 EiB",
reason.c_str(), what);
return RAD_E_NOMEM;
};
if (!sized) return refuse("no host has");
@@ -2750,10 +2909,11 @@ int Engine::configure_kv() {
if (!lockable_room(slot * n, 0, false, &why)) return refuse("does not fit: " + why);
if (ck_store_.open(slot, slot * n) != RAD_OK)
return refuse(std::string("the host did not pin: ") + rad_dev_last_error());
RAD_INFO("checkpoint slots: %lld %s snapshot(s) of %s in pinned host memory (%s), "
"none of it on the card", (long long)n, what, humanb(slot).c_str(),
humanb(ck_store_.cap_bytes()).c_str());
} else if (slot > 0 && cfg_.prefix_cache) {
if (!sized_auto)
RAD_INFO("checkpoint slots: %lld %s snapshot(s) of %s in pinned host memory (%s), "
"none of it on the card", (long long)n, what, humanb(slot).c_str(),
humanb(ck_store_.cap_bytes()).c_str());
} else if (slot > 0 && cfg_.prefix_cache && !sized_auto) {
RAD_INFO("checkpoint slots: --checkpoint-slots 0 keeps no %s snapshot, so every "
"prefix hit on this model prefills from the start", what);
}
@@ -2911,6 +3071,14 @@ int Engine::configure_kv() {
*
* For an image generator the sequence is a conditioning, which its driver refuses at
* admission; warn in those terms. */
if (ranks_[0]->program.is_audio_generator()) {
RAD_WARN("kv group '%s' holds %lld rows: a request needs its prompt and every "
"frame it may make, both branches, up to %lld rows a branch, so a long "
"piece is refused at once rather than cut short. Ask for shorter "
"pieces, use --kv-cache-dtype fp8, or add ranks.",
p->name.c_str(), (long long)cap, (long long)want);
continue;
}
if (ranks_[0]->program.is_generator()) {
RAD_WARN("kv group '%s' holds %lld rows: a conditioning longer than that -- a "
"prompt with its pictures, up to %lld rows -- is refused. A picture "
@@ -3139,8 +3307,8 @@ int Engine::start() {
}
}
/* RUNTIME LoRA: the startup adapters, copied into their slots now that every rank's pools have
* an address and before any step can read them. */
/* Runtime LoRA: the startup adapters, copied into their slots now that every rank's pools
* have an address and before any step can read them. */
RAD_TRY(lora_start());
/* ---- the loan: the cache's idle blocks, lent to the expert slab in place -----------------
+32 -12
View File
@@ -1,23 +1,41 @@
/* engine_gen.cpp -- the image generator's loop: the driver's passes (core/gen/driver.h) run on
* the ranks like token steps, one at a time, each drained before the next.
/* engine_gen.cpp -- a generator's loop: the driver's passes (core/gen/pass.h; driver.h for
* images, audio_driver.h for audio, video_driver.h for video) run on the ranks like token steps, one at a time, each drained
* before the next.
*
* Draining is cheap: a pass is tens to thousands of milliseconds of device work, and the next
* pass depends only on the driver's host bookkeeping, so the wait costs the microseconds of
* building it. Issuing ahead would need a second staging region and a commit protocol.
*/
#include "engine_priv.h"
#include "gen/driver.h"
#include "gen/pass.h"
#include <chrono>
#include <thread>
namespace rad {
/* A generator pass's kind, for the buffer probe's lines. */
static const char* pass_name(int gen) {
switch (gen) {
case RAD_GEN_PASS_COND: return "cond";
case RAD_GEN_PASS_DENOISE: return "denoise";
case RAD_GEN_PASS_DECODE: return "decode";
case RAD_GEN_PASS_PROMPT: return "prompt";
case RAD_GEN_PASS_FRAME: return "frame";
case RAD_GEN_PASS_WINDOW: return "window";
case RAD_GEN_PASS_VOCODE: return "vocode";
case RAD_GEN_PASS_VCOND: return "vcond";
case RAD_GEN_PASS_VSTEP: return "vstep";
case RAD_GEN_PASS_ADECODE: return "adecode";
case RAD_GEN_PASS_VDECODE: return "vdecode";
default: return "";
}
}
int Engine::gen_loop() {
if (rad_dev_set(ranks_[0]->device) < 0)
RAD_ERR("image generator loop: could not bind rank 0's device");
RAD_ERR("generator loop: could not bind rank 0's device");
int step = 0, idle = 0;
const rad_buf img = ranks_[0]->program.generator.image_out;
/* An error ends the driver's requests, then the loop. */
auto stop = [&](int st) {
gen_->shutdown("the engine stopped on an error and is not serving", st);
@@ -43,15 +61,17 @@ int Engine::gen_loop() {
rad_strerror(st));
return stop(st);
}
/* A decode pass's image, copied behind it on rank 0's stream; every rank holds the same
* pixels. */
if (const int64_t n = gen_->decode_bytes(); n > 0) {
const void* src = ranks_[0]->ctx.buf_ptr(img);
/* What the pass leaves for the host (an image, a window's samples, the frames' status),
* copied behind it on rank 0's stream; every rank holds the same values. */
for (const gen::IPassDriver::Readback& r : gen_->readbacks()) {
if (st < 0 || r.bytes <= 0) continue;
const void* src = ranks_[0]->ctx.buf_ptr(r.buf);
if (!src) {
RAD_ERR("the generator's image buffer was declared but never planned");
RAD_ERR("the generator's output buffer '%s' was declared but never planned",
ranks_[0]->program.buffers[r.buf].name.c_str());
return stop(RAD_E_STATE);
}
st = rad_memcpy_async(gen_->host_image(), src, n, ranks_[0]->ctx.stream());
st = rad_memcpy_async(r.host, src, r.bytes, ranks_[0]->ctx.stream());
}
for (auto& rk : ranks_)
if (st >= 0) st = rad_stream_sync(rk->ctx.stream());
@@ -59,7 +79,7 @@ int Engine::gen_loop() {
RAD_ERR("generator pass %d: the device failed: %s", step, rad_strerror(st));
return stop(st);
}
dump_buffers(ranks_[0]->ctx, step);
dump_buffers(ranks_[0]->ctx, step, pass_name(b->gen));
gen_->done();
++step;
}
+40 -25
View File
@@ -1,10 +1,10 @@
/* engine_lora.cpp -- runtime LoRA on the engine side: which modules adapters may target (fixed
* before declare), and loading an adapter into a slot of every rank's pools.
*
* A LOAD IS: pack the adapter for each rank (lora::load_adapter, host only), refuse a module no
* rank placed, copy each rank's bytes into the slot on a stream of its own, wait, and only then
* publish the name. A request can name the adapter only after the publish, so no step ever reads
* a slot while it is being written; a slot no published adapter holds is never referenced. */
* A load packs the adapter for each rank (lora::load_adapter, host only), refuses a module no rank
* placed, copies each rank's bytes into the slot on a stream of its own, waits, and only then
* publishes the name. A request can name the adapter only after the publish, so no step reads a
* slot while it is written. */
#include "engine_priv.h"
#include "lora/lora.h"
@@ -54,13 +54,8 @@ int read_targets(const std::string& dir, std::set<std::string>* out, std::string
int Engine::lora_targets() {
if (!cfg_.lora.enabled()) return RAD_OK;
lora_targets_ = cfg_.lora.targets;
lora_targets_ = std::set<std::string>(cfg_.lora.targets.begin(), cfg_.lora.targets.end());
if (lora_targets_.empty()) {
if (cfg_.lora.adapters.empty()) {
RAD_ERR("lora: --max-loras with no --lora names no module an adapter may target; give "
"them with --lora-target-modules (q_proj,k_proj,v_proj,o_proj,...)");
return RAD_E_INVAL;
}
for (const auto& [name, dir] : cfg_.lora.adapters) {
std::string err;
const int s = read_targets(dir, &lora_targets_, &err);
@@ -70,13 +65,6 @@ int Engine::lora_targets() {
}
}
}
std::set<std::string> seen;
for (const auto& [name, dir] : cfg_.lora.adapters) {
if (!seen.insert(name).second) {
RAD_ERR("lora: two adapters are named '%s'", name.c_str());
return RAD_E_INVAL;
}
}
lora_table_.reset(cfg_.lora.slots(), &lora_epoch_);
return RAD_OK;
}
@@ -92,6 +80,35 @@ int Engine::lora_start() {
t.c_str());
return RAD_E_UNSUPPORTED;
}
/* Every target is a module some rank carries adapters on. A leaf the model lacks, or holds
* only outside the trunk (embedding, lm_head, a tower, the drafter), would target nothing. */
{
std::set<std::string> carried;
for (const auto& r : ranks_)
for (const lora::Site& site : r->lora_sites)
for (const lora::SiteSource& src : site.sources)
if (src.targeted) carried.insert(src.module.substr(src.module.rfind('.') + 1));
for (const std::string& x : lora_targets_)
if (!carried.count(x)) {
RAD_ERR("lora: the target module '%s' is no trunk linear of this model, so no "
"adapter could land on it; leave it out of --lora-target-modules (or of "
"the adapters' target_modules)", x.c_str());
return RAD_E_UNSUPPORTED;
}
}
/* The adapter ops run in their GEMM's domain and read the pools on the card, so a targeted
* GEMM placed on the host could serve no adapter request. On the host backend every op and
* the pools are in host memory. */
if (!device_is_host())
for (const auto& r : ranks_)
for (const LoraIssueSite& site : r->program.lora_sites)
if (r->ctx.op_domain((rad_op)site.gemm) != RAD_DOMAIN_DEVICE) {
RAD_ERR("lora: rank %d: the GEMM over '%s' is placed on the host, and its "
"adapter ops read pools on the card; keep the targeted weights in "
"VRAM or leave the module out of --lora-target-modules", r->index,
r->program.lora_pools[(size_t)site.pool].weight.c_str());
return RAD_E_UNSUPPORTED;
}
{
const Program& P = ranks_[0]->program;
int64_t slot_bytes = 0;
@@ -118,12 +135,10 @@ int Engine::lora_load(const std::string& name, const std::string& dir, std::stri
std::lock_guard<std::mutex> lk(lora_mu_);
if (!cfg_.lora.enabled()) { *err = "the engine was started without adapters"; return RAD_E_STATE; }
if (name.empty()) { *err = "an adapter needs a name"; return RAD_E_INVAL; }
/* A SLOT FREED A MOMENT AGO IS WAITED FOR HERE, not handed back as a retry. It is reusable once
* the step loop has gone round three times (a pass issued ahead may still read it), and the
* loop goes round idle or busy, so that is milliseconds -- an unload followed at once by a load
* (a hot swap) would otherwise fail almost every time under traffic. Only other loads wait on
* lora_mu_ meanwhile; requests and unloads go to the table, and the step loop's counter is an
* atomic. */
/* A slot that is still cooling (lora/slots.h) is waited for here rather than answered with a
* retry: the step loop goes round idle or busy, so the wait is milliseconds, and a hot swap
* (unload, then load at once) would otherwise fail under traffic. Only other loads wait on
* lora_mu_ meanwhile; requests and unloads use the table alone. */
const auto give_up = std::chrono::steady_clock::now() + std::chrono::seconds(2);
int slot = -1;
for (;;) {
@@ -174,8 +189,8 @@ int Engine::lora_load(const std::string& name, const std::string& dir, std::stri
char* ds = (char*)P.buffers[lp.scale].ptr;
if (!da || !db || !ds) { rc = RAD_E_STATE; *err = "a pool has no address"; break; }
da += (int64_t)slot * ab; db += (int64_t)slot * bb; ds += (int64_t)slot * sb;
/* A pool this adapter does not touch is ZEROED, not left: the bytes are whatever the
* last adapter in the slot or the arena held, and a scale of 0 times a NaN is a NaN. */
/* A pool this adapter does not touch is zeroed, not left as it was: the bytes are what
* the slot's last adapter or the arena held, and a scale of 0 times a NaN is a NaN. */
if (ps.empty) {
if (rad_memset_async(da, 0, ab, st) < 0 || rad_memset_async(db, 0, bb, st) < 0 ||
rad_memset_async(ds, 0, sb, st) < 0)
+1 -1
View File
@@ -34,7 +34,7 @@ struct Engine::Rank {
int index = 0;
int device = 0;
Program program; /* declare runs once per rank: dimensions are already divided */
/* RUNTIME LoRA: this rank's sites (core/lora/lora.h), the loader's map from an adapter's
/* Runtime LoRA: this rank's sites (core/lora/lora.h), the loader's map from an adapter's
* modules to this rank's slot bytes. Empty with LoRA off. */
std::vector<lora::Site> lora_sites;
Plan plan;
+19 -3
View File
@@ -7,6 +7,7 @@
#include "device/device.h"
#include "rad_plugin.h"
#include <cstdio>
#include <cstring>
#include <cstdint>
#include <cstdlib>
@@ -21,7 +22,10 @@ namespace rad {
*
* RADIANCE_DUMP_BUF names declared buffers (comma separated); every step prints the first row of
* each: mean, largest magnitude and first four elements. RADIANCE_DUMP_HEAD=<n> adds the first n
* elements verbatim (integers included); RADIANCE_DUMP_TOPK=<k> adds the k largest.
* elements verbatim (integers included); RADIANCE_DUMP_TOPK=<k> adds the k largest. A name may
* carry a row count, `frame.mix:100`, to read that many rows as one (a code-major plane holds one
* code a row). RADIANCE_DUMP_DIR=<dir> also writes each read's raw bytes to
* <dir>/<step>-<phase>-<name>.bin, for a comparison against another implementation's tensors.
*
* It shows tensors inside a step, which neither rad-kbench (one op at a time) nor --debug-graph
* (what was declared) can. An environment variable at -vv only, because it adds a device-to-host
@@ -70,6 +74,13 @@ static void dump_row(int step, const char* phase, const char* name, uint32_t dty
uint64_t h = 1469598103934665603ull;
for (size_t i = 0; i < raw.size(); ++i) { h ^= raw[i]; h *= 1099511628211ull; }
const int64_t good = cnt - bad;
if (const char* dir = std::getenv("RADIANCE_DUMP_DIR"); dir && *dir) {
const std::string path = fmt("%s/%d-%s-%s.bin", dir, step, phase, name);
if (FILE* f = std::fopen(path.c_str(), "wb")) {
std::fwrite(raw.data(), 1, raw.size(), f);
std::fclose(f);
}
}
RAD_TRACE("step %d%-8s %-28s %-5s n=%lld hash %016llx mean %.6f amax %.5f "
"nonfinite %lld%s [%.6f %.6f %.6f %.6f]",
step, phase, name, rad_dtype_name(dtype), (long long)cnt, (unsigned long long)h,
@@ -159,8 +170,13 @@ void dump_buffers(Ctx& ctx, int step, const char* phase) {
for (const char* s = names; *s; ) {
const char* e = s;
while (*e && *e != ',') ++e;
const std::string want(s, (size_t)(e - s));
std::string want(s, (size_t)(e - s));
s = *e ? e + 1 : e;
int64_t rows = 1;
if (const size_t colon = want.find(':'); colon != std::string::npos) {
rows = std::max<long long>(1, std::strtoll(want.c_str() + colon + 1, nullptr, 10));
want.resize(colon);
}
if (want.empty()) continue;
/* Weights match the same names, to check that the loader put the right checkpoint tensor
@@ -188,7 +204,7 @@ void dump_buffers(Ctx& ctx, int step, const char* phase) {
const int64_t row = b.decl.rank >= 1 ? b.bytes / (b.decl.shape[0] ? b.decl.shape[0] : 1)
: b.bytes;
done = dump_at(ctx, step, phase, b.name, b.decl.dtype, ptr,
std::min<int64_t>(row, dump_cap()));
row <= dump_cap() ? std::min<int64_t>(row * rows, b.bytes) : dump_cap());
}
}
}
+791 -111
View File
File diff suppressed because it is too large. Load diff
+79 -17
View File
@@ -17,8 +17,8 @@
* convert time.
*
* An imported quantisation's descriptor (`auto-round`, `gptq`, `quark`, `compressed-tensors`,
* `paroquant`) names the tool, not a served form, so no plugin claims it; Checkpoint::imports()
* describes how the plugin is chosen.
* `paroquant`, `modelopt`) names the tool, not a served form, so no plugin claims it;
* Checkpoint::imports() describes how the plugin is chosen.
*/
#pragma once
#include "../rad_internal.h"
@@ -31,6 +31,7 @@
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
namespace rad {
@@ -54,12 +55,16 @@ struct SrcTensor {
* scale row covers. 0 for other tensors. */
int32_t gptq_bits = 0;
int64_t gptq_group = 0;
/* CT-INT4 (compressed-tensors' symmetric pack-quantized int4): `data` is X.weight_packed's
* int32 words [N, K / 8], eight codes per word along K from the low bits up, unsigned with zero
* point 8. The tensor described is the logical [N, K] code matrix, `rad_dtype` RAD_I4;
* `ct_group` is the K columns one scale of X.weight_scale [N, K / group] covers. 0 for other
* tensors. */
/* CT-INT4 (compressed-tensors' pack-quantized int4): `data` is X.weight_packed's int32 words
* [N, K / 8], eight codes per word along K from the low bits up, each the signed code plus 8.
* The tensor described is the logical [N, K] code matrix, `rad_dtype` RAD_I4 (symmetric) or
* RAD_U4 (asymmetric, the stored nibbles); `ct_group` is the K columns one scale of
* X.weight_scale [N, K / group] covers. 0 for other tensors. */
int64_t ct_group = 0;
/* An asymmetric CT-INT4 weight's X.weight_zero_point: int32 [ceil(N / 8), G], eight zero
* points per word along N from the low bits up, each the signed zero point plus 8
* (compressed-tensors packs it along dim 0). Null for a symmetric weight. */
const SrcTensor* ct_zero = nullptr;
/* ParoQuant's int5-bitplane (Import::ParoI5): `data` is the AWQ-packed low nibbles qweight
* [K, N/8] and the tensor described is the logical [N, K] u5 code matrix; `aux` are the fifth-bit
* plane qweight_hi [K, N/32], and the zero points qzeros [G, N/8] and qzeros_hi [G, N/32].
@@ -131,6 +136,9 @@ public:
/* Sub-tensor `index` along dim 0 of a stacked (rank >= 2) tensor, as a view owned here and
* valid for the checkpoint's life. Null, with the reason logged, if there is no such slice. */
const SrcTensor* slice(const SrcTensor& st, int index, const char* declared);
/* Rows [r0, r0 + n) along dim 0 of a plainly stored tensor, as a view owned here (a
* RAD_MAP_ROWS piece). Null, with the reason logged, when the rows are not there. */
const SrcTensor* rows(const SrcTensor& st, int64_t r0, int64_t n, const char* declared);
/* FP8's block, from quantization_config.weight_block_size; 128x128 when it says nothing. */
int64_t fp8_block_rows() const { return fp8_br_; }
@@ -141,21 +149,24 @@ public:
* (zero point stored less one). QuarkMx: Quark's MXFP4 (fp4 weights, per_group 32, e8m0
* scales, no per-layer overrides). ParoMx: ParoQuant's `paroquant_mxfp4` (Quark's codes and
* exponents in a rotated basis, rotations beside them). CtInt4, Nvfp4, CtFp8:
* compressed-tensors' pack-quantized int4, a release with an nvfp4-pack-quantized group, and
* one whose groups are all float-quantized FP8 (detect_import). In an Nvfp4 or CtFp8 release
* every weight without the NVFP4 tensors reads stock, so FP8 and bf16 linears beside the
* NVFP4 ones read by their own form. An unreadable form of these stays None, with the reason
* in import_refusal(). The quantization_config keys are then renamed
* `imported_quantization_config.*`, since they describe the tool, not a served format. */
enum class Import { None, Gptq, QuarkMx, CtInt4, ParoMx, ParoI5, ParoI4, Nvfp4, CtFp8 };
* compressed-tensors' pack-quantized int4 (symmetric, or asymmetric with a zero point), a
* release with an nvfp4-pack-quantized group, and one whose groups are all float-quantized FP8
* (detect_import). ModelOpt: NVIDIA ModelOpt's NVFP4, FP8, or both per layer
* (MIXED_PRECISION). In an Nvfp4, CtFp8 or ModelOpt release every weight without the NVFP4
* tensors reads stock, so FP8 and bf16 linears beside the NVFP4 ones read by their own form.
* An unreadable form of these stays None, with the reason in import_refusal(). The
* quantization_config keys are then renamed `imported_quantization_config.*`, since they
* describe the tool, not a served format. */
enum class Import { None, Gptq, QuarkMx, CtInt4, ParoMx, ParoI5, ParoI4, Nvfp4, CtFp8,
ModelOpt };
Import imports() const { return import_; }
const std::string& import_refusal() const { return import_why_; }
/* The pieces an imported `name` (a `.weight`) is read from, as views owned here: GPTQ-packed
* codes and their scales, Quark's codes and exponents as RAD dtypes, or NVFP4's codes as fp4
* beside an f32 scale plane derived from the e4m3 scales and the global scale. RAD_E_NOTFOUND
* when `name` is an ordinary tensor or absent; another error, with `why`, for an unreadable
* imported form. */
* beside an f32 scale plane derived from the e4m3 scales and the second level (a divisor in
* compressed-tensors, a multiplier in ModelOpt). RAD_E_NOTFOUND when `name` is an ordinary
* tensor or absent; another error, with `why`, for an unreadable imported form. */
int import_piece(const std::string& name, const SrcTensor** codes, const SrcTensor** scale,
std::string* why);
@@ -166,6 +177,7 @@ private:
const std::unordered_map<std::string, std::string>* owner = nullptr);
int open_safetensors(const std::string& path);
int open_diffusers();
int add_companions();
int open_gguf(const std::string& path);
void detect_import();
@@ -185,11 +197,27 @@ private:
Import import_ = Import::None;
std::string import_why_;
int64_t ct_group_ = 0; /* CtInt4: the group every weight's config states */
bool ct_asym_ = false; /* CtInt4: the config states asymmetric weights */
/* import_piece's answers by name, so a weight resolved twice reuses its views. */
std::unordered_map<std::string, std::pair<const SrcTensor*, const SrcTensor*>> imported_;
};
/* ================================================================== logical weights */
/* Another spelling of the numbers a weight ships, asked for by a recipe's `import` rule
* (ckpt_import_form). Each field left at its default keeps that part as the import writes it.
*
* codes an unsigned dtype of the shipped codes' width: a symmetric grid's signed codes c are
* written c + 2^(bits-1) under a zero point of 2^(bits-1), so (u - z) * s == c * s;
* zero the zero plane's dtype (a shipped or re-expressed zero point), which must hold it;
* scale the scale plane's dtype, each shipped scale rounded to nearest (counted when that
* changes it);
* block a scale shipped once per row or per tensor (FP8) repeated over this block grid,
* which every block's rows must share. */
struct ImportForm {
uint32_t codes = RAD_DT_INVALID, zero = RAD_DT_INVALID, scale = RAD_DT_INVALID;
int64_t block[2] = { 0, 0 };
};
/* A declared weight's source, as the name map resolves it: pieces joined along `concat_dim`, and
* for block-scaled FP8 each piece's scale plane beside it. */
struct CkptWeight {
@@ -216,6 +244,22 @@ struct CkptWeight {
* piece (a row part: gate and up, or q, k and v, each rotated separately). */
bool paro = false;
std::vector<const SrcTensor*> pq_pairs, pq_theta, pq_scale;
/* A weight-normalised tensor (RAD_MAP_WNORM): `pieces` is its direction v alone, and every
* element of v with first index i reads times wnorm_scale[i] = g_i / ||v_i||. Not trivial
* (the values change), so a recipe rule stores it. */
bool wnorm = false;
std::vector<float> wnorm_scale;
/* A weight computed from its sources at resolve (RAD_MAP_TRANSPOSE, RAD_MAP_EMA): its f32
* values in the logical shape, which ckpt_rows_f32 serves. Not trivial, so a recipe rule
* stores it. */
std::vector<float> derived;
/* An `import` rule's form, applied by ckpt_plane_rows (also `imported`). `rounded` counts the
* shipped scales `form.scale` does not hold exactly and `max_rel` is their largest relative
* change, both found by ckpt_import_form. */
bool reform = false;
ImportForm form{};
int64_t rounded = 0;
double max_rel = 0;
RadEncoding enc{};
std::string why;
};
@@ -226,6 +270,24 @@ struct CkptWeight {
int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, bool optional,
CkptWeight* out, std::string* why);
/* The quantiser name of a recipe rule rad-convert handles itself through ckpt_import_form. */
constexpr const char* kImportRule = "import";
/* An import rule's options (codes=DTYPE, zero=DTYPE, scale=DTYPE, block=RxC) as an ImportForm.
* RAD_E_INVAL, with the option named in `why`, for an option it does not take or a value it
* cannot read. */
int ckpt_import_form_parse(const std::vector<std::pair<std::string, std::string>>& options,
ImportForm* f, std::string* why);
/* Re-express a resolved `w` as `f` asks (a recipe's `import` rule): RAD_OK with `w->enc` the new
* encoding and the form recorded for ckpt_plane_rows. RAD_E_UNSUPPORTED, with `why`, when `w` is
* a plain float weight with nothing shipped to re-express (the rule declines it); any other error,
* with `why`, when its shipped form cannot take `f`: a form other than an integer grid (GPTQ,
* CT-INT4) or an FP8 weight with one scale per row or per tensor, a code or zero dtype that does
* not hold the shipped values, or a block whose rows carry different scales. Rounding a scale to
* `f.scale` is allowed and counted in `w->rounded`. */
int ckpt_import_form(CkptWeight* w, const ImportForm& f, std::string* why);
/* The checkpoint tensor a piece or scale reads: its name without the "[index]" a slice of a
* stacked tensor carries, so an expert reads the stack it was cut from. */
std::string ckpt_tensor_of(const SrcTensor& t);
+41 -2
View File
@@ -55,7 +55,42 @@ int weight_share(const WeightInfo& w, const RadEncoding& enc, uint32_t rank, con
"RAD_SHARD_NONE", w.decl.shard == RAD_SHARD_ROW ? "ROW" : "COL",
rank));
const bool cols = w.decl.shard == RAD_SHARD_COL || rank == 1;
if (cols) {
const int np1 = rank == 1 && w.decl.n_row_parts > 1 ? w.decl.n_row_parts : 1;
if (cols && np1 > 1) {
/* A rank-1 weight of stacked parts (a fused projection's bias, [value | gate]) is cut
* as the matrix it goes with: this rank's slice of each part, never a contiguous
* slice of the stack. Per-part spans and declared parts read as the row cut's do. */
if (w.n_part_spans > 0) {
if (w.n_part_spans != np1)
return refuse(fmt("%d per-part spans for %d stacked parts", w.n_part_spans, np1));
int64_t sum = 0, soff = 0;
for (int g = 0; g < np1; ++g) sum += w.part_total[g];
if (sum != VC)
return refuse(fmt("the %d stacked parts' stated elements sum to %lld and the "
"entry has %lld", np1, (long long)sum, (long long)VC));
for (int g = 0; g < np1; ++g) {
view.push_back({ 0, VR, soff + w.part_lo[g], soff + w.part_hi[g] });
soff += w.part_total[g];
}
} else {
if (span)
return refuse("a single span over a rank-1 weight of stacked parts is not "
"defined; state one span a part");
if (VC % world) return refuse(fmt("%lld elements do not divide by %d ranks",
(long long)VC, world));
int64_t sum = 0, soff = 0;
for (int g = 0; g < np1; ++g) sum += w.decl.row_parts[g];
if (sum != VC / world)
return refuse(fmt("%d declared parts sum to %lld, and the rank's share of %lld "
"elements at %d ranks is %lld", np1, (long long)sum,
(long long)VC, world, (long long)(VC / world)));
for (int g = 0; g < np1; ++g) {
const int64_t take = w.decl.row_parts[g];
view.push_back({ 0, VR, soff + index * take, soff + (index + 1) * take });
soff += take * world;
}
}
} else if (cols) {
int64_t c0 = w.shard_lo, c1 = w.shard_hi;
if (!span) {
if (VC % world) return refuse(fmt("%lld columns do not divide by %d ranks",
@@ -162,7 +197,11 @@ int weight_share(const WeightInfo& w, const RadEncoding& enc, uint32_t rank, con
s.rows += pq.rows;
s.cols = pq.cols;
}
if (s.rows != w.sel_rows[k] || s.cols != w.sel_cols[k])
/* A vector's stacked parts come out as one piece a part, each a row of the share; laid
* end to end they are the declared vector, so only the element count has to agree. */
const bool fits = rank == 1 ? s.rows * s.cols == w.sel_rows[k] * w.sel_cols[k]
: s.rows == w.sel_rows[k] && s.cols == w.sel_cols[k];
if (!fits)
return refuse(fmt("this rank's share of the '%s' plane is [%lld, %lld] and the "
"declaration says [%lld, %lld]", p.role, (long long)s.rows,
(long long)s.cols, (long long)w.sel_rows[k],
+76
View File
@@ -0,0 +1,76 @@
/* audio.h -- audio generation: the request and the channel its audio comes back on.
*
* An audio generator (abi/rad_builder.h, rad_declare_audio_generator) makes a piece in two stages,
* a language model writing it frame by frame and a denoiser turning runs of frames (windows) into
* audio, which a vocoder plays. core/gen/audio_driver.h turns a request into those passes; this is
* what a caller hands it and what it hands back: a window's samples as each is vocoded, then the
* end.
*/
#pragma once
#include "rad_core.h"
#include <atomic>
#include <condition_variable>
#include <deque>
#include <memory>
#include <mutex>
#include <string>
#include <vector>
namespace rad {
namespace gen {
/* One window's playable samples, interleaved, in [-1, 1]. */
struct AudioChunk {
int32_t window = 0;
std::vector<float> samples;
};
/* As Ticket (gen.h) is for an image: the driver thread writes, the caller reads. */
class AudioTicket {
public:
/* driver side */
void push(AudioChunk&& c);
void finish(int status, const std::string& why = std::string());
/* caller side: the next chunk, or false once the request has ended and every chunk was
* taken. Waits at most `ms` milliseconds; `*timed_out` marks a false that was a timeout. */
bool next(AudioChunk* out, int ms, bool* timed_out);
bool finished() const;
int status() const;
std::string why() const;
std::atomic<bool> cancel{false};
/* Usage for the response, written by the driver before finish(): prompt tokens, frames made,
* windows played and per-phase times. */
int64_t in_tokens = 0, frames = 0, windows = 0;
int64_t t_submit_ns = 0, t_prompt_ns = 0, t_frames_ns = 0, t_first_audio_ns = 0,
t_done_ns = 0;
/* Why the piece ended: the model ended it, or it reached the request's length. */
bool model_ended = false;
private:
mutable std::mutex mu_;
std::condition_variable cv_;
std::deque<AudioChunk> q_;
bool done_ = false;
int status_ = RAD_OK;
std::string why_;
};
struct AudioRequest {
/* The conditional prompt, and the unconditional one when the declaration renders it from a
* template of its own (RadAudioGenDecl::neg_tmpl); otherwise it is derived from the
* conditional prompt as the declaration says (neg_token), and `neg_tokens` is empty. */
std::vector<int32_t> tokens;
std::vector<int32_t> neg_tokens;
int64_t max_frames = 0; /* the most frames to make, >= 1 */
int32_t steps = 0; /* 0: the model's default */
float cfg = 0.0f; /* 0: the model's default */
uint64_t seed = 0;
std::shared_ptr<AudioTicket> ticket;
};
} /* namespace gen */
} /* namespace rad */
+910
View File
@@ -0,0 +1,910 @@
/* audio_driver.cpp -- the audio generator's pass driver (audio_driver.h), and the ticket a caller
* waits on (audio.h). */
#include "audio_driver.h"
#include "sched/mem_iface.h"
#include <algorithm>
#include <chrono>
#include <cstring>
namespace rad {
namespace gen {
/* ================================================================== the ticket */
void AudioTicket::push(AudioChunk&& c) {
{
std::lock_guard<std::mutex> lk(mu_);
q_.push_back(std::move(c));
}
cv_.notify_all();
}
void AudioTicket::finish(int status, const std::string& why) {
{
std::lock_guard<std::mutex> lk(mu_);
if (done_) return;
done_ = true;
status_ = status;
why_ = why;
}
cv_.notify_all();
}
bool AudioTicket::next(AudioChunk* out, int ms, bool* timed_out) {
std::unique_lock<std::mutex> lk(mu_);
if (timed_out) *timed_out = false;
if (q_.empty() && !done_)
cv_.wait_for(lk, std::chrono::milliseconds(ms), [this] { return !q_.empty() || done_; });
if (!q_.empty()) {
*out = std::move(q_.front());
q_.pop_front();
return true;
}
if (!done_ && timed_out) *timed_out = true;
return false;
}
bool AudioTicket::finished() const {
std::lock_guard<std::mutex> lk(mu_);
return done_ && q_.empty();
}
int AudioTicket::status() const {
std::lock_guard<std::mutex> lk(mu_);
return status_;
}
std::string AudioTicket::why() const {
std::lock_guard<std::mutex> lk(mu_);
return why_;
}
/* ================================================================== sizing */
namespace {
constexpr int64_t kAlign = 256;
int64_t align_up(int64_t v) { return (v + kAlign - 1) / kAlign * kAlign; }
struct Sizes {
int64_t T = 0, S = 0, L = 0, NB = 0;
};
Sizes sizes_of(const Program& prog, int64_t block_size) {
const RadAudioGenDecl& d = prog.audio_gen;
Sizes z;
z.T = prog.ctx.max_tok;
z.S = prog.ctx.max_seqs;
z.L = d.max_lanes;
z.NB = block_size > 0 ? (AudioDriver::max_seq_rows(d) + block_size - 1) / block_size : 0;
return z;
}
/* Region offsets and sizes, in order, and the total; shared by the allocation and the VRAM budget.
* The order is the enum's in audio_driver.h. */
int64_t carve(const Sizes& z, int64_t (*bytes)[2], int n) {
const int64_t I = 4;
const int64_t SL = std::max(z.S, z.L);
const int64_t want[] = {
z.T * I, /* R_TOK */
z.T * I, /* R_POS */
(z.S + 1) * I, /* R_CU */
z.T * I, /* R_SLOT */
z.S * z.NB * I, /* R_BT */
z.S * I, /* R_USED */
z.L * I, /* R_LANE */
z.L * I, /* R_LAST */
z.L * I, /* R_FRAME */
2 * SL * I, /* R_SEED */
z.S * 4, /* R_T */
z.S * 4, /* R_TN */
z.S * 4, /* R_CFG */
z.S * I, /* R_PAIR */
z.S * I, /* R_WLANE */
z.S * I, /* R_FLAGS */
z.S * I, /* R_WIDX */
z.S * I, /* R_WF0 */
z.S * I, /* R_WNF */
(z.S + 1) * I, /* R_LCU */
z.T * I, /* R_LSRC */
z.S * I, /* R_ESLOT */
z.S * I, /* R_LROW */
z.S * I, /* R_PREFIX */
};
int64_t off = 0;
for (int r = 0; r < n; ++r) {
bytes[r][0] = off;
bytes[r][1] = want[r];
off = align_up(off + want[r]);
}
return off;
}
} /* namespace */
int64_t AudioDriver::device_bytes(const Program& prog) {
if (!prog.is_audio_generator() || prog.kv_groups.size() < 2) return 0;
const Sizes z = sizes_of(prog, prog.kv_groups[1].block_size);
int64_t b[R_N][2];
return carve(z, b, R_N);
}
int AudioDriver::init(const Program& prog, IKVManager* kv, const std::vector<RankIO>& ranks) {
fini();
if (!prog.is_audio_generator()) return RAD_E_STATE;
decl_ = prog.audio_gen;
name_ = prog.agen_str.name;
kv_ = kv;
ranks_ = ranks;
/* The language model's KV, both branches of every lane: one paged full-attention group. */
if (prog.kv_groups.size() != 2 || prog.kv_groups[1].decl.kind != RAD_KV_FULL ||
prog.kv_groups[1].block_size <= 0) {
RAD_ERR("audio generator: the program declares %zu KV group(s); the driver stages exactly "
"one full-attention group, the language model's", prog.kv_groups.size() - 1);
return RAD_E_UNSUPPORTED;
}
kv_group_ = 1;
block_size_ = prog.kv_groups[1].block_size;
const Sizes z = sizes_of(prog, block_size_);
max_tok_ = z.T;
max_seqs_ = z.S;
max_blocks_ = z.NB;
neg_own_ = !prog.agen_str.neg_tmpl.empty();
/* A FRAME pass carries both branches of every lane; a window's step at least one window, a
* chunk's vocode its frames and their context, and a whole prompt both its branches. */
const int64_t step_rows = chunked() ? decl_.voc_context + decl_.voc_chunk
: 2 * (decl_.win_lead + win_latents(decl_.win_frames));
const int64_t prompt_rows = decl_.prompt_whole ? 2 * decl_.max_prompt : 2;
if (max_seqs_ < 2 * decl_.max_lanes || max_tok_ < 2 * decl_.max_lanes ||
max_tok_ < step_rows || max_tok_ < prompt_rows) {
RAD_ERR("audio generator: a pass carries %lld rows of %lld sequences; '%s' needs %lld "
"sequences for its %lld lanes, %lld rows for a %s and %lld for a whole prompt",
(long long)max_tok_, (long long)max_seqs_, name_.c_str(),
(long long)(2 * decl_.max_lanes), (long long)decl_.max_lanes,
(long long)step_rows, chunked() ? "chunk's vocode" : "window's step",
(long long)prompt_rows);
return RAD_E_UNSUPPORTED;
}
int64_t b[R_N][2];
bytes_ = carve(z, b, R_N);
for (int r = 0; r < R_N; ++r) { reg_[r].off = b[r][0]; reg_[r].bytes = b[r][1]; reg_[r].used = 0; }
host_ = static_cast<char*>(rad_dev_alloc(bytes_, RAD_MEM_HOST_PINNED));
status_host_ = static_cast<int32_t*>(rad_dev_alloc(decl_.max_lanes * 4, RAD_MEM_HOST_PINNED));
audio_bytes_ = (chunked() ? decl_.voc_chunk : win_latents(decl_.win_frames)) *
decl_.samples_per_latent * decl_.channels * 4;
audio_host_ = static_cast<float*>(rad_dev_alloc(audio_bytes_, RAD_MEM_HOST_PINNED));
if (!host_ || !status_host_ || !audio_host_) {
RAD_ERR("audio generator: no pinned host memory for the pass staging (%lld + %lld bytes)",
(long long)bytes_, (long long)audio_bytes_);
return RAD_E_NOMEM;
}
std::memset(host_, 0, (size_t)bytes_);
dev_.assign(ranks_.size(), nullptr);
for (size_t r = 0; r < ranks_.size(); ++r) {
RAD_TRY(rad_dev_set(ranks_[r].device));
dev_[r] = rad_dev_alloc(bytes_, RAD_MEM_DEVICE);
if (!dev_[r]) {
RAD_ERR("audio generator: rank %zu has no room for the pass staging (%lld bytes)", r,
(long long)bytes_);
return RAD_E_NOMEM;
}
}
if (!ranks_.empty()) RAD_TRY(rad_dev_set(ranks_[0].device));
out_.assign(ranks_.size(), RadBatch{});
aout_.assign(ranks_.size(), RadAudioGenBatch{});
kout_.assign(ranks_.size(), RadKVGroupBatch{});
free_lanes_.clear();
for (int64_t i = decl_.max_lanes - 1; i >= 0; --i) free_lanes_.push_back((int32_t)i);
return RAD_OK;
}
void AudioDriver::fini() {
for (size_t r = 0; r < dev_.size(); ++r)
if (dev_[r]) {
if (r < ranks_.size()) rad_dev_set(ranks_[r].device);
rad_dev_free(dev_[r], RAD_MEM_DEVICE);
}
dev_.clear();
if (!ranks_.empty()) rad_dev_set(ranks_[0].device);
if (host_) rad_dev_free(host_, RAD_MEM_HOST_PINNED);
if (status_host_) rad_dev_free(status_host_, RAD_MEM_HOST_PINNED);
if (audio_host_) rad_dev_free(audio_host_, RAD_MEM_HOST_PINNED);
host_ = nullptr;
status_host_ = nullptr;
audio_host_ = nullptr;
}
/* ================================================================== requests */
int AudioDriver::submit(std::unique_ptr<AudioRequest> r, std::string* why) {
if (!r || !r->ticket) return RAD_E_INVAL;
const RadAudioGenDecl& d = decl_;
auto no = [&](const std::string& w) {
if (why) *why = w;
return RAD_E_INVAL;
};
const int64_t T = (int64_t)r->tokens.size(), Tn = (int64_t)r->neg_tokens.size();
if (!neg_own_ && T <= d.neg_keep_head + d.neg_keep_tail)
return no("the prompt is " + std::to_string(T) + " tokens, too short to hold its own "
"markers");
if (T < 1 || std::max(T, Tn) > d.max_prompt)
return no("the prompt is " + std::to_string(std::max(T, Tn)) + " tokens; this model takes "
"1.." + std::to_string(d.max_prompt));
if (r->max_frames < 1 || r->max_frames > d.max_frames)
return no("the length must be 1.." + std::to_string(d.max_frames) + " frames (" +
std::to_string(d.max_frames * d.frame_rate_den / d.frame_rate_num) +
" seconds)");
if (r->steps < 0 || r->steps > 1000) return no("num_inference_steps must be 1..1000");
if (r->cfg != 0.0f && !(r->cfg >= 1.0f)) return no("guidance_scale must be >= 1");
if (!kv_->can_ever_fit(std::max(T, Tn) + r->max_frames + 1))
return no("a piece of " + std::to_string(r->max_frames) + " frames after a " +
std::to_string(T) + "-token prompt does not fit the KV cache even when it is "
"empty; ask for a shorter piece");
r->ticket->t_submit_ns = (int64_t)rad_mono_ns();
std::lock_guard<std::mutex> lk(mu_);
if (closed_) {
if (why) *why = closed_why_;
return closed_status_;
}
auto j = std::make_unique<Job>();
j->id = next_id_++;
j->T = T;
j->req = std::move(r);
jobs_.push_back(std::move(j));
return RAD_OK;
}
void AudioDriver::shutdown(const char* why, int status) {
std::lock_guard<std::mutex> lk(mu_);
closed_ = true;
closed_why_ = why ? why : "the engine stopped";
closed_status_ = status;
for (auto& j : jobs_) j->req->ticket->finish(status, closed_why_);
}
int64_t AudioDriver::queued() const {
std::lock_guard<std::mutex> lk(mu_);
int64_t n = 0;
for (const auto& j : jobs_) if (!j->admitted) ++n;
return n;
}
int64_t AudioDriver::running() const {
std::lock_guard<std::mutex> lk(mu_);
int64_t n = 0;
for (const auto& j : jobs_) if (j->admitted) ++n;
return n;
}
AudioDriver::Job* AudioDriver::job_locked(uint64_t id) {
for (auto& j : jobs_) if (j->id == id) return j.get();
return nullptr;
}
void AudioDriver::release_locked(Job& j) {
for (int b = 0; b < 2; ++b)
if (j.seq[b]) {
kv_->free_sequence(j.seq[b]);
j.seq[b] = 0;
}
j.have_kv = false;
if (j.lane >= 0) {
free_lanes_.push_back(j.lane);
j.lane = -1;
}
}
void AudioDriver::fail_locked(Job& j, int status, const std::string& why) {
j.failed = true;
j.req->ticket->finish(status, why);
}
/* In arrival order; a request that does not fit stops the ones behind it. */
int AudioDriver::admit_locked() {
for (auto& jp : jobs_) {
Job& j = *jp;
if (j.admitted || j.failed) continue;
if (free_lanes_.empty()) break;
const AudioRequest& r = *j.req;
const float cfg = r.cfg > 0.0f ? r.cfg : (float)decl_.default_cfg;
/* The unconditional prompt: the request's own (the conditional one at guidance 1, which
* makes the guided logits the conditional ones), or derived from the conditional one. */
std::vector<int32_t> neg = r.tokens;
if (neg_own_ && cfg != 1.0f && !r.neg_tokens.empty()) {
neg = r.neg_tokens;
} else if (!neg_own_) {
for (int64_t i = decl_.neg_keep_head; i < j.T - decl_.neg_keep_tail; ++i)
neg[(size_t)i] = decl_.neg_token;
}
/* Both branches for the whole piece, so nothing in flight ever waits for KV. */
bool ok = true;
for (int b = 0; b < 2 && ok; ++b) {
const int64_t rows = (b ? (int64_t)neg.size() : j.T) + r.max_frames + 1;
j.seq[b] = ((uint64_t)1 << 61) | next_seq_++;
if (kv_->add_sequence(j.seq[b]) < 0 || kv_->ensure(j.seq[b], rows) < 0) ok = false;
}
if (!ok) {
for (int b = 0; b < 2; ++b)
if (j.seq[b]) {
if (kv_->has_sequence(j.seq[b])) kv_->free_sequence(j.seq[b]);
j.seq[b] = 0;
}
break;
}
j.have_kv = true;
j.lane = free_lanes_.back();
free_lanes_.pop_back();
j.neg = std::move(neg);
j.Tn = (int64_t)j.neg.size();
j.steps = r.steps > 0 ? r.steps : (int32_t)decl_.default_steps;
j.cfg = cfg;
j.req->ticket->in_tokens = j.T;
j.admitted = true;
}
return RAD_OK;
}
/* ================================================================== windows */
/* Window k is frames [k hop, k hop + win_frames), cut short at the piece's end. Window 0 always
* exists; window k >= 1 exists while frames remain past its overlap with window k - 1. */
int64_t AudioDriver::window_frames(const Job& j, int32_t k) const {
const int64_t f0 = win_frame0(k);
return j.ar_done ? std::min<int64_t>(decl_.win_frames, j.kept - f0) : decl_.win_frames;
}
bool AudioDriver::window_ready(const Job& j) const {
if (j.voc_due >= 0) return false;
if (j.win_step > 0) return true;
const int64_t k = j.win;
if (j.ar_done)
return k == 0 ? j.kept >= 1
: j.kept > k * decl_.win_hop + (decl_.win_frames - decl_.win_hop);
return j.kept >= k * decl_.win_hop + decl_.win_frames;
}
bool AudioDriver::chunk_due(const Job& j) const {
const int64_t ready = j.kept - j.played;
return !j.finished && (ready >= decl_.voc_chunk || (j.ar_done && ready > 0));
}
int AudioDriver::window_last(const Job& j, int32_t k) const {
const bool next_exists =
j.kept > (int64_t)(k + 1) * decl_.win_hop + (decl_.win_frames - decl_.win_hop);
if (next_exists) return 0;
return j.ar_done ? 1 : -1;
}
/* ================================================================== staging */
int AudioDriver::upload() {
for (size_t r = 0; r < ranks_.size(); ++r)
for (int g = 0; g < R_N; ++g) {
if (reg_[g].used <= 0) continue;
RAD_TRY(rad_memcpy_async((char*)dev_[r] + reg_[g].off, host_ + reg_[g].off,
reg_[g].used, ranks_[r].stream));
}
return RAD_OK;
}
void AudioDriver::base_batches(int64_t n_tok, int64_t n_seq, int32_t max_q, int32_t max_ctx,
int step, bool kv, int64_t bt_pitch) {
for (size_t r = 0; r < ranks_.size(); ++r) {
RadBatch& B = out_[r];
RadAudioGenBatch& A = aout_[r];
RadKVGroupBatch& K = kout_[r];
const int ri = (int)r;
B = RadBatch{};
B.step = step;
B.phase = RAD_PHASE_PREFILL;
B.n_tok = n_tok;
B.n_seq = n_seq;
B.max_q_len = max_q;
B.max_ctx_len = max_ctx;
B.max_q_len_prefill = max_q;
B.token_ids = dptr<int32_t>(ri, R_TOK);
B.positions = dptr<int32_t>(ri, R_POS);
B.cu_seqlens = dptr<int32_t>(ri, R_CU);
if (kv) {
K = RadKVGroupBatch{};
K.group = (rad_kvgroup)kv_group_;
K.slot_mapping = dptr<int32_t>(ri, R_SLOT);
K.block_table = dptr<int32_t>(ri, R_BT);
K.block_table_pitch = bt_pitch;
K.seqused = dptr<int32_t>(ri, R_USED);
K.block_size = block_size_;
K.max_blocks = max_blocks_;
B.n_kv_groups = 1;
B.kv = &K;
}
A = RadAudioGenBatch{};
A.lane = dptr<int32_t>(ri, R_LANE);
A.last = dptr<int32_t>(ri, R_LAST);
A.frame = dptr<int32_t>(ri, R_FRAME);
A.seed = dptr<uint32_t>(ri, R_SEED);
A.t = dptr<float>(ri, R_T);
A.t_next = dptr<float>(ri, R_TN);
A.cfg = dptr<float>(ri, R_CFG);
A.pair = dptr<int32_t>(ri, R_PAIR);
A.win_lane = dptr<int32_t>(ri, R_WLANE);
A.flags = dptr<int32_t>(ri, R_FLAGS);
A.win_index = dptr<int32_t>(ri, R_WIDX);
A.win_frame0 = dptr<int32_t>(ri, R_WF0);
A.win_frames = dptr<int32_t>(ri, R_WNF);
A.lat_cu = dptr<int32_t>(ri, R_LCU);
A.lat_src = dptr<int32_t>(ri, R_LSRC);
A.slot = dptr<int32_t>(ri, R_ESLOT);
A.last_row = dptr<int32_t>(ri, R_LROW);
A.prefix = dptr<int32_t>(ri, R_PREFIX);
B.agen_b = &A;
}
}
/* The KV slot of position `p` in a sequence with this block table. */
static int32_t slot_of(const std::vector<int32_t>& bt, int64_t p, int64_t bs) {
const int64_t bi = p / bs;
return bi < (int64_t)bt.size() ? (int32_t)(bt[(size_t)bi] * bs + p % bs) : -1;
}
/* ================================================================== the passes */
const RadBatch* AudioDriver::next(int step) {
std::lock_guard<std::mutex> lk(mu_);
pass_ = Pass{};
rb_.clear();
if (closed_) return nullptr;
/* Retire finished, failed and cancelled jobs, returning their KV and lanes before admitting.
* Safe because next() runs between passes, with nothing in flight. */
for (auto it = jobs_.begin(); it != jobs_.end();) {
Job& j = **it;
const bool cancelled = j.req->ticket->cancel.load(std::memory_order_acquire);
if (!(j.failed || cancelled || j.finished)) { ++it; continue; }
if (cancelled && !j.failed && !j.finished)
j.req->ticket->finish(RAD_E_CANCELLED, "the request was cancelled");
release_locked(j);
it = jobs_.erase(it);
}
admit_locked();
/* 1. A vocode: a chunk of frames that is ready, or a finished window, once it is known
* whether a window follows it. */
for (auto& jp : jobs_) {
Job& j = *jp;
if (!j.admitted || j.failed) continue;
if (chunked()) {
if (chunk_due(j)) return build_chunk(j, step);
continue;
}
if (j.voc_due >= 0 && window_last(j, j.voc_due) >= 0) return build_vocode(j, step);
}
/* 2. A prompt chunk. */
for (auto& jp : jobs_) {
Job& j = *jp;
if (j.admitted && !j.failed && j.prompt_done < j.T) return build_prompt(j, step);
}
/* 3. A frame of every lane in its autoregressive stage, or a step of the ready windows. */
std::vector<Job*> fr, win;
int64_t win_rows = 0, win_ent = 0;
for (auto& jp : jobs_) {
Job& j = *jp;
if (!j.admitted || j.failed || j.prompt_done < j.T) continue;
if (!j.ar_done) fr.push_back(&j);
if (!chunked() && window_ready(j)) {
const int64_t nb = j.cfg > 1.0f ? 2 : 1;
const int64_t rows =
nb * (decl_.win_lead + win_latents(window_frames(j, j.win)));
if (win_rows + rows <= max_tok_ && win_ent + nb <= max_seqs_) {
win_rows += rows;
win_ent += nb;
win.push_back(&j);
}
}
}
if (!fr.empty() && (win.empty() || frame_turn_)) {
frame_turn_ = false;
return build_frame(fr, step);
}
if (!win.empty()) {
frame_turn_ = true;
return build_window(win, step);
}
return nullptr;
}
const RadBatch* AudioDriver::batch_for(int rank) const {
if (rank < 0 || (size_t)rank >= out_.size() || pass_.kind == 0) return nullptr;
return &out_[(size_t)rank];
}
const RadBatch* AudioDriver::build_prompt(Job& j, int step) {
for (int g = 0; g < R_N; ++g) reg_[g].used = 0;
/* Each branch's rows: both whole, or the same chunk of both (their lengths are then equal). */
const int64_t p0 = j.prompt_done;
int64_t cb[2];
if (decl_.prompt_whole) {
cb[0] = j.T;
cb[1] = j.Tn;
} else {
cb[0] = cb[1] = std::min<int64_t>(j.T - j.prompt_done, max_tok_ / 2);
}
const int64_t cmax = std::max(cb[0], cb[1]);
int32_t* tok = hptr<int32_t>(R_TOK);
int32_t* pos = hptr<int32_t>(R_POS);
int32_t* slot = hptr<int32_t>(R_SLOT);
int32_t* cu = hptr<int32_t>(R_CU);
int64_t pitch = 1;
for (int b = 0; b < 2; ++b)
pitch = std::max<int64_t>(pitch, (int64_t)kv_->block_table(j.seq[b], kv_group_).size());
int32_t* btab = hptr<int32_t>(R_BT);
int32_t* used = hptr<int32_t>(R_USED);
cu[0] = 0;
for (int b = 0; b < 2; ++b) {
const std::vector<int32_t>& src = b ? j.neg : j.req->tokens;
const std::vector<int32_t>& bt = kv_->block_table(j.seq[b], kv_group_);
for (int64_t i = 0; i < cb[b]; ++i) {
const int64_t e = cu[b] + i;
tok[e] = src[(size_t)(p0 + i)];
pos[e] = (int32_t)(p0 + i);
slot[e] = slot_of(bt, p0 + i, block_size_);
}
cu[b + 1] = (int32_t)(cu[b] + cb[b]);
for (int64_t k = 0; k < pitch; ++k)
btab[b * pitch + k] = k < (int64_t)bt.size() ? bt[(size_t)k] : -1;
used[b] = (int32_t)(p0 + cb[b]);
}
const int64_t rows = cu[2];
const bool last = p0 + cb[0] == j.T;
for (int b = 0; b < 2; ++b) {
hptr<int32_t>(R_ESLOT)[b] = 2 * j.lane + b;
hptr<int32_t>(R_LROW)[b] = cu[b + 1] - 1;
hptr<int32_t>(R_PREFIX)[b] = (int32_t)p0;
}
reg_[R_ESLOT].used = reg_[R_LROW].used = reg_[R_PREFIX].used = 2 * 4;
hptr<int32_t>(R_LANE)[0] = j.lane;
hptr<int32_t>(R_LAST)[0] = last ? 1 : 0;
hptr<uint32_t>(R_SEED)[0] = (uint32_t)(j.req->seed & 0xffffffffu);
hptr<uint32_t>(R_SEED)[1] = (uint32_t)(j.req->seed >> 32);
reg_[R_TOK].used = reg_[R_POS].used = reg_[R_SLOT].used = rows * 4;
reg_[R_CU].used = 3 * 4;
reg_[R_BT].used = 2 * pitch * 4;
reg_[R_USED].used = 2 * 4;
reg_[R_LANE].used = reg_[R_LAST].used = 4;
reg_[R_SEED].used = 8;
if (upload() < 0) return nullptr;
base_batches(rows, 2, (int32_t)cmax, (int32_t)(p0 + cmax), step, true, pitch);
h_lane_.assign(1, j.lane);
h_last_.assign(1, last ? 1 : 0);
for (size_t r = 0; r < ranks_.size(); ++r) {
out_[r].gen = RAD_GEN_PASS_PROMPT;
RadAudioGenBatch& A = aout_[r];
A.n_lane = 1;
A.lane_h = h_lane_.data();
A.last_h = h_last_.data();
}
pass_.kind = RAD_GEN_PASS_PROMPT;
pass_.jobs.assign(1, j.id);
pass_.rows.assign(1, cb[0]);
return &out_[0];
}
const RadBatch* AudioDriver::build_frame(const std::vector<Job*>& js, int step) {
for (int g = 0; g < R_N; ++g) reg_[g].used = 0;
const int64_t L = (int64_t)js.size(), S = 2 * L;
int32_t* tok = hptr<int32_t>(R_TOK);
int32_t* pos = hptr<int32_t>(R_POS);
int32_t* slot = hptr<int32_t>(R_SLOT);
int32_t* cu = hptr<int32_t>(R_CU);
int32_t* btab = hptr<int32_t>(R_BT);
int32_t* used = hptr<int32_t>(R_USED);
int32_t* lane = hptr<int32_t>(R_LANE);
int32_t* frame = hptr<int32_t>(R_FRAME);
uint32_t* seed = hptr<uint32_t>(R_SEED);
int64_t pitch = 1;
int32_t max_ctx = 0;
for (const Job* j : js)
for (int b = 0; b < 2; ++b)
pitch = std::max<int64_t>(pitch, (int64_t)kv_->block_table(j->seq[b], kv_group_).size());
h_lane_.assign((size_t)L, 0);
h_frame_.assign((size_t)L, 0);
pass_.jobs.clear();
for (int64_t i = 0; i < L; ++i) {
const Job& j = *js[(size_t)i];
for (int b = 0; b < 2; ++b) {
/* The frame's row follows the branch's prompt and its earlier frames. */
const int64_t p = (b ? j.Tn : j.T) + j.frame;
const int64_t e = 2 * i + b;
const std::vector<int32_t>& bt = kv_->block_table(j.seq[b], kv_group_);
tok[e] = 0;
pos[e] = (int32_t)p;
slot[e] = slot_of(bt, p, block_size_);
cu[e] = (int32_t)e;
for (int64_t k = 0; k < pitch; ++k)
btab[e * pitch + k] = k < (int64_t)bt.size() ? bt[(size_t)k] : -1;
used[e] = (int32_t)(p + 1);
hptr<int32_t>(R_ESLOT)[e] = 2 * j.lane + b;
hptr<int32_t>(R_LROW)[e] = (int32_t)e;
max_ctx = std::max<int32_t>(max_ctx, (int32_t)(p + 1));
}
hptr<float>(R_CFG)[i] = j.cfg;
lane[i] = h_lane_[(size_t)i] = j.lane;
frame[i] = h_frame_[(size_t)i] = j.frame;
seed[2 * i] = (uint32_t)(j.req->seed & 0xffffffffu);
seed[2 * i + 1] = (uint32_t)(j.req->seed >> 32);
pass_.jobs.push_back(j.id);
}
cu[S] = (int32_t)S;
reg_[R_TOK].used = reg_[R_POS].used = reg_[R_SLOT].used = S * 4;
reg_[R_CU].used = (S + 1) * 4;
reg_[R_BT].used = S * pitch * 4;
reg_[R_USED].used = S * 4;
reg_[R_LANE].used = reg_[R_FRAME].used = reg_[R_CFG].used = L * 4;
reg_[R_SEED].used = 2 * L * 4;
reg_[R_ESLOT].used = reg_[R_LROW].used = S * 4;
if (upload() < 0) return nullptr;
base_batches(S, S, 1, max_ctx, step, true, pitch);
for (size_t r = 0; r < ranks_.size(); ++r) {
RadBatch& B = out_[r];
B.gen = RAD_GEN_PASS_FRAME;
B.phase = RAD_PHASE_DECODE;
B.n_seq_decode = S;
B.n_tok_decode = S;
B.max_q_len_decode = 1;
B.max_q_len_prefill = 0;
RadAudioGenBatch& A = aout_[r];
A.n_lane = L;
A.lane_h = h_lane_.data();
A.frame_h = h_frame_.data();
}
rb_.assign(1, Readback{ decl_.status, decl_.max_lanes * 4, status_host_ });
pass_.kind = RAD_GEN_PASS_FRAME;
return &out_[0];
}
const RadBatch* AudioDriver::build_window(const std::vector<Job*>& js, int step) {
for (int g = 0; g < R_N; ++g) reg_[g].used = 0;
int32_t* tok = hptr<int32_t>(R_TOK);
int32_t* pos = hptr<int32_t>(R_POS);
int32_t* cu = hptr<int32_t>(R_CU);
float* t = hptr<float>(R_T);
float* tn = hptr<float>(R_TN);
float* cfg = hptr<float>(R_CFG);
int32_t* pair = hptr<int32_t>(R_PAIR);
int32_t* wlane = hptr<int32_t>(R_WLANE);
int32_t* flags = hptr<int32_t>(R_FLAGS);
int32_t* widx = hptr<int32_t>(R_WIDX);
int32_t* wf0 = hptr<int32_t>(R_WF0);
int32_t* wnf = hptr<int32_t>(R_WNF);
int32_t* lcu = hptr<int32_t>(R_LCU);
int32_t* lsrc = hptr<int32_t>(R_LSRC);
uint32_t* seed = hptr<uint32_t>(R_SEED);
h_wlane_.clear();
h_flags_.clear();
h_widx_.clear();
h_wf0_.clear();
h_wnf_.clear();
h_lcu_.assign(1, 0);
pass_.jobs.clear();
int64_t S = 0, row = 0, lrow = 0;
int32_t max_q = 0;
cu[0] = 0;
lcu[0] = 0;
for (Job* jp : js) {
Job& j = *jp;
const int64_t nf = window_frames(j, j.win);
const int64_t nl = win_latents(nf);
const int64_t len = decl_.win_lead + nl;
const int nb = j.cfg > 1.0f ? 2 : 1;
int32_t f = 0;
if (j.win_step == 0) f |= RAD_AGEN_F_FIRST;
if (j.win_step + 1 == j.steps) f |= RAD_AGEN_F_LAST;
if (j.win > 0) f |= RAD_AGEN_F_JOIN;
for (int b = 0; b < nb; ++b) {
const int64_t e = S++;
for (int64_t k = 0; k < len; ++k) {
tok[row + k] = 0;
pos[row + k] = (int32_t)k;
}
for (int64_t k = 0; k < nl; ++k) lsrc[lrow + k] = (int32_t)(row + decl_.win_lead + k);
row += len;
lrow += nl;
cu[e + 1] = (int32_t)row;
lcu[e + 1] = (int32_t)lrow;
t[e] = (float)j.win_step / (float)j.steps;
tn[e] = (float)(j.win_step + 1) / (float)j.steps;
cfg[e] = b ? 0.0f : (nb > 1 ? j.cfg : 1.0f);
pair[e] = b ? -2 : (nb > 1 ? (int32_t)(e + 1) : -1);
wlane[e] = j.lane;
flags[e] = f;
widx[e] = j.win;
wf0[e] = (int32_t)win_frame0(j.win);
wnf[e] = (int32_t)nf;
seed[2 * e] = (uint32_t)(j.req->seed & 0xffffffffu);
seed[2 * e + 1] = (uint32_t)(j.req->seed >> 32);
h_wlane_.push_back(j.lane);
h_flags_.push_back(f);
h_widx_.push_back(j.win);
h_wf0_.push_back(wf0[e]);
h_wnf_.push_back((int32_t)nf);
h_lcu_.push_back((int32_t)lrow);
max_q = std::max<int32_t>(max_q, (int32_t)len);
}
pass_.jobs.push_back(j.id);
}
reg_[R_TOK].used = reg_[R_POS].used = row * 4;
reg_[R_CU].used = reg_[R_LCU].used = (S + 1) * 4;
reg_[R_T].used = reg_[R_TN].used = reg_[R_CFG].used = S * 4;
reg_[R_PAIR].used = reg_[R_WLANE].used = reg_[R_FLAGS].used = S * 4;
reg_[R_WIDX].used = reg_[R_WF0].used = reg_[R_WNF].used = S * 4;
reg_[R_SEED].used = 2 * S * 4;
reg_[R_LSRC].used = lrow * 4;
if (upload() < 0) return nullptr;
base_batches(row, S, max_q, 0, step, false, 0);
for (size_t r = 0; r < ranks_.size(); ++r) {
out_[r].gen = RAD_GEN_PASS_WINDOW;
RadAudioGenBatch& A = aout_[r];
A.win_lane_h = h_wlane_.data();
A.flags_h = h_flags_.data();
A.win_index_h = h_widx_.data();
A.win_frame0_h = h_wf0_.data();
A.win_frames_h = h_wnf_.data();
A.lat_rows = lrow;
A.lat_cu_h = h_lcu_.data();
}
pass_.kind = RAD_GEN_PASS_WINDOW;
return &out_[0];
}
const RadBatch* AudioDriver::build_vocode(Job& j, int step) {
for (int g = 0; g < R_N; ++g) reg_[g].used = 0;
const int32_t k = j.voc_due;
const int64_t nl = win_latents(window_frames(j, k));
int64_t left = k > 0 ? decl_.win_crop_left : 0;
int64_t right = window_last(j, k) == 1 ? 0 : decl_.win_crop_right;
left = std::min<int64_t>(left, nl);
right = std::min<int64_t>(right, nl - left);
int32_t* cu = hptr<int32_t>(R_CU);
cu[0] = 0;
cu[1] = (int32_t)nl;
reg_[R_CU].used = 2 * 4;
if (upload() < 0) return nullptr;
base_batches(nl, 1, (int32_t)nl, 0, step, false, 0);
for (size_t r = 0; r < ranks_.size(); ++r) {
out_[r].gen = RAD_GEN_PASS_VOCODE;
RadAudioGenBatch& A = aout_[r];
A.voc_lane = j.lane;
A.voc_window = k;
A.voc_latents = (int32_t)nl;
A.voc_left = (int32_t)left;
A.voc_right = (int32_t)right;
}
const int64_t samples = (nl - left - right) * decl_.samples_per_latent;
rb_.assign(1, Readback{ decl_.audio_out, samples * decl_.channels * 4, audio_host_ });
pass_.kind = RAD_GEN_PASS_VOCODE;
pass_.voc_job = j.id;
pass_.voc_window = k;
pass_.voc_samples = samples;
return &out_[0];
}
/* A chunk of a lane's kept frames, after the frames it reads again for context. Its rows are
* the frames, at their positions in the piece. */
const RadBatch* AudioDriver::build_chunk(Job& j, int step) {
for (int g = 0; g < R_N; ++g) reg_[g].used = 0;
const int64_t n = std::min<int64_t>(decl_.voc_chunk, j.kept - j.played);
const int64_t ctx = std::min<int64_t>(decl_.voc_context, j.played);
const int64_t f0 = j.played - ctx, nl = ctx + n;
int32_t* cu = hptr<int32_t>(R_CU);
int32_t* pos = hptr<int32_t>(R_POS);
cu[0] = 0;
cu[1] = (int32_t)nl;
for (int64_t i = 0; i < nl; ++i) pos[i] = (int32_t)(f0 + i);
reg_[R_CU].used = 2 * 4;
reg_[R_POS].used = nl * 4;
if (upload() < 0) return nullptr;
base_batches(nl, 1, (int32_t)nl, 0, step, false, 0);
for (size_t r = 0; r < ranks_.size(); ++r) {
out_[r].gen = RAD_GEN_PASS_VOCODE;
RadAudioGenBatch& A = aout_[r];
A.voc_lane = j.lane;
A.voc_window = j.windows_played;
A.voc_latents = (int32_t)nl;
A.voc_left = (int32_t)ctx;
A.voc_right = 0;
A.voc_frame0 = f0;
}
const int64_t samples = n * decl_.samples_per_latent;
rb_.assign(1, Readback{ decl_.audio_out, samples * decl_.channels * 4, audio_host_ });
pass_.kind = RAD_GEN_PASS_VOCODE;
pass_.voc_job = j.id;
pass_.voc_window = j.windows_played;
pass_.voc_samples = samples;
pass_.voc_frames = n;
return &out_[0];
}
int AudioDriver::done() {
std::lock_guard<std::mutex> lk(mu_);
const int64_t now = (int64_t)rad_mono_ns();
switch (pass_.kind) {
case RAD_GEN_PASS_PROMPT:
for (size_t i = 0; i < pass_.jobs.size(); ++i) {
Job* j = job_locked(pass_.jobs[i]);
if (!j) continue;
j->prompt_done += pass_.rows[i];
if (j->prompt_done >= j->T) j->req->ticket->t_prompt_ns = now;
}
break;
case RAD_GEN_PASS_FRAME:
for (uint64_t id : pass_.jobs) {
Job* j = job_locked(id);
if (!j || j->failed) continue;
const int32_t st = status_host_[j->lane];
if (st < 0) {
j->ar_done = true;
j->req->ticket->model_ended = true;
if (j->kept == 0) {
fail_locked(*j, RAD_E_INVAL, "the model ended the piece before its first "
"frame; try other text or another seed");
continue;
}
} else {
if (j->frame >= decl_.first_frame) j->kept = j->frame - decl_.first_frame + 1;
++j->frame;
if (j->kept >= j->req->max_frames) j->ar_done = true;
}
if (j->ar_done) {
j->req->ticket->frames = j->kept;
j->req->ticket->t_frames_ns = now;
/* Every frame already played: nothing more is owed. */
if (chunked() && j->played == j->kept) {
j->finished = true;
j->req->ticket->windows = j->windows_played;
j->req->ticket->t_done_ns = now;
j->req->ticket->finish(RAD_OK);
}
}
}
break;
case RAD_GEN_PASS_WINDOW:
for (uint64_t id : pass_.jobs) {
Job* j = job_locked(id);
if (!j) continue;
if (++j->win_step >= j->steps) {
j->voc_due = j->win;
j->win_step = 0;
}
}
break;
case RAD_GEN_PASS_VOCODE: {
Job* j = job_locked(pass_.voc_job);
if (!j) break;
AudioChunk c;
c.window = pass_.voc_window;
c.samples.assign(audio_host_, audio_host_ + pass_.voc_samples * decl_.channels);
j->req->ticket->push(std::move(c));
if (j->windows_played == 0) j->req->ticket->t_first_audio_ns = now;
++j->windows_played;
bool last;
if (chunked()) {
j->played += pass_.voc_frames;
last = j->ar_done && j->played == j->kept;
} else {
last = window_last(*j, j->voc_due) == 1;
j->voc_due = -1;
++j->win;
}
if (last) {
j->finished = true;
j->req->ticket->windows = j->windows_played;
j->req->ticket->t_done_ns = now;
j->req->ticket->finish(RAD_OK);
}
break;
}
default:
break;
}
pass_ = Pass{};
rb_.clear();
return RAD_OK;
}
} /* namespace gen */
} /* namespace rad */
+188
View File
@@ -0,0 +1,188 @@
/* audio_driver.h -- the audio generator's pass driver (audio.h, abi/rad_builder.h's
* RadAudioGenDecl describes the passes).
*
* Driven by the engine thread like the image driver (driver.h): `next()` picks and stages a pass,
* `done()` folds its result back once every rank has run it. Requests arrive from HTTP threads
* through `submit()` and leave through their AudioTicket.
*
* A request holds a lane and two KV sequences, its conditional and unconditional branches, from
* admission to its last window; both are reserved for the whole piece at admission (prompt plus
* every frame the request may make), so a request in flight never waits for KV.
*
* Pass priority, one pass at a time:
*
* 1. VOCODE a finished window is owed (it frees the lane's latent for the next window and gives
* the caller audio), or, for a vocoder that plays frames as they are made
* (RadAudioGenDecl::voc_chunk), a chunk of frames is ready: `voc_chunk` of them, or the
* piece's last.
* 2. PROMPT an admitted request's prompt is not all in the KV: the next chunk of it, both
* branches.
* 3. FRAME and WINDOW, taking turns when both have work: one frame of every request in its
* autoregressive stage, or one denoising step of the windows that are ready. A FRAME pass
* carries every lane at once, since its cost is reading the language model's weights, which
* the lanes share; a window's step is compute and carries what fits the pass's rows.
*
* A window is ready once the language model has made all its frames, or ended the piece. Its
* vocoding waits until it is known whether a window follows it (the crop at its end depends on
* that): once the frames of the next window have begun, or the piece has ended.
*/
#pragma once
#include "audio.h"
#include "pass.h"
#include "device/device.h"
#include <mutex>
namespace rad {
struct IKVManager;
namespace gen {
class AudioDriver final : public IPassDriver {
public:
struct RankIO {
int device = 0;
RadStream stream = nullptr;
};
/* `kv` is rank 0's KV manager: one block table serves every rank. */
int init(const Program& prog, IKVManager* kv, const std::vector<RankIO>& ranks);
void fini();
~AudioDriver() override { fini(); }
/* The bytes init() allocates on each rank's card, for the VRAM budget. */
static int64_t device_bytes(const Program& prog);
/* The longest sequence a branch holds: the whole prompt and every frame. The KV group is
* sized from it. */
static int64_t max_seq_rows(const RadAudioGenDecl& d) { return d.max_prompt + d.max_frames + 1; }
/* ---------------------------------------------------------- HTTP threads */
/* Queue a request, refused at once with `why` when it can never run. */
int submit(std::unique_ptr<AudioRequest> r, std::string* why);
const RadAudioGenDecl& decl() const { return decl_; }
void shutdown(const char* why, int status) override;
/* ---------------------------------------------------------- the engine thread */
const RadBatch* next(int step) override;
const RadBatch* batch_for(int rank) const override;
const std::vector<Readback>& readbacks() const override { return rb_; }
int done() override;
int64_t queued() const override;
int64_t running() const override;
private:
struct Job {
uint64_t id = 0;
std::unique_ptr<AudioRequest> req;
int32_t lane = -1;
uint64_t seq[2] = { 0, 0 };
bool have_kv = false;
bool admitted = false;
bool failed = false;
int64_t T = 0; /* prompt tokens */
std::vector<int32_t> neg; /* the unconditional prompt */
int64_t Tn = 0; /* its tokens */
int64_t prompt_done = 0; /* prompt rows in the KV */
/* The autoregressive stage: the next frame to make, the frames kept, and whether it is
* over (the model ended the piece, or it reached max_frames). */
int32_t frame = 0;
int64_t kept = 0;
bool ar_done = false;
/* The windows: the one being stepped (or next to start), its step, and the one owed a
* vocode pass (-1 none). */
int32_t win = 0;
int32_t win_step = 0;
int32_t steps = 0;
float cfg = 1.0f;
int32_t voc_due = -1;
int32_t windows_played = 0;
/* A vocoder playing frames as they are made: the kept frames played so far. */
int64_t played = 0;
bool finished = false;
};
/* The pass in flight, for done(). */
struct Pass {
int kind = 0;
std::vector<uint64_t> jobs; /* PROMPT, FRAME, WINDOW: one per lane or window */
std::vector<int64_t> rows; /* PROMPT: the chunk each job's branches advanced */
uint64_t voc_job = 0;
int32_t voc_window = -1;
int64_t voc_samples = 0;
int64_t voc_frames = 0; /* a chunk's frames played */
};
/* Staging regions: their offsets in the host span and every rank's slab. */
struct Region { int64_t off = 0, bytes = 0, used = 0; };
enum { R_TOK, R_POS, R_CU, R_SLOT, R_BT, R_USED, R_LANE, R_LAST, R_FRAME, R_SEED,
R_T, R_TN, R_CFG, R_PAIR, R_WLANE, R_FLAGS, R_WIDX, R_WF0, R_WNF, R_LCU, R_LSRC,
R_ESLOT, R_LROW, R_PREFIX, R_N };
template <class T> T* hptr(int r) const { return reinterpret_cast<T*>(host_ + reg_[r].off); }
template <class T> T* dptr(int rank, int r) const {
return reinterpret_cast<T*>((char*)dev_[(size_t)rank] + reg_[r].off);
}
int upload();
void base_batches(int64_t n_tok, int64_t n_seq, int32_t max_q, int32_t max_ctx, int step,
bool kv, int64_t bt_pitch);
int admit_locked();
void release_locked(Job& j);
void fail_locked(Job& j, int status, const std::string& why);
Job* job_locked(uint64_t id);
/* Window geometry: window k's first frame and frames once the piece has `n` frames (or
* at least `n`, with `ended` false), whether it exists, and whether it is the last. */
int64_t win_frame0(int32_t k) const { return (int64_t)k * decl_.win_hop; }
int64_t win_latents(int64_t frames) const { return frames * decl_.lat_num / decl_.lat_den; }
bool window_ready(const Job& j) const;
/* A vocoder playing frames as they are made: whether a chunk of `j`'s frames is due. */
bool chunk_due(const Job& j) const;
bool chunked() const { return decl_.voc_chunk > 0; }
int window_last(const Job& j, int32_t k) const; /* 1 last, 0 not, -1 not yet known */
int64_t window_frames(const Job& j, int32_t k) const;
const RadBatch* build_prompt(Job& j, int step);
const RadBatch* build_frame(const std::vector<Job*>& js, int step);
const RadBatch* build_window(const std::vector<Job*>& js, int step);
const RadBatch* build_vocode(Job& j, int step);
const RadBatch* build_chunk(Job& j, int step);
RadAudioGenDecl decl_{};
std::string name_;
int64_t max_tok_ = 0, max_seqs_ = 0;
int64_t block_size_ = 0, max_blocks_ = 0;
int32_t kv_group_ = 0;
bool neg_own_ = false; /* the unconditional prompt is the request's own */
std::vector<RankIO> ranks_;
IKVManager* kv_ = nullptr;
char* host_ = nullptr; /* pinned, same layout as each slab */
int64_t bytes_ = 0;
std::vector<void*> dev_;
Region reg_[R_N];
int32_t* status_host_ = nullptr;
float* audio_host_ = nullptr;
int64_t audio_bytes_ = 0;
std::vector<Readback> rb_;
std::vector<RadBatch> out_; /* one per rank */
std::vector<RadAudioGenBatch> aout_;
std::vector<RadKVGroupBatch> kout_;
Pass pass_;
bool frame_turn_ = true; /* FRAME goes first when both are due */
/* Host arrays a pass's plugin reads on the host (the _h fields), for the life of the pass. */
std::vector<int32_t> h_lane_, h_last_, h_frame_, h_wlane_, h_flags_, h_widx_,
h_wf0_, h_wnf_, h_lcu_;
mutable std::mutex mu_;
std::deque<std::unique_ptr<Job>> jobs_; /* arrival order */
std::vector<int32_t> free_lanes_;
uint64_t next_id_ = 1;
uint64_t next_seq_ = 1;
bool closed_ = false;
std::string closed_why_;
int closed_status_ = RAD_E_STATE;
};
} /* namespace gen */
} /* namespace rad */
+3
View File
@@ -439,6 +439,7 @@ const RadBatch* Driver::next(int step) {
std::lock_guard<std::mutex> lk(mu_);
pass_ = Pass{};
dec_bytes_ = 0;
rb_.clear();
if (closed_) return nullptr;
/* Retire finished, failed and cancelled jobs, returning their KV and lanes before admitting.
* Safe because next() runs between passes, with nothing in flight. */
@@ -820,6 +821,7 @@ const RadBatch* Driver::build_decode(int32_t l, bool preview, int step) {
G.dec_preview = preview ? 1 : 0;
}
dec_bytes_ = (int64_t)j->req->width * j->req->height * decl_.pixel_channels;
rb_.assign(1, Readback{ decl_.image_out, dec_bytes_, img_host_ });
pass_.kind = RAD_GEN_PASS_DECODE;
pass_.job = j->id;
pass_.lane = l;
@@ -889,6 +891,7 @@ int Driver::done() {
}
pass_ = Pass{};
dec_bytes_ = 0;
rb_.clear();
return RAD_OK;
}
+11 -16
View File
@@ -23,6 +23,7 @@
*/
#pragma once
#include "gen.h"
#include "pass.h"
#include "device/device.h"
#include <mutex>
@@ -31,7 +32,7 @@
namespace rad {
namespace gen {
class Driver {
class Driver final : public IPassDriver {
public:
struct RankIO {
int device = 0;
@@ -54,25 +55,18 @@ public:
* request. */
const RadGeneratorDecl& decl() const { return decl_; }
int64_t max_cond_tokens() const { return max_tok_; }
/* Fail every request queued or in flight, and refuse new ones. */
void shutdown(const char* why, int status);
void shutdown(const char* why, int status) override;
/* ---------------------------------------------------------- the engine thread */
/* The next pass, staged on every rank's stream, or null when there is nothing to run.
* `step` is the engine's pass counter, carried into RadBatch::step. */
const RadBatch* next(int step);
const RadBatch* batch_for(int rank) const;
/* Bytes of image output the staged pass produces, 0 if none; the engine copies them to
* host_image() behind the pass. */
int64_t decode_bytes() const { return dec_bytes_; }
void* host_image() const { return img_host_; }
/* The pass has run on every rank and its streams are drained. */
int done();
const RadBatch* next(int step) override;
const RadBatch* batch_for(int rank) const override;
/* A decode pass's pixels: `image_out` into the pinned image buffer. */
const std::vector<Readback>& readbacks() const override { return rb_; }
int done() override;
bool busy() const;
/* For /health, /stats and the dashboard. */
int64_t queued() const;
int64_t running() const;
int64_t queued() const override;
int64_t running() const override;
private:
struct Cond {
@@ -160,6 +154,7 @@ private:
void* img_host_ = nullptr;
int64_t img_bytes_ = 0;
int64_t dec_bytes_ = 0;
std::vector<Readback> rb_;
std::vector<RadBatch> out_; /* one per rank */
std::vector<RadGenBatch> gout_;
+45
View File
@@ -0,0 +1,45 @@
/* pass.h -- what the engine's pass loop needs of a generator's driver.
*
* A generator program is driven by passes rather than token steps (abi/rad_builder.h,
* rad_declare_generator and rad_declare_audio_generator). Each kind has its own driver, which turns
* its requests into passes (core/gen/driver.h for images, core/gen/audio_driver.h for audio); the
* loop that runs them on the ranks is one (Engine::gen_loop). The loop asks for the next pass,
* runs it on every rank, copies back what the driver names and hands the pass back.
*/
#pragma once
#include "rad_core.h"
#include <vector>
namespace rad {
namespace gen {
struct IPassDriver {
/* A device buffer the staged pass leaves for the host: `bytes` from the start of `buf` on
* rank 0, copied to `host` behind the pass. Every rank holds the same values. */
struct Readback {
rad_buf buf = RAD_NULL_HANDLE;
int64_t bytes = 0;
void* host = nullptr;
};
virtual ~IPassDriver() = default;
/* The next pass, staged on every rank's stream, or null when there is nothing to run.
* `step` is the engine's pass counter, carried into RadBatch::step. */
virtual const RadBatch* next(int step) = 0;
virtual const RadBatch* batch_for(int rank) const = 0;
/* What the staged pass's results are, valid until done(). */
virtual const std::vector<Readback>& readbacks() const = 0;
/* The pass has run on every rank, its streams are drained and the readbacks have landed. */
virtual int done() = 0;
/* Fail every request queued or in flight, and refuse new ones. */
virtual void shutdown(const char* why, int status) = 0;
/* For /health, /stats and the dashboard. */
virtual int64_t queued() const = 0;
virtual int64_t running() const = 0;
};
} /* namespace gen */
} /* namespace rad */
+97
View File
@@ -0,0 +1,97 @@
/* video.h -- video generation: the request and the channel its video comes back on.
*
* A video generator (abi/rad_builder.h, rad_declare_video_generator) makes a video and its
* soundtrack in one denoising loop over a packed sequence, then decodes the soundtrack and the
* frames, a chunk of frames at a time. core/gen/video_driver.h turns a request into those passes;
* this is what a caller hands it and what it hands back: progress as the steps run, the
* soundtrack, the frames chunk by chunk in order, then the end.
*/
#pragma once
#include "rad_core.h"
#include <atomic>
#include <condition_variable>
#include <deque>
#include <memory>
#include <mutex>
#include <string>
#include <vector>
namespace rad {
namespace gen {
/* One thing a request has made. */
struct VideoEvent {
enum Kind { STEP = 1, AUDIO = 2, FRAMES = 3 };
int kind = 0;
int32_t steps_done = 0; /* STEP: denoising steps finished */
/* AUDIO: the whole soundtrack, interleaved, in [-1, 1]. */
std::vector<float> samples;
/* FRAMES: frames [first, first + n) of the video, each [height, width, 3] u8 RGB. */
int32_t first = 0, n = 0;
std::vector<uint8_t> rgb;
};
/* As Ticket (gen.h) is for an image: the driver thread writes, the caller reads. */
class VideoTicket {
public:
/* driver side */
void push(VideoEvent&& e);
void finish(int status, const std::string& why = std::string());
/* caller side: the next event, or false once the request has ended and every event was
* taken. Waits at most `ms` milliseconds; `*timed_out` marks a false that was a timeout. */
bool next(VideoEvent* out, int ms, bool* timed_out);
bool finished() const;
int status() const;
std::string why() const;
std::atomic<bool> cancel{false};
/* What the request makes, written by the driver at submit: the frames and their size, the
* steps, and the soundtrack's rate and channels. */
int32_t frames = 0, width = 0, height = 0, steps = 0;
int64_t sample_rate = 0, channels = 0;
double fps = 0.0;
/* Usage, written by the driver before finish(): prompt tokens, rows a step and per-phase
* times. */
int64_t in_tokens = 0, rows = 0;
int64_t t_submit_ns = 0, t_cond_ns = 0, t_denoised_ns = 0, t_done_ns = 0;
private:
mutable std::mutex mu_;
std::condition_variable cv_;
std::deque<VideoEvent> q_;
bool done_ = false;
int status_ = RAD_OK;
std::string why_;
};
struct VideoRequest {
std::vector<int32_t> tokens; /* the prompt, rendered and tokenised */
int32_t width = 0, height = 0; /* pixels, within the declaration's limits */
int32_t chunks = 0; /* the length in chunks (RadVideoGenDecl) */
int32_t steps = 0; /* sigma grid points; 0: the model's default */
uint64_t seed = 0;
std::shared_ptr<VideoTicket> ticket;
};
/* A request's shape under a declaration: frames, latent grid, soundtrack latents and the rows of
* a step. Shared by the driver and the server, which checks a request before preparing it. */
struct VideoShape {
int32_t frames = 0, lat_frames = 0, lat_h = 0, lat_w = 0, n_audio = 0;
int64_t video_rows = 0, audio_rows = 0;
};
VideoShape video_shape(const RadVideoGenDecl& d, int32_t width, int32_t height, int32_t chunks);
/* The two schedules a request of `steps` grid points runs (RadVideoGenDecl, "The sampler"): each
* the f32 sigmas, last 0, and the model evaluations it takes, the shorter of the two. With a
* trained schedule any other step count than n_rungs + 1 gives no steps. */
struct VideoSchedule {
std::vector<float> sig_v, sig_a;
int32_t steps = 0;
};
VideoSchedule video_schedule(const RadVideoGenDecl& d, int32_t steps);
} /* namespace gen */
} /* namespace rad */
+665
View File
@@ -0,0 +1,665 @@
/* video_driver.cpp -- the video generator's pass driver (video_driver.h), the ticket a caller
* waits on, and a request's shape and schedule (video.h). */
#include "video_driver.h"
#include <algorithm>
#include <chrono>
#include <cstring>
namespace rad {
namespace gen {
/* ================================================================== the ticket */
void VideoTicket::push(VideoEvent&& e) {
{
std::lock_guard<std::mutex> lk(mu_);
q_.push_back(std::move(e));
}
cv_.notify_all();
}
void VideoTicket::finish(int status, const std::string& why) {
{
std::lock_guard<std::mutex> lk(mu_);
if (done_) return;
done_ = true;
status_ = status;
why_ = why;
}
cv_.notify_all();
}
bool VideoTicket::next(VideoEvent* out, int ms, bool* timed_out) {
std::unique_lock<std::mutex> lk(mu_);
if (timed_out) *timed_out = false;
if (q_.empty() && !done_)
cv_.wait_for(lk, std::chrono::milliseconds(ms), [this] { return !q_.empty() || done_; });
if (!q_.empty()) {
*out = std::move(q_.front());
q_.pop_front();
return true;
}
if (!done_ && timed_out) *timed_out = true;
return false;
}
bool VideoTicket::finished() const {
std::lock_guard<std::mutex> lk(mu_);
return done_ && q_.empty();
}
int VideoTicket::status() const {
std::lock_guard<std::mutex> lk(mu_);
return status_;
}
std::string VideoTicket::why() const {
std::lock_guard<std::mutex> lk(mu_);
return why_;
}
/* ================================================================== shape and schedule */
VideoShape video_shape(const RadVideoGenDecl& d, int32_t width, int32_t height, int32_t chunks) {
VideoShape s;
s.frames = (int32_t)(d.frames_per_chunk * chunks + d.frames_tail);
s.lat_frames = (int32_t)(d.latents_per_chunk * chunks + d.latents_tail);
s.lat_h = (int32_t)(height / d.latent_scale);
s.lat_w = (int32_t)(width / d.latent_scale);
/* round(frames / fps * audio_rate), ties to even as the reference's float round; with an
* integer numerator and denominator a tie is exact. */
const int64_t num = (int64_t)s.frames * d.fps_den * d.audio_rate, den = d.fps_num;
int64_t q = num / den;
const int64_t r2 = 2 * (num % den);
if (r2 > den || (r2 == den && (q & 1))) ++q;
s.n_audio = (int32_t)q;
s.video_rows = (int64_t)s.lat_frames * (s.lat_h / d.patch) * (s.lat_w / d.patch);
s.audio_rows = d.audio_channels * (int64_t)s.n_audio;
return s;
}
/* The shift of one base time, in f32 as the reference's tensor arithmetic. */
static float shift_sigma(double shift, float b) {
const float sh = (float)shift, sh1 = (float)(shift - 1.0);
return (sh * b) / (1.0f + sh1 * b);
}
/* torch.linspace(1, 0, n) in f32, which computes the first half up from the start and the
* second half down from the end, then the exponential shift, consecutive duplicates dropped. */
static std::vector<float> shifted_sigmas(double shift, int64_t n) {
std::vector<float> s;
if (n < 2) return s;
const float start = 1.0f, end = 0.0f;
const float step = (end - start) / (float)(n - 1);
const int64_t half = n / 2;
for (int64_t i = 0; i < n; ++i) {
const float b = i < half ? start + step * (float)i : end - step * (float)(n - i - 1);
const float v = shift_sigma(shift, b);
if (s.empty() || v != s.back()) s.push_back(v);
}
return s;
}
/* A trained schedule: each rung taken to f32 and shifted, then the terminal 0. */
static std::vector<float> rung_sigmas(double shift, const double* rungs, int32_t n) {
std::vector<float> s;
for (int32_t i = 0; i < n; ++i) s.push_back(shift_sigma(shift, (float)rungs[i]));
s.push_back(0.0f);
return s;
}
VideoSchedule video_schedule(const RadVideoGenDecl& d, int32_t steps) {
VideoSchedule v;
if (d.n_rungs > 0) {
if (steps != d.n_rungs + 1) return v;
v.sig_v = rung_sigmas(d.shift_video, d.rungs, d.n_rungs);
v.sig_a = rung_sigmas(d.shift_audio, d.rungs, d.n_rungs);
v.steps = d.n_rungs;
return v;
}
v.sig_v = shifted_sigmas(d.shift_video, steps);
v.sig_a = shifted_sigmas(d.shift_audio, steps);
const size_t n = std::min(v.sig_v.size(), v.sig_a.size());
v.steps = n > 0 ? (int32_t)(n - 1) : 0;
return v;
}
/* ================================================================== sizing */
namespace {
constexpr int64_t kAlign = 256;
int64_t align_up(int64_t v) { return (v + kAlign - 1) / kAlign * kAlign; }
/* Region offsets and sizes, in the enum's order (video_driver.h), and the total; shared by the
* allocation and the VRAM budget. */
int64_t carve(const RadVideoGenDecl& d, int64_t max_tok, int64_t (*bytes)[2], int n) {
const int64_t want[] = {
d.max_text * 4, /* R_TOK */
d.max_text * 4, /* R_POS */
2 * 4, /* R_CU */
3 * max_tok * 4, /* R_ROPE: a step's rotary positions */
RAD_VGEOM_N * 4, /* R_GEOM */
6 * 4, /* R_SCHED */
d.max_steps * 4, /* R_TV */
d.max_steps * 4, /* R_TA */
4 * 4, /* R_SEED */
4, /* R_LANE */
4, /* R_FIRST */
4 * 4, /* R_SEG */
4 * 4, /* R_LAT */
};
int64_t off = 0;
for (int r = 0; r < n; ++r) {
bytes[r][0] = off;
bytes[r][1] = want[r];
off = align_up(off + want[r]);
}
return off;
}
int64_t frames_bytes_of(const RadVideoGenDecl& d) {
return (d.frames_per_chunk + d.frames_tail) * d.max_area * 3;
}
/* The samples a channel of a soundtrack under `frames` frames: its latents rounded up, which
* bounds the rounding video_shape does. */
int64_t samples_of(const RadVideoGenDecl& d, int32_t frames) {
const int64_t num = (int64_t)frames * d.fps_den * d.audio_rate;
return (num / d.fps_num + 1) * (d.sample_rate / d.audio_rate);
}
} /* namespace */
int64_t VideoDriver::device_bytes(const Program& prog) {
if (!prog.is_video_generator()) return 0;
int64_t b[R_N][2];
return carve(prog.video_gen, prog.ctx.max_tok, b, R_N);
}
int VideoDriver::init(const Program& prog, PositionsFn positions,
const std::vector<RankIO>& ranks) {
fini();
if (!prog.is_video_generator()) return RAD_E_STATE;
decl_ = prog.video_gen;
rungs_ = prog.vgen_str.rungs;
decl_.rungs = rungs_.empty() ? nullptr : rungs_.data();
name_ = prog.vgen_str.name;
ranks_ = ranks;
positions_ = positions;
max_tok_ = prog.ctx.max_tok;
if (!positions_) {
RAD_ERR("video generator '%s': the plugin exports no rad_arch_video_positions, which a "
"video generator must", name_.c_str());
return RAD_E_UNSUPPORTED;
}
if (max_tok_ < decl_.max_text) {
RAD_ERR("video generator '%s': a pass carries %lld rows and a prompt may be %lld tokens",
name_.c_str(), (long long)max_tok_, (long long)decl_.max_text);
return RAD_E_UNSUPPORTED;
}
int64_t b[R_N][2];
bytes_ = carve(decl_, max_tok_, b, R_N);
for (int r = 0; r < R_N; ++r) { reg_[r].off = b[r][0]; reg_[r].bytes = b[r][1]; reg_[r].used = 0; }
frames_bytes_ = frames_bytes_of(decl_);
audio_bytes_ = samples_of(decl_, (int32_t)(decl_.frames_per_chunk * decl_.max_chunks +
decl_.frames_tail)) *
decl_.audio_channels * 4;
host_ = static_cast<char*>(rad_dev_alloc(bytes_, RAD_MEM_HOST_PINNED));
frames_host_ = static_cast<uint8_t*>(rad_dev_alloc(frames_bytes_, RAD_MEM_HOST_PINNED));
audio_host_ = static_cast<float*>(rad_dev_alloc(audio_bytes_, RAD_MEM_HOST_PINNED));
if (!host_ || !frames_host_ || !audio_host_) {
RAD_ERR("video generator: no pinned host memory for the pass staging and outputs (%lld + "
"%lld + %lld bytes)", (long long)bytes_, (long long)frames_bytes_,
(long long)audio_bytes_);
return RAD_E_NOMEM;
}
std::memset(host_, 0, (size_t)bytes_);
dev_.assign(ranks_.size(), nullptr);
for (size_t r = 0; r < ranks_.size(); ++r) {
RAD_TRY(rad_dev_set(ranks_[r].device));
dev_[r] = rad_dev_alloc(bytes_, RAD_MEM_DEVICE);
if (!dev_[r]) {
RAD_ERR("video generator: rank %zu has no room for the pass staging (%lld bytes)", r,
(long long)bytes_);
return RAD_E_NOMEM;
}
}
if (!ranks_.empty()) RAD_TRY(rad_dev_set(ranks_[0].device));
out_.assign(ranks_.size(), RadBatch{});
vout_.assign(ranks_.size(), RadVideoGenBatch{});
free_lanes_.clear();
for (int64_t i = decl_.max_lanes - 1; i >= 0; --i) free_lanes_.push_back((int32_t)i);
return RAD_OK;
}
void VideoDriver::fini() {
for (size_t r = 0; r < dev_.size(); ++r)
if (dev_[r]) {
if (r < ranks_.size()) rad_dev_set(ranks_[r].device);
rad_dev_free(dev_[r], RAD_MEM_DEVICE);
}
dev_.clear();
if (!ranks_.empty()) rad_dev_set(ranks_[0].device);
if (host_) rad_dev_free(host_, RAD_MEM_HOST_PINNED);
if (frames_host_) rad_dev_free(frames_host_, RAD_MEM_HOST_PINNED);
if (audio_host_) rad_dev_free(audio_host_, RAD_MEM_HOST_PINNED);
host_ = nullptr;
frames_host_ = nullptr;
audio_host_ = nullptr;
}
/* ================================================================== requests */
int VideoDriver::submit(std::unique_ptr<VideoRequest> r, std::string* why) {
if (!r || !r->ticket) return RAD_E_INVAL;
const RadVideoGenDecl& d = decl_;
auto no = [&](const std::string& w) {
if (why) *why = w;
return RAD_E_INVAL;
};
const int64_t T = (int64_t)r->tokens.size();
if (T < 1 || T > d.max_text)
return no("the prompt is " + std::to_string(T) + " tokens; this model takes 1.." +
std::to_string(d.max_text));
if (r->chunks < d.min_chunks || r->chunks > d.max_chunks)
return no("the length must be " + std::to_string(d.min_chunks) + ".." +
std::to_string(d.max_chunks) + " chunks");
const int64_t W = r->width, H = r->height;
if (W % d.size_multiple || H % d.size_multiple || W < d.min_side || H < d.min_side ||
W * H > d.max_area || std::max(W, H) > d.max_aspect * std::min(W, H))
return no("the size " + std::to_string(W) + "x" + std::to_string(H) + " is not one this "
"model makes: sides multiples of " + std::to_string(d.size_multiple) + " from " +
std::to_string(d.min_side) + ", at most " + std::to_string(d.max_area) +
" pixels, the long side at most " + std::to_string(d.max_aspect) +
" times the short");
const int32_t steps = r->steps > 0 ? r->steps : (int32_t)d.default_steps;
if (d.n_rungs > 0 && steps != d.n_rungs + 1)
return no("num_inference_steps must be " + std::to_string(d.n_rungs + 1) + ": this model "
"runs the schedule it was trained on, " + std::to_string(d.n_rungs) +
" evaluations");
if (steps < 2 || steps > d.max_steps)
return no("num_inference_steps must be 2.." + std::to_string(d.max_steps) + " (sigma grid "
"points, the last one 0)");
auto j = std::make_unique<Job>();
const VideoShape s = video_shape(d, r->width, r->height, r->chunks);
j->geom.n_text = (int32_t)T;
j->geom.frames = s.frames;
j->geom.lat_frames = s.lat_frames;
j->geom.lat_h = s.lat_h;
j->geom.lat_w = s.lat_w;
j->geom.n_audio = s.n_audio;
j->rows = T + s.audio_rows + s.video_rows;
if (j->rows > max_tok_)
return no("a step of this video is " + std::to_string(j->rows) + " rows and a pass "
"carries " + std::to_string(max_tok_) + "; ask for a shorter or smaller video");
const int64_t nr = positions_(RAD_VPOS_STEP, &j->geom, nullptr, 0);
const int64_t nd = positions_(RAD_VPOS_DECODE, &j->geom, nullptr, 0);
if (nr != j->rows || nd <= 0 || nd > max_tok_)
return no("the model lays this video out in " + std::to_string(nr) + " step rows and " +
std::to_string(nd) + " decoder rows, which this server cannot run");
j->dec_rows = nd;
j->pos.assign((size_t)(3 * nr), 0.0f);
if (positions_(RAD_VPOS_STEP, &j->geom, j->pos.data(), nr) != nr)
return no("the model could not lay this video out");
j->sched = video_schedule(d, steps);
if (j->sched.steps < 1) return no("the schedule has no steps");
j->n_chunks = r->chunks;
j->n_samples = (int64_t)s.n_audio * (d.sample_rate / d.audio_rate);
VideoTicket& t = *r->ticket;
t.frames = s.frames;
t.width = r->width;
t.height = r->height;
t.steps = j->sched.steps;
t.sample_rate = d.sample_rate;
t.channels = d.audio_channels;
t.fps = (double)d.fps_num / (double)d.fps_den;
t.in_tokens = T;
t.rows = j->rows;
t.t_submit_ns = (int64_t)rad_mono_ns();
std::lock_guard<std::mutex> lk(mu_);
if (closed_) {
if (why) *why = closed_why_;
return closed_status_;
}
j->id = next_id_++;
j->req = std::move(r);
jobs_.push_back(std::move(j));
return RAD_OK;
}
void VideoDriver::shutdown(const char* why, int status) {
std::lock_guard<std::mutex> lk(mu_);
closed_ = true;
closed_why_ = why ? why : "the engine stopped";
closed_status_ = status;
for (auto& j : jobs_) j->req->ticket->finish(status, closed_why_);
}
int64_t VideoDriver::queued() const {
std::lock_guard<std::mutex> lk(mu_);
int64_t n = 0;
for (const auto& j : jobs_) if (!j->admitted) ++n;
return n;
}
int64_t VideoDriver::running() const {
std::lock_guard<std::mutex> lk(mu_);
int64_t n = 0;
for (const auto& j : jobs_) if (j->admitted) ++n;
return n;
}
VideoDriver::Job* VideoDriver::job_locked(uint64_t id) {
for (auto& j : jobs_) if (j->id == id) return j.get();
return nullptr;
}
void VideoDriver::release_locked(Job& j) {
if (j.lane >= 0) {
free_lanes_.push_back(j.lane);
j.lane = -1;
}
}
void VideoDriver::fail_locked(Job& j, int status, const std::string& why) {
j.failed = true;
j.req->ticket->finish(status, why);
}
/* In arrival order: a request needs only a lane. */
void VideoDriver::admit_locked() {
for (auto& jp : jobs_) {
Job& j = *jp;
if (j.admitted || j.failed) continue;
if (free_lanes_.empty()) break;
j.lane = free_lanes_.back();
free_lanes_.pop_back();
j.admitted = true;
}
}
/* ================================================================== staging */
int VideoDriver::upload() {
for (size_t r = 0; r < ranks_.size(); ++r)
for (int g = 0; g < R_N; ++g) {
if (reg_[g].used <= 0) continue;
RAD_TRY(rad_memcpy_async((char*)dev_[r] + reg_[g].off, host_ + reg_[g].off,
reg_[g].used, ranks_[r].stream));
}
return RAD_OK;
}
/* The geometry a pass's ops read off the device (RAD_VGEOM_*), with chunk `chunk`'s span when it
* is a decode's. */
void VideoDriver::stage_geom(const Job& j, int32_t chunk) {
int32_t* g = hptr<int32_t>(R_GEOM);
std::memset(g, 0, RAD_VGEOM_N * 4);
g[RAD_VGEOM_LAT_FRAMES] = j.geom.lat_frames;
g[RAD_VGEOM_LAT_H] = j.geom.lat_h;
g[RAD_VGEOM_LAT_W] = j.geom.lat_w;
g[RAD_VGEOM_N_TEXT] = j.geom.n_text;
g[RAD_VGEOM_N_AUDIO] = j.geom.n_audio;
g[RAD_VGEOM_CHUNK_LAT0] = (int32_t)(decl_.latents_per_chunk * chunk);
g[RAD_VGEOM_CHUNK_FRAMES] = (int32_t)decl_.dec_latents;
g[RAD_VGEOM_CHUNK_H] = j.geom.lat_h;
g[RAD_VGEOM_CHUNK_W] = j.geom.lat_w;
g[RAD_VGEOM_CHUNK_FIRST] = chunk == 0;
g[RAD_VGEOM_CHUNK_LAST] = chunk == j.n_chunks - 1;
g[RAD_VGEOM_PATCH_FRAMES] = (int32_t)decl_.dec_latents;
g[RAD_VGEOM_PATCH_H] = (int32_t)(j.geom.lat_h / decl_.patch);
g[RAD_VGEOM_PATCH_W] = (int32_t)(j.geom.lat_w / decl_.patch);
reg_[R_GEOM].used = RAD_VGEOM_N * 4;
const int64_t audio_rows = decl_.audio_channels * (int64_t)j.geom.n_audio;
const int64_t video_rows = j.rows - j.geom.n_text - audio_rows;
*hptr<int32_t>(R_LANE) = j.lane;
*hptr<int32_t>(R_FIRST) = j.step == 0;
int32_t* seg = hptr<int32_t>(R_SEG);
seg[0] = 0;
seg[1] = j.geom.n_text;
seg[2] = (int32_t)(j.geom.n_text + audio_rows);
seg[3] = (int32_t)j.rows;
int32_t* lat = hptr<int32_t>(R_LAT);
lat[0] = 0;
lat[1] = (int32_t)video_rows;
lat[2] = 0;
lat[3] = (int32_t)audio_rows;
reg_[R_LANE].used = 4;
reg_[R_FIRST].used = 4;
reg_[R_SEG].used = 4 * 4;
reg_[R_LAT].used = 4 * 4;
}
void VideoDriver::base_batches(const Job& j, int64_t n_tok, int step) {
for (size_t r = 0; r < ranks_.size(); ++r) {
RadBatch& B = out_[r];
RadVideoGenBatch& V = vout_[r];
const int ri = (int)r;
B = RadBatch{};
B.step = step;
B.phase = RAD_PHASE_PREFILL;
B.n_tok = n_tok;
B.n_seq = 1;
B.max_q_len = (int32_t)n_tok;
B.max_q_len_prefill = (int32_t)n_tok;
B.token_ids = dptr<int32_t>(ri, R_TOK);
B.positions = dptr<int32_t>(ri, R_POS);
B.cu_seqlens = dptr<int32_t>(ri, R_CU);
V = RadVideoGenBatch{};
V.lane = j.lane;
V.geom = j.geom;
V.geom_d = dptr<int32_t>(ri, R_GEOM);
V.lane_d = dptr<int32_t>(ri, R_LANE);
V.first_d = dptr<int32_t>(ri, R_FIRST);
V.seg_cu = dptr<int32_t>(ri, R_SEG);
V.lat_cu = dptr<int32_t>(ri, R_LAT);
V.n_steps = j.sched.steps;
V.t_video = dptr<float>(ri, R_TV);
V.t_audio = dptr<float>(ri, R_TA);
V.step = j.step;
V.sched = dptr<float>(ri, R_SCHED);
V.pos = dptr<float>(ri, R_ROPE);
V.seed = dptr<uint32_t>(ri, R_SEED);
V.chunk = j.chunk;
V.n_chunks = j.n_chunks;
V.dec_rows = j.dec_rows;
V.n_samples = j.n_samples;
B.vgen_b = &V;
}
}
/* ================================================================== the passes */
const RadBatch* VideoDriver::next(int step) {
std::lock_guard<std::mutex> lk(mu_);
pass_ = Pass{};
rb_.clear();
if (closed_) return nullptr;
/* Retire finished, failed and cancelled jobs, returning their lanes before admitting. Safe
* because next() runs between passes, with nothing in flight. */
for (auto it = jobs_.begin(); it != jobs_.end();) {
Job& j = **it;
const bool cancelled = j.req->ticket->cancel.load(std::memory_order_acquire);
if (!(j.failed || cancelled || j.finished)) { ++it; continue; }
if (cancelled && !j.failed && !j.finished)
j.req->ticket->finish(RAD_E_CANCELLED, "the request was cancelled");
release_locked(j);
it = jobs_.erase(it);
}
admit_locked();
/* 1. The decodes of a denoised lane: the soundtrack, then the chunks in order. */
for (auto& jp : jobs_) {
Job& j = *jp;
if (!j.admitted || j.failed || j.step < j.sched.steps) continue;
if (!j.audio_done) return build_audio(j, step);
if (j.chunk < j.n_chunks) return build_chunk(j, step);
}
/* 2. A prompt. */
for (auto& jp : jobs_) {
Job& j = *jp;
if (j.admitted && !j.failed && !j.cond_done) return build_cond(j, step);
}
/* 3. The oldest lane's next step. */
for (auto& jp : jobs_) {
Job& j = *jp;
if (j.admitted && !j.failed && j.cond_done && j.step < j.sched.steps)
return build_step(j, step);
}
return nullptr;
}
const RadBatch* VideoDriver::batch_for(int rank) const {
if (rank < 0 || (size_t)rank >= out_.size() || pass_.kind == 0) return nullptr;
return &out_[(size_t)rank];
}
const RadBatch* VideoDriver::build_cond(Job& j, int step) {
for (int g = 0; g < R_N; ++g) reg_[g].used = 0;
const int64_t T = j.geom.n_text;
int32_t* tok = hptr<int32_t>(R_TOK);
int32_t* pos = hptr<int32_t>(R_POS);
std::memcpy(tok, j.req->tokens.data(), (size_t)T * 4);
for (int64_t i = 0; i < T; ++i) pos[i] = (int32_t)i;
int32_t* cu = hptr<int32_t>(R_CU);
cu[0] = 0;
cu[1] = (int32_t)T;
float* tv = hptr<float>(R_TV);
float* ta = hptr<float>(R_TA);
for (int32_t i = 0; i < j.sched.steps; ++i) {
tv[i] = 1.0f - j.sched.sig_v[(size_t)i];
ta[i] = 1.0f - j.sched.sig_a[(size_t)i];
}
reg_[R_TOK].used = T * 4;
reg_[R_POS].used = T * 4;
reg_[R_CU].used = 2 * 4;
reg_[R_TV].used = j.sched.steps * 4;
reg_[R_TA].used = j.sched.steps * 4;
stage_geom(j, 0);
if (upload() < 0) return nullptr;
base_batches(j, T, step);
for (auto& B : out_) B.gen = RAD_GEN_PASS_VCOND;
pass_.kind = RAD_GEN_PASS_VCOND;
pass_.job = j.id;
return &out_[0];
}
const RadBatch* VideoDriver::build_step(Job& j, int step) {
for (int g = 0; g < R_N; ++g) reg_[g].used = 0;
const int32_t i = j.step;
float* s = hptr<float>(R_SCHED);
s[0] = 1.0f - j.sched.sig_v[(size_t)i];
s[1] = j.sched.sig_v[(size_t)i];
s[2] = j.sched.sig_v[(size_t)i + 1];
s[3] = 1.0f - j.sched.sig_a[(size_t)i];
s[4] = j.sched.sig_a[(size_t)i];
s[5] = j.sched.sig_a[(size_t)i + 1];
reg_[R_SCHED].used = 6 * 4;
std::memcpy(hptr<float>(R_ROPE), j.pos.data(), j.pos.size() * 4);
reg_[R_ROPE].used = (int64_t)j.pos.size() * 4;
/* The video's noise seed is the request's; the soundtrack's the same with its top bit flipped,
* so the two streams never coincide. */
uint32_t* sd = hptr<uint32_t>(R_SEED);
const uint64_t seed = j.req->seed;
sd[0] = (uint32_t)seed;
sd[1] = (uint32_t)(seed >> 32);
sd[2] = (uint32_t)seed;
sd[3] = (uint32_t)(seed >> 32) ^ 0x80000000u;
reg_[R_SEED].used = 4 * 4;
/* The packed sequence is one attention document. */
int32_t* cu = hptr<int32_t>(R_CU);
cu[0] = 0;
cu[1] = (int32_t)j.rows;
reg_[R_CU].used = 2 * 4;
stage_geom(j, 0);
if (upload() < 0) return nullptr;
base_batches(j, j.rows, step);
for (auto& B : out_) B.gen = RAD_GEN_PASS_VSTEP;
pass_.kind = RAD_GEN_PASS_VSTEP;
pass_.job = j.id;
return &out_[0];
}
const RadBatch* VideoDriver::build_audio(Job& j, int step) {
for (int g = 0; g < R_N; ++g) reg_[g].used = 0;
stage_geom(j, 0);
if (upload() < 0) return nullptr;
base_batches(j, 0, step);
for (auto& B : out_) B.gen = RAD_GEN_PASS_ADECODE;
rb_.assign(1, Readback{ decl_.audio_out, j.n_samples * decl_.audio_channels * 4, audio_host_ });
pass_.kind = RAD_GEN_PASS_ADECODE;
pass_.job = j.id;
return &out_[0];
}
const RadBatch* VideoDriver::build_chunk(Job& j, int step) {
for (int g = 0; g < R_N; ++g) reg_[g].used = 0;
stage_geom(j, j.chunk);
if (upload() < 0) return nullptr;
base_batches(j, j.dec_rows, step);
const bool last = j.chunk == j.n_chunks - 1;
const int32_t n = (int32_t)(decl_.frames_per_chunk + (last ? decl_.frames_tail : 0));
for (size_t r = 0; r < out_.size(); ++r) {
out_[r].gen = RAD_GEN_PASS_VDECODE;
vout_[r].n_frames_out = n;
}
const int64_t bytes = (int64_t)n * j.req->height * j.req->width * 3;
rb_.assign(1, Readback{ decl_.frames_out, bytes, frames_host_ });
pass_.kind = RAD_GEN_PASS_VDECODE;
pass_.job = j.id;
pass_.n_frames = n;
return &out_[0];
}
int VideoDriver::done() {
std::lock_guard<std::mutex> lk(mu_);
const int64_t now = (int64_t)rad_mono_ns();
Job* j = job_locked(pass_.job);
switch (j ? pass_.kind : 0) {
case RAD_GEN_PASS_VCOND:
j->cond_done = true;
j->req->ticket->t_cond_ns = now;
break;
case RAD_GEN_PASS_VSTEP: {
++j->step;
VideoEvent e;
e.kind = VideoEvent::STEP;
e.steps_done = j->step;
j->req->ticket->push(std::move(e));
if (j->step >= j->sched.steps) j->req->ticket->t_denoised_ns = now;
break;
}
case RAD_GEN_PASS_ADECODE: {
VideoEvent e;
e.kind = VideoEvent::AUDIO;
e.samples.assign(audio_host_, audio_host_ + j->n_samples * decl_.audio_channels);
j->req->ticket->push(std::move(e));
j->audio_done = true;
break;
}
case RAD_GEN_PASS_VDECODE: {
VideoEvent e;
e.kind = VideoEvent::FRAMES;
e.first = j->frames_out;
e.n = pass_.n_frames;
const size_t bytes = (size_t)pass_.n_frames * j->req->height * j->req->width * 3;
e.rgb.assign(frames_host_, frames_host_ + bytes);
j->req->ticket->push(std::move(e));
j->frames_out += pass_.n_frames;
if (++j->chunk == j->n_chunks) {
j->finished = true;
j->req->ticket->t_done_ns = now;
j->req->ticket->finish(RAD_OK);
}
break;
}
default:
break;
}
pass_ = Pass{};
rb_.clear();
return RAD_OK;
}
} /* namespace gen */
} /* namespace rad */
+141
View File
@@ -0,0 +1,141 @@
/* video_driver.h -- the video generator's pass driver (video.h; abi/rad_builder.h's
* RadVideoGenDecl describes the passes).
*
* Driven by the engine thread like the other drivers (driver.h): `next()` picks and stages a
* pass, `done()` folds its result back once every rank has run it. Requests arrive from HTTP
* threads through `submit()` and leave through their VideoTicket.
*
* A request holds a lane from admission to its last chunk. Its geometry, schedule and rotary
* positions are fixed at submit, so nothing is computed between passes but the staging.
*
* Pass priority, one pass at a time:
*
* 1. ADECODE, then each VDECODE chunk in order, of a lane whose denoising is done: they finish
* a request and free its lane.
* 2. VCOND of an admitted request, so its steps can follow the current request's without a gap.
* 3. VSTEP of the oldest lane with steps left. Requests are denoised one after another, not in
* turns: a pass is one request's whole sequence, so taking turns would only delay the first.
*/
#pragma once
#include "video.h"
#include "pass.h"
#include "device/device.h"
#include <mutex>
namespace rad {
namespace gen {
class VideoDriver final : public IPassDriver {
public:
struct RankIO {
int device = 0;
RadStream stream = nullptr;
};
using PositionsFn = int64_t (*)(int, const RadVideoGeom*, float*, int64_t);
/* `positions` is the plugin's rad_arch_video_positions. */
int init(const Program& prog, PositionsFn positions, const std::vector<RankIO>& ranks);
void fini();
~VideoDriver() override { fini(); }
/* The bytes init() allocates on each rank's card, for the VRAM budget. */
static int64_t device_bytes(const Program& prog);
/* ---------------------------------------------------------- HTTP threads */
/* Queue a request, refused at once with `why` when it can never run. */
int submit(std::unique_ptr<VideoRequest> r, std::string* why);
const RadVideoGenDecl& decl() const { return decl_; }
void shutdown(const char* why, int status) override;
/* ---------------------------------------------------------- the engine thread */
const RadBatch* next(int step) override;
const RadBatch* batch_for(int rank) const override;
const std::vector<Readback>& readbacks() const override { return rb_; }
int done() override;
int64_t queued() const override;
int64_t running() const override;
private:
struct Job {
uint64_t id = 0;
std::unique_ptr<VideoRequest> req;
RadVideoGeom geom{};
int64_t rows = 0, dec_rows = 0;
int32_t n_chunks = 0;
int64_t n_samples = 0; /* the soundtrack's samples a channel */
VideoSchedule sched;
std::vector<float> pos; /* [3, rows] */
int32_t lane = -1;
bool admitted = false;
bool cond_done = false;
int32_t step = 0; /* steps done */
bool audio_done = false;
int32_t chunk = 0; /* chunks decoded */
int32_t frames_out = 0; /* frames handed to the caller */
bool failed = false;
bool finished = false;
};
/* The pass in flight, for done(). */
struct Pass {
int kind = 0;
uint64_t job = 0;
int32_t n_frames = 0;
};
/* Staging regions: their offsets in the host span and every rank's slab. */
struct Region { int64_t off = 0, bytes = 0, used = 0; };
enum { R_TOK, R_POS, R_CU, R_ROPE, R_GEOM, R_SCHED, R_TV, R_TA, R_SEED, R_LANE, R_FIRST,
R_SEG, R_LAT, R_N };
template <class T> T* hptr(int r) const { return reinterpret_cast<T*>(host_ + reg_[r].off); }
template <class T> T* dptr(int rank, int r) const {
return reinterpret_cast<T*>((char*)dev_[(size_t)rank] + reg_[r].off);
}
int upload();
void base_batches(const Job& j, int64_t n_tok, int step);
void stage_geom(const Job& j, int32_t chunk);
void admit_locked();
void release_locked(Job& j);
void fail_locked(Job& j, int status, const std::string& why);
Job* job_locked(uint64_t id);
const RadBatch* build_cond(Job& j, int step);
const RadBatch* build_step(Job& j, int step);
const RadBatch* build_audio(Job& j, int step);
const RadBatch* build_chunk(Job& j, int step);
RadVideoGenDecl decl_{};
std::vector<double> rungs_; /* decl_.rungs points here */
std::string name_;
PositionsFn positions_ = nullptr;
int64_t max_tok_ = 0;
std::vector<RankIO> ranks_;
char* host_ = nullptr; /* pinned, same layout as each slab */
int64_t bytes_ = 0;
std::vector<void*> dev_;
Region reg_[R_N];
uint8_t* frames_host_ = nullptr;
int64_t frames_bytes_ = 0;
float* audio_host_ = nullptr;
int64_t audio_bytes_ = 0;
std::vector<Readback> rb_;
std::vector<RadBatch> out_; /* one per rank */
std::vector<RadVideoGenBatch> vout_;
Pass pass_;
mutable std::mutex mu_;
std::deque<std::unique_ptr<Job>> jobs_; /* arrival order */
std::vector<int32_t> free_lanes_;
uint64_t next_id_ = 1;
bool closed_ = false;
std::string closed_why_;
int closed_status_ = RAD_E_STATE;
};
} /* namespace gen */
} /* namespace rad */
+5 -9
View File
@@ -2,11 +2,9 @@
* --lora-target-modules). Read by declare (which sites and pools exist), by the adapter manager
* (what may be loaded into them) and by nothing else.
*
* OFF UNLESS ASKED FOR: with no adapter named and no --max-loras, `enabled()` is false, declare
* appends nothing, the program has no pool and no extra op, and the engine computes exactly what it
* computed before this file existed. */
* Off unless asked for: with no adapter named and no --max-loras, `enabled()` is false, declare
* appends nothing, the program has no pool and no extra op, and no step carries an adapter slot. */
#pragma once
#include <set>
#include <string>
#include <utility>
#include <vector>
@@ -20,11 +18,9 @@ struct LoraConfig {
int max_loras = 0;
/* The rank every slot is sized for; an adapter of lower rank is zero-padded into it. */
int max_rank = 16;
/* HF module leaf names (q_proj, gate_proj, in_proj_qkv, ...) the sites are built for. Empty:
* the union of the startup adapters' target_modules, or -- with no startup adapter -- every
* LoRA-capable trunk linear (`all_linear`). */
std::set<std::string> targets;
bool all_linear = false;
/* HF module leaf names (q_proj, gate_proj, in_proj_qkv, ...) the sites are built for, sorted
* and unique. Empty: the union of the startup adapters' target_modules. */
std::vector<std::string> targets;
bool enabled() const { return max_loras > 0 || !adapters.empty(); }
int slots() const {
+57 -16
View File
@@ -28,6 +28,38 @@ bool is_coded(uint32_t dt) {
return dt == RAD_F8E4M3 || dt == RAD_F8E5M2 || dt == RAD_I8;
}
/* The block of a scale stream of `blocks` groups over `ext` elements, as the kernel libraries
* read one (libref/ref_gemm.h's grid_block): the power of two whose ceiling division gives
* `blocks`, else the plain ceiling; one group is the whole extent. */
int64_t grid_block(int64_t ext, int64_t blocks) {
if (ext <= 0) return 1;
if (blocks <= 1) return ext;
const int64_t lo = (ext + blocks - 1) / blocks;
int64_t b = 1;
while (b < lo) b <<= 1;
return (ext + b - 1) / b == blocks ? b : lo;
}
/* The scale grid of a coded activation the GEMM `reads`: the read set's one f32 buffer beside
* the codes (reads[0]), [rows, groups] or one scale a row, over the codes' full width. The
* GEMM's own `group` is the weight's (an MXFP4 weight's 32-wide exponent block reads an
* activation scaled per 128), and a GEMM may read a column span of the activation, so neither
* its `group` nor its K gives the activation's grid. 0 when the stream is not one f32 buffer. */
int64_t activation_grid(const Program& P, const std::vector<rad_buf>& reads) {
const RadBufDecl& a = P.buffers[reads[0]].decl;
const RadBufDecl* s = nullptr;
for (size_t i = 1; i < reads.size(); ++i) {
const RadBufDecl& d = P.buffers[reads[i]].decl;
if (d.dtype != RAD_F32) continue;
if (s) return 0;
s = &d;
}
if (!s || a.rank < 1 || s->rank < 1) return 0;
const int64_t width = a.shape[a.rank - 1];
const int64_t groups = s->rank >= 2 ? s->shape[s->rank - 1] : 1;
return groups > 0 ? grid_block(width, groups) : 0;
}
rad_buf decl_persist(Builder& b, const std::string& name, uint32_t dtype, uint32_t rank,
const int64_t* shape) {
RadBufDecl d{};
@@ -44,6 +76,16 @@ rad_buf decl_persist(Builder& b, const std::string& name, uint32_t dtype, uint32
int lora_declare(Builder& b, const LoraDeclare& d) {
if (!d.cfg || !d.cfg->enabled()) return RAD_OK;
Program& P = b.program();
/* Adapters are chosen per request and applied on the token steps of a model that writes
* logits; a generator's passes and an embedding model's requests carry no adapter. */
if (P.is_pass_driven() || P.pooled_buf != RAD_NULL_HANDLE ||
P.logits_buf == RAD_NULL_HANDLE) {
RAD_ERR("lora: runtime LoRA adapters serve a model that generates text, and this one %s",
P.is_pass_driven() ? "is an image, audio or video generator"
: P.pooled_buf != RAD_NULL_HANDLE ? "makes embeddings"
: "declares no logits");
return RAD_E_UNSUPPORTED;
}
const int S = d.cfg->slots();
const int max_rank = d.cfg->max_rank;
const int64_t max_tok = P.ctx.max_tok;
@@ -53,10 +95,8 @@ int lora_declare(Builder& b, const LoraDeclare& d) {
return RAD_E_INVAL;
}
/* EVERY READER OF A TARGETED WEIGHT CARRIES THE DELTA, OR STARTUP REFUSES. A targeted weight
* that some op multiplies without the adapter is a model that is the base in one place and the
* adapter in another, and the text it writes is wrong in a way no test of the targeted GEMM
* would show. */
/* Every reader of a targeted weight carries the delta, or startup refuses: a weight some op
* multiplies without the adapter would be the base in one place and the adapter in another. */
std::vector<lora::UnsupportedUse> bad;
int s = lora::find_unsupported_uses(P, d.targets, &bad);
if (s < 0) return s;
@@ -110,10 +150,10 @@ int lora_declare(Builder& b, const LoraDeclare& d) {
}
}
/* ---- t = A.x, one f32 plane per capacity R and lane. PERSIST and not TRANSIENT: the ops that
* use it are issued inside the GEMM's issue, at the GEMM's position, while the buffer plan would
* place a transient by the appended ops' own position at the end of the program -- and share
* its bytes with whatever is live there. */
/* ---- t = A.x, one f32 plane per capacity R and lane. Persistent, not transient: the ops that
* use it run at the GEMM's position, but the buffer plan would place a transient at the
* appended ops' own position, the end of the program, and share its bytes with buffers live
* mid-program. */
std::map<int64_t, int32_t> t_by_r;
P.lora_t.clear();
for (const lora::Site& x : sites) {
@@ -136,14 +176,13 @@ int lora_declare(Builder& b, const LoraDeclare& d) {
const uint32_t gh = x.gemm;
if (gh == 0 || gh >= P.ops.size()) return RAD_E_STATE;
if (!b.op_resolved(gh)) continue; /* never handed to the plugin, so never issued */
/* Copied out first: decl_op below appends to P.ops and moves every OpInfo. */
/* Copied out first: decl_op below appends to P.ops, which may move every OpInfo. */
const OpInfo& g = P.ops[gh];
const std::string gop = g.op;
const std::string rkey = g.ranged_key;
const int64_t lo = g.range_lo, hi = g.range_hi;
long long gk = 0, gn = 0, gg = 0;
long long gk = 0, gn = 0;
const bool has_k = g.base.get_i("K", &gk), has_n = g.base.get_i("N", &gn);
const bool has_group = g.base.get_i("group", &gg) && gg > 0;
const int oa = opd_index(g, "a"), oas = opd_index(g, "a_scale"), oy = opd_index(g, "y");
const std::vector<rad_buf> reads = b.op_read_set(gh), writes = b.op_write_set(gh);
@@ -167,6 +206,12 @@ int lora_declare(Builder& b, const LoraDeclare& d) {
const uint32_t y_dt = P.buffers[writes[0]].decl.dtype;
const bool coded = is_coded(a_dt);
if (coded && oas < 0) { refuse("a coded activation and no `a_scale` operand"); continue; }
const int64_t a_grid = coded ? activation_grid(P, reads) : 0;
if (coded && a_grid <= 0) {
refuse("a coded activation whose read set holds no single f32 scale stream beside the "
"codes, so the grid lora_shrink reads it at is not known at declare");
continue;
}
RadParam sp[6];
int n_sp = 0;
@@ -174,7 +219,7 @@ int lora_declare(Builder& b, const LoraDeclare& d) {
sp[n_sp++] = RAD_INT("K", x.K_r);
sp[n_sp++] = RAD_INT("R", x.R);
sp[n_sp++] = RAD_INT("S", S);
if (coded && has_group) sp[n_sp++] = RAD_INT("group", gg);
if (coded) sp[n_sp++] = RAD_INT("group", a_grid);
sp[n_sp++] = RAD_STR("dtype", rad_dtype_name(a_dt));
const rad_op hs = b.decl_op("lora_shrink", sp, n_sp, nullptr, 0);
@@ -200,10 +245,6 @@ int lora_declare(Builder& b, const LoraDeclare& d) {
P.ops[he].anchor = (int32_t)gh;
P.ops[gh].lora_site = (int32_t)P.lora_sites.size();
P.lora_sites.push_back(is);
x.lora_shrink = hs; x.lora_expand = he;
const LoraPool& lp = P.lora_pools[(size_t)x.pool];
x.pool_a = lp.a; x.pool_b = lp.b; x.pool_scale = lp.scale;
}
if (n_refused) return RAD_E_UNSUPPORTED;
+3 -3
View File
@@ -2,9 +2,9 @@
* its program, build the sites (lora.h), declare the adapter pools and the two ops each targeted
* GEMM is followed by, and record what the issue path needs (Program::lora_sites).
*
* Runs inside rad_tools_declare, after rad_arch_declare and before the sampler, on the real
* declare AND on every sizing declare -- identically, because a sizing declare must produce the
* same op list (rad_builder.cpp checks it op by op). */
* Runs inside rad_tools_declare, after rad_arch_declare and before the sampler, identically on the
* real declare and on every sizing declare, which must produce the same op list (rad_builder.cpp
* checks it op by op). */
#pragma once
#include "lora/config.h"
#include "lora/lora.h"
+39 -52
View File
@@ -130,7 +130,7 @@ struct MapIndex {
}
};
/* THE predicate, over the maps already found. */
/* weight_targeted(), over the maps already found. */
bool targeted_core(const Program& prog, const WeightInfo& w,
const std::vector<const RadNameMap*>& maps, const TargetSet& targets) {
if (targets.empty() || maps.empty()) return false;
@@ -190,11 +190,6 @@ rad_weight b_weight(const OpInfo& op) {
return op.weights.empty() ? 0 : op.weights[0];
}
void fnv(uint64_t* h, const void* p, size_t n) {
const uint8_t* b = static_cast<const uint8_t*>(p);
for (size_t i = 0; i < n; ++i) { *h ^= b[i]; *h *= 1099511628211ull; }
}
bool read_file(const std::string& path, std::string* out) {
std::ifstream f(path, std::ios::binary);
if (!f) return false;
@@ -339,11 +334,9 @@ int make_site(const Program& prog, const MapIndex& mi, const TargetSet& targets,
Site s;
s.gemm = op_index;
s.op = op.op;
s.w = wh;
s.weight = W.name;
s.shard = W.decl.shard;
s.max_rank = max_rank;
s.res_unchecked = op.op == "gemm_nt_bias";
if (W.decl.rank != 2)
return fail(err, RAD_E_SHAPE, fmt("weight '%s' is rank %u; a LoRA site needs a matrix",
@@ -425,8 +418,8 @@ int make_site(const Program& prog, const MapIndex& mi, const TargetSet& targets,
int64_t N_full = 0;
for (int64_t t : s.part_total) N_full = (t > 0 && N_full >= 0) ? N_full + t : -1;
/* ---- THE LOADER'S OWN FUNCTION AGREES, or this is not a site. weight_share is what puts the
* base weight's bytes on this rank; asked for a plain [N_full, K_full] entry it must name the
/* ---- the loader's own cut must agree, or this is not a site: weight_share, which puts the
* base weight's bytes on this rank, must name for a plain [N_full, K_full] entry the
* rectangles this geometry names. */
if (N_full > 0 && s.K_full > 0) {
WeightInfo v = W;
@@ -483,7 +476,7 @@ int make_site(const Program& prog, const MapIndex& mi, const TargetSet& targets,
srcs.push_back(m->src[k] ? m->src[k] : "");
}
if (alternatives) {
/* COPY with alternatives: the first one the container holds IS the weight, and which one
/* COPY with alternatives: the first one the container holds is the weight, and which one
* that is is not recorded. Usable only when exactly one alternative is targeted. */
std::vector<std::string> hit;
for (const std::string& x : srcs) {
@@ -580,6 +573,15 @@ bool op_is_site(const Program& prog, const OpInfo& op, rad_weight* b_out, std::s
return no(fmt("gemm_nt_q over rotated parts (pb1=%lld pb2=%lld): its input is the "
"rotated activation", p1, p2));
}
if (gq || gqb) {
/* At w4a8, w8a8 and w2a8 `a` is quant_act_i8's codes in the int8 WMMA's step order (the
* middle dwords of every 16-byte step exchanged, docs/OPS.md), which lora_shrink would
* read as the activation's columns. */
const char* dt = op.base.get_s("dtype");
if (dt && (!std::strcmp(dt, "w4a8") || !std::strcmp(dt, "w8a8") || !std::strcmp(dt, "w2a8")))
return no(fmt("%s at %s reads quant_act_i8's codes in the int8 WMMA's step order, not "
"in the activation's column order", op.op.c_str(), dt));
}
const WeightInfo& w = prog.weights[b];
if (gq || gqb) {
long long k = 0;
@@ -607,7 +609,7 @@ int find_unsupported_uses(const Program& prog, const TargetSet& targets,
const bool site = op_is_site(prog, op, &b, &why);
for (rad_weight h : op.weights) {
if (!targeted_idx(prog, mi, h, targets)) continue;
/* Every view of a targeted weight read by a site over the SAME logical weight is the
/* Every view of a targeted weight read by a site over the same logical weight is the
* site's own (codes, scale, ref). Anything else reading it is not a site. */
if (site && b && prog.weights[b].source == prog.weights[h].source) continue;
UnsupportedUse u;
@@ -669,32 +671,6 @@ int build_sites(const Program& prog, const TargetSet& targets, int max_rank,
return RAD_OK;
}
TargetSet all_capable_targets(const Program& prog) {
std::set<std::string> leaves;
for (size_t h = 1; h < prog.weights.size(); ++h) {
const WeightInfo& w = prog.weights[h];
if (excluded_weight(prog, w)) continue;
std::vector<const RadNameMap*> maps;
scan_maps(prog, w.source, &maps);
for (const RadNameMap* m : maps)
for (int k = 0; k < m->n_src && k < 8; ++k) {
std::string leaf;
const std::string src = m->src[k] ? m->src[k] : "";
if (!module_of(src, &leaf).empty() && !excluded_source(src)) leaves.insert(leaf);
}
}
TargetSet ok;
for (const std::string& l : leaves) {
const TargetSet one{ l };
std::vector<Site> s;
std::string e;
if (find_unsupported_uses(prog, one, nullptr) == 0 && build_sites(prog, one, 1, &s, &e) == RAD_OK &&
!s.empty())
ok.insert(l);
}
return ok;
}
std::string explain_module(const Program& prog, const TargetSet& targets, const std::string& module) {
const std::string want[3] = {
module,
@@ -817,6 +793,17 @@ int load_adapter(const std::string& dir, const std::vector<Site>& sites, int max
if (truthy("trainable_token_indices"))
return fail(err, RAD_E_UNSUPPORTED, cfg_path + ": trainable_token_indices -- embedding "
"updates are not served");
/* PEFT options that change the forward pass itself, not only the weights. */
if (truthy("layer_replication"))
return fail(err, RAD_E_UNSUPPORTED, cfg_path + ": layer_replication -- an adapter over "
"repeated base layers is not served");
if (truthy("use_qalora"))
return fail(err, RAD_E_UNSUPPORTED, cfg_path + ": use_qalora -- QA-LoRA's pooled input is "
"not served");
if (truthy("alora_invocation_tokens"))
return fail(err, RAD_E_UNSUPPORTED, cfg_path + ": alora_invocation_tokens -- an activated "
"LoRA, which applies only after its "
"invocation, is not served");
if (!cfg.contains("r") || !cfg["r"].is_number_integer() || cfg["r"].get<int64_t>() <= 0)
return fail(err, RAD_E_FORMAT, cfg_path + ": no positive integer `r`");
if (!cfg.contains("lora_alpha") || !cfg["lora_alpha"].is_number())
@@ -833,6 +820,9 @@ int load_adapter(const std::string& dir, const std::vector<Site>& sites, int max
else if (t.is_array())
for (const ojson& x : t) if (x.is_string()) info->target_modules.push_back(x.get<std::string>());
}
/* PEFT's get_pattern_key: a key matches a module whose name ends in it on a dot boundary,
* `(.*\.)?(key)$` from the start of the name, and the first matching key in the file's order
* wins. */
struct Pat { std::string key; std::regex re; double v; };
std::vector<Pat> rpat, apat;
for (const char* which : { "rank_pattern", "alpha_pattern" }) {
@@ -846,14 +836,17 @@ int load_adapter(const std::string& dir, const std::vector<Site>& sites, int max
Pat p;
p.key = it.key();
try {
p.re = std::regex(p.key, std::regex::ECMAScript);
p.re = std::regex("(.*\\.)?(" + p.key + ")$", std::regex::ECMAScript);
} catch (const std::regex_error& e) {
return fail(err, RAD_E_FORMAT, cfg_path + ": " + which + " key '" + p.key +
"' is not a regex this engine reads (" + e.what() + ")");
}
p.v = it.value().get<double>();
if (!std::isfinite(p.v))
return fail(err, RAD_E_FORMAT, cfg_path + ": " + which + "[" + p.key +
"] is not a finite number");
if (!std::strcmp(which, "rank_pattern")) {
if (!it.value().is_number_integer() || p.v <= 0)
if (!it.value().is_number_integer() || p.v <= 0 || p.v > (double)INT32_MAX)
return fail(err, RAD_E_FORMAT, cfg_path + ": rank_pattern[" + p.key +
"] is not a positive integer");
info->rank_pattern.push_back({ p.key, (int64_t)p.v });
@@ -873,19 +866,10 @@ int load_adapter(const std::string& dir, const std::vector<Site>& sites, int max
"adapter as safetensors");
if (st.open(st_path) != RAD_OK) return fail(err, RAD_E_IO, st_path + ": cannot open as safetensors");
uint64_t hash = 1469598103934665603ull;
fnv(&hash, text.data(), text.size());
std::vector<const StTensor*> order;
for (const StTensor& t : st.tensors()) order.push_back(&t);
std::sort(order.begin(), order.end(),
[](const StTensor* a, const StTensor* b) { return a->name < b->name; });
for (const StTensor* t : order) {
fnv(&hash, t->name.data(), t->name.size() + 1);
fnv(&hash, t->dtype_str.data(), t->dtype_str.size() + 1);
for (int64_t d : t->shape) fnv(&hash, &d, sizeof d);
if (t->data) fnv(&hash, t->data, (size_t)t->bytes);
}
info->content_hash = hash;
static const std::regex key_re(R"(^(.*)\.lora_([AB])\.(weight|default\.weight)$)");
std::map<std::string, AdModule> mods;
@@ -902,7 +886,7 @@ int load_adapter(const std::string& dir, const std::vector<Site>& sites, int max
"; only linear LoRA A/B pairs are served");
}
std::string mod = m[1].str();
const size_t at = mod.find("base_model.model."); /* rad-export: first occurrence */
const size_t at = mod.find("base_model.model."); /* the first one, as rad-export strips it */
if (at != std::string::npos) mod.erase(at, 17);
AdModule& am = mods[mod];
am.name = mod;
@@ -932,8 +916,8 @@ int load_adapter(const std::string& dir, const std::vector<Site>& sites, int max
}
int64_t rr = info->r;
double aa = info->alpha;
for (const Pat& p : rpat) if (std::regex_search(am.name, p.re)) { rr = (int64_t)p.v; break; }
for (const Pat& p : apat) if (std::regex_search(am.name, p.re)) { aa = p.v; break; }
for (const Pat& p : rpat) if (std::regex_match(am.name, p.re)) { rr = (int64_t)p.v; break; }
for (const Pat& p : apat) if (std::regex_match(am.name, p.re)) { aa = p.v; break; }
if (am.A->shape[0] != rr || am.B->shape[1] != rr)
return fail(err, RAD_E_SHAPE,
fmt("module %s: expected rank %lld (r / rank_pattern), found lora_A %s and "
@@ -945,6 +929,9 @@ int load_adapter(const std::string& dir, const std::vector<Site>& sites, int max
am.rank = rr;
am.alpha = aa;
am.scale = (float)(info->rslora ? aa / std::sqrt((double)rr) : aa / (double)rr);
if (!std::isfinite(am.scale))
return fail(err, RAD_E_FORMAT, fmt("module %s: alpha %g over rank %lld is no finite "
"f32 scale", am.name.c_str(), aa, (long long)rr));
info->max_module_rank = std::max(info->max_module_rank, rr);
const size_t d = am.name.rfind('.');
info->leaves.insert(d == std::string::npos ? am.name : am.name.substr(d + 1));
+22 -41
View File
@@ -1,22 +1,19 @@
/* lora.h -- runtime LoRA: which declared GEMMs an adapter lands in, and the bytes of one adapter for
* one rank (research/radiance/lora/DESIGN.md §2, §5).
* one rank. Two host-only steps that read nothing but the declared Program:
*
* TWO PURE STEPS, both host-only and both read nothing but the declared Program:
* build_sites() after declare, every LoRA-capable trunk GEMM whose weight a target names becomes
* a Site: the weight's per-rank geometry (K slice, output width, where each PEFT
* module's rows land in y), read from what the plugin recorded on the weight
* (shard mode, row parts, shard and part spans, name-map sources), never from a
* plugin's own split rule. One Site per GEMM op; the Sites of one declared weight
* share one pool.
* load_adapter() a PEFT directory -> one PackedSite per pool, the bytes of one slot.
*
* build_sites() after declare: every LoRA-capable trunk GEMM whose weight a target names becomes
* a Site -- the weight's per-rank geometry (K slice, output width, which rows of
* which PEFT module land where in the GEMM's y) read off the facts the plugin
* recorded on the weight: its shard mode, row parts, shard / part spans and its
* name-map sources. Never a plugin's own split rule. One Site per GEMM op; the
* Sites of one declared weight share one POOL (one slot layout per weight).
* load_adapter() a PEFT directory -> one PackedSite per pool: exactly the bytes of one slot.
* Nothing here touches a device; the caller declares the pools and copies.
*
* Nothing here allocates device memory or touches a device; the caller declares the pools and copies.
*
* TARGETS ARE HF MODULE LEAF NAMES ("q_proj", "gate_proj", "in_proj_qkv", ...). A declared weight is
* targeted when one of its name-map sources is `<prefix>.<leaf>.weight`, `leaf` in the set, and the
* weight is not in a non-trunk scope (weight_targeted() states the rule; build_sites and
* find_unsupported_uses use exactly that predicate, and the builder may call it mid-declare).
* Targets are HF module leaf names ("q_proj", "gate_proj", "in_proj_qkv", ...). A declared weight is
* targeted when one of its name-map sources is `<prefix>.<leaf>.weight` with `leaf` in the set and
* the weight is in the trunk; weight_targeted() is the one predicate everything here uses.
*/
#pragma once
#include "../rad_core.h"
@@ -30,25 +27,23 @@
namespace rad {
namespace lora {
/* HF module LEAF names. A std::set so two callers that build it in different orders get the same
* answer. Empty targets nothing. */
/* HF module leaf names, ordered so every caller builds the same set. Empty targets nothing. */
using TargetSet = std::set<std::string>;
/* ONE CONTIGUOUS RUN OF ONE PEFT MODULE'S ROWS INSIDE THIS SITE'S y, ON THIS RANK.
* A module may need SEVERAL parts: in_proj_qkv covers three row parts of the delta net's fused
* ssm_inz, and a rank holds a slice of EACH, so its B rows on that rank are three disjoint runs
* landing at three y columns. Every part of one module carries the same t_off. */
/* One contiguous run of one PEFT module's rows inside this site's y, on this rank. A module may
* need several: in_proj_qkv covers three row parts of the delta net's fused ssm_inz and a rank
* holds a slice of each, so its B rows there are three runs at three y columns. Every part of one
* module has the same t_off. */
struct SitePart {
std::string module; /* HF module path without ".weight", as the name map spells it */
int64_t src_lo = 0, src_hi = 0;/* rows [lo,hi) of the module's full output (= rows of lora_B) */
int64_t y_col = 0; /* column of this site's per-rank y where row src_lo lands */
int64_t t_off = 0; /* first t column of the module's block = module slot * max_rank */
/* ADDED: the weight's row part this run lies in (0 for a weight of one part). */
int32_t row_part = 0;
int32_t row_part = 0; /* the weight's row part this run lies in (0: a single part) */
};
/* ADDED: one name-map source of the site's weight, in concatenation order -- targeted or not,
* because an untargeted source still occupies rows of the fused weight. */
/* One name-map source of the site's weight, in concatenation order, targeted or not: an untargeted
* source still occupies rows of the fused weight. */
struct SiteSource {
std::string module; /* source without ".weight" */
bool targeted = false;
@@ -59,28 +54,20 @@ struct SiteSource {
};
struct Site {
uint32_t gemm = 0; /* the gemm op handle (anchor) */
uint32_t lora_shrink = 0, lora_expand = 0; /* appended op handles (stream G) */
uint32_t gemm = 0; /* the gemm op handle */
std::string weight; /* declared weight name */
int shard = 0; /* RAD_SHARD_ROW / COL / NONE of the base weight */
int64_t K_r = 0, k_lo = 0, K_full = 0; /* x columns on this rank; COL: A columns
* [k_lo, k_lo + K_r). K_full 0 = not recorded on
* the weight (a COL span): taken from lora_A. */
int64_t N_r = 0; /* per-rank y width the gemm writes */
int64_t R = 0; /* capacity: n_modules * max_rank (see report:
* DESIGN said parts.size() * max_rank) */
int64_t R = 0; /* capacity: n_modules * max_rank */
std::vector<SitePart> parts; /* empty while !parts_resolved */
uint32_t pool_a = 0, pool_b = 0, pool_scale = 0; /* PERSIST buffers; 0 here, the caller's */
/* ---- ADDED */
int32_t pool = -1; /* index of the weight in build_sites' per-weight pool list */
uint32_t w = 0; /* the declared weight's handle */
std::string op; /* the gemm's op name */
int32_t n_modules = 0; /* targeted sources */
int32_t max_rank = 0;
bool parts_resolved = true; /* false: the fused layout is decided by B rows at load */
bool res_unchecked = false; /* gemm_nt_bias: its optional `res` operand is bound at
* issue, not at declare -- stream G checks it there */
std::vector<SiteSource> sources;
/* Per row part g of the weight (P = max(1, n_row_parts) entries): the part's rows in the
* container (0 = not recorded: an equal-part single span), this rank's rows [lo, hi) of it in
@@ -93,7 +80,6 @@ struct PackedSite {
std::vector<uint16_t> a; /* [R, K_r] bf16, zero rows past the module's rank in each block */
std::vector<uint16_t> b; /* [N_r, R] bf16, zero outside the module's rows / rank block */
std::vector<float> scale; /* [N_r]: the module's alpha/r (alpha/sqrt(r) rsLoRA) on its rows */
/* ADDED */
int32_t pool = -1;
bool empty = true; /* no module of this adapter lands in this pool */
};
@@ -121,7 +107,6 @@ struct AdapterInfo {
std::set<std::string> leaves; /* leaf names present in the tensors (targets present) */
std::vector<std::string> absent; /* modules no site on THIS rank took (see check_placed) */
int64_t max_module_rank = 0;
uint64_t content_hash = 0; /* FNV-1a 64 over the config bytes and the tensors */
};
/* A targeted weight read by an op that is not a LoRA site. The caller refuses at startup. */
@@ -165,10 +150,6 @@ int build_sites(const Program& prog, const TargetSet& targets, int max_rank,
std::vector<Site>* out, std::string* err,
std::vector<std::string>* pool_weights = nullptr);
/* Every leaf whose every targeted weight in `prog` would be a site: what "all LoRA-capable trunk
* linears" means when no adapter names the targets. */
TargetSet all_capable_targets(const Program& prog);
/* One adapter for one rank: `packed` gets one PackedSite per pool (index = Site::pool), in the
* slot layout of the pool's sites. Refusals return a negative code and name module, expected and
* found. A module with no site on THIS rank is not refused here -- an attention-zero rank holds no
+2 -3
View File
@@ -29,9 +29,8 @@ int SlotTable::reserve(const std::string& name, int* slot, bool* cooling, std::s
*err = "an adapter named '" + name + "' is already loaded";
return RAD_E_INVAL;
}
/* The old adapter's requests are still running on its slot, and a request naming
* the new one would be told apart from them only by the uid: load it once the old one
* is gone (POST /v1/unload_lora_adapter says how many remain). */
/* The old adapter's requests still run on its slot; the name loads again once they
* are gone (POST /v1/unload_lora_adapter says how many remain). */
const auto it = refs_.find(x.uid);
const int n = it == refs_.end() ? 0 : it->second;
*err = fmt("an adapter named '%s' is being unloaded: %d request%s still use%s it", name.c_str(),
+11 -11
View File
@@ -2,22 +2,22 @@
* be written again. Host bookkeeping only: the engine copies the adapter's bytes (engine_lora.cpp)
* and this table decides which slot, publishes the name, hands out holds and frees slots.
*
* A SLOT'S LIFE:
* A slot's life:
*
* free --load--> loaded --unload, no request uses it--> free (cooling)
* | ^
* +--unload, requests use it--> draining ---+ the last of them finishes
*
* A request holds the adapter it names from admission until its reply is done (the server keeps
* the hold in the request's Generation), so an adapter is never unloaded under a request. An
* unload of an adapter in use DRAINS it: from that moment no new request can name it (it is gone
* from the names, and acquire answers as for a name never loaded), the requests already holding
* it finish normally, and the last hold to go frees the slot. A load of the same name waits for
* that rather than racing it.
* A request holds the adapter it names from admission until its reply is done or it is cancelled
* (the server keeps the hold in the request's Generation), so an adapter is never unloaded under a
* request. An unload of an adapter in use drains it: no new request can name it (acquire answers
* as for a name never loaded), the requests already holding it finish, and the last hold to go
* frees the slot. A load of the same name is refused until then.
*
* COOLING: a freed slot is written again only once the step loop has gone round three times
* since (`epoch` below counts its rounds): the step after a request's last one may already be on
* the card, issued ahead, and reads the slot through the step batch until it runs.
* Cooling: a freed slot is written again only after the step loop has gone round
* kSlotCoolRounds times (`epoch` counts its rounds). A step that read the slot may still be on
* the card when the last hold goes, issued ahead of the readback; an idle round has no step in
* flight and a busy round collects one, so with one step issued ahead two rounds suffice.
*
* Thread-safe: every call takes the table's lock. Loads are serialised by the caller (one at a
* time between reserve and publish), which is what keeps a reserved slot from being handed out
@@ -85,7 +85,7 @@ private:
const std::atomic<uint64_t>* epoch_ = nullptr;
};
/* Step-loop rounds a freed slot waits before it is written again (see COOLING above). */
/* Step-loop rounds a freed slot waits before it is written again (see Cooling above). */
inline constexpr uint64_t kSlotCoolRounds = 3;
} /* namespace lora */
+64 -12
View File
@@ -82,6 +82,58 @@ void KeepAll::select(const std::vector<int64_t>& pos, std::vector<int64_t>* keep
*keep = pos;
}
/* A session's tip is usually a prompt's tail between two interval checkpoints, so each step also
* counts the ladder with a tail half an interval on as its tip. */
int64_t CheckpointPolicy::held(int64_t ctx, int64_t interval) const {
if (interval <= 0 || ctx < interval) return 1;
std::vector<int64_t> kept, keep;
size_t most = 0;
for (int64_t p = interval; p <= ctx; p += interval) {
kept.push_back(p);
select(kept, &keep);
std::sort(keep.begin(), keep.end());
kept.swap(keep);
most = std::max(most, kept.size());
if (p + interval / 2 <= ctx) {
std::vector<int64_t> tipped = kept;
tipped.push_back(p + interval / 2);
select(tipped, &keep);
most = std::max(most, keep.size());
}
}
return (int64_t)most;
}
int64_t KeepAll::held(int64_t ctx, int64_t interval) const {
return interval > 0 && ctx >= interval ? ctx / interval : 1;
}
std::unique_ptr<CheckpointPolicy> make_checkpoint_policy(const std::string& name,
int64_t interval) {
if (name == "tip-only") return std::make_unique<KeepTipOnly>();
if (name == "keep-all") return std::make_unique<KeepAll>();
return std::make_unique<GeometricBackoff>(interval);
}
CheckpointSlots checkpoint_slots_auto(const CheckpointPolicy& policy, int64_t max_seqs,
int64_t ctx, int64_t interval, int64_t slot_bytes,
int64_t share_bytes, int64_t room_bytes) {
CheckpointSlots c;
c.per_seq = policy.held(ctx, interval) + 1;
const int64_t seqs = std::max<int64_t>(max_seqs, 1);
c.want = seqs > INT64_MAX / c.per_seq ? INT64_MAX : seqs * c.per_seq;
if (slot_bytes <= 0) return c;
const int64_t share = std::max<int64_t>(share_bytes, 0) / slot_bytes;
const int64_t room = std::max<int64_t>(room_bytes, 0) / slot_bytes;
c.slots = std::min(c.want, std::max(share, std::min(c.want, kCheckpointSlotsFloor)));
if (c.slots < c.want) c.bound = CheckpointSlots::Bound::Share;
if (room < c.slots) {
c.slots = room;
c.bound = CheckpointSlots::Bound::Room;
}
return c;
}
/* ------------------------------------------------------------------ configure */
int PrefixCache::configure(const Config& cfg, KVManager* kv, int64_t checkpoint_interval) {
@@ -93,11 +145,8 @@ int PrefixCache::configure(const Config& cfg, KVManager* kv, int64_t checkpoint_
groups_.clear();
map_.clear(); lru_.clear();
ck_by_prefix_.clear(); ck_by_session_.clear();
/* config_parse rejects unknown names, so the else branch is "geometric-backoff".
* set_policy() may override this afterwards. */
if (cfg.checkpoint_policy == "tip-only") policy_ = std::make_unique<KeepTipOnly>();
else if (cfg.checkpoint_policy == "keep-all") policy_ = std::make_unique<KeepAll>();
else policy_ = std::make_unique<GeometricBackoff>(checkpoint_interval);
/* set_policy() may override this afterwards. */
policy_ = make_checkpoint_policy(cfg.checkpoint_policy, checkpoint_interval);
report_.clear();
if (!kv) return RAD_E_INVAL;
@@ -202,7 +251,7 @@ void PrefixCache::touch(const BlockHash& h, uint64_t now_ns) const {
CacheHit PrefixCache::lookup(const std::vector<int32_t>& tokens,
const std::vector<MMContentKey>& mm,
std::vector<std::vector<int32_t>>* blocks_out,
const HitCap* cap) const {
const HitCap* cap, uint64_t session) const {
CacheHit hit;
if (blocks_out) { blocks_out->assign(groups_.size(), {}); }
if (!enabled_ || tokens.empty()) return hit;
@@ -296,6 +345,7 @@ CacheHit PrefixCache::lookup(const std::vector<int32_t>& tokens,
best->second.used_ns = now;
handed_.push_back(best->first);
++stats_.ckpt_hits;
if (session != 0) take_over(session, hs, hit.n_attn_tokens);
return hit;
}
@@ -384,13 +434,16 @@ int PrefixCache::insert(uint64_t session,
tiers_->note_session(session, hs, n_tokens, now, label);
}
/* A conversation's snapshots belong to its latest turn. Sessions are keyed by request id, so
* without this each earlier turn's deepest snapshot would stay a protected tip. Every snapshot
* on the chain just published moves under this id, so the policy sees one session, one tip. */
take_over(session, hs, n_full * block_size_);
return RAD_OK;
}
void PrefixCache::take_over(uint64_t session, const std::vector<BlockHash>& hs,
int64_t upto) const {
for (auto& kvp : ck_by_prefix_) {
Ckpt& c = kvp.second;
if (c.session == session || c.pos <= 0 || c.pos > n_full * block_size_ ||
c.pos % block_size_ != 0 || hs[(size_t)(c.pos / block_size_ - 1)] != kvp.first)
if (c.session == session || c.pos <= 0 || c.pos > upto || c.pos % block_size_ != 0 ||
hs[(size_t)(c.pos / block_size_ - 1)] != kvp.first)
continue;
auto old = ck_by_session_.find(c.session);
if (old != ck_by_session_.end()) {
@@ -401,7 +454,6 @@ int PrefixCache::insert(uint64_t session,
c.session = session;
ck_by_session_[session].push_back(kvp.first);
}
return RAD_OK;
}
+43 -3
View File
@@ -110,6 +110,11 @@ public:
* retain. The tip, positions.back(), must always be kept: an appending transcript resumes
* from it. */
virtual void select(const std::vector<int64_t>& positions, std::vector<int64_t>* keep) const = 0;
/* The most snapshots the policy keeps for one session that grows to `ctx` tokens with a
* checkpoint on every `interval`, retention applied after each: the session's standing share
* of the store. The base applies select() to its own output one checkpoint at a time, which
* is cheap only for a policy that keeps few. */
virtual int64_t held(int64_t ctx, int64_t interval) const;
};
/* Keep the tip and, at every scale S = interval x 2^k, the shallowest checkpoint in the tip's
@@ -134,13 +139,40 @@ class KeepTipOnly final : public CheckpointPolicy {
public:
const char* name() const override { return "tip-only"; }
void select(const std::vector<int64_t>& positions, std::vector<int64_t>* keep) const override;
int64_t held(int64_t, int64_t) const override { return 1; }
};
class KeepAll final : public CheckpointPolicy {
public:
const char* name() const override { return "keep-all"; }
void select(const std::vector<int64_t>& positions, std::vector<int64_t>* keep) const override;
int64_t held(int64_t ctx, int64_t interval) const override;
};
/* The policy --checkpoint-policy names, at the resolved checkpoint interval. config_parse admits
* only the three names, so any other is geometric backoff. */
std::unique_ptr<CheckpointPolicy> make_checkpoint_policy(const std::string& name, int64_t interval);
/* ------------------------------------------------------------------ the store's size */
/* --checkpoint-slots auto. Every sequence --max-num-seqs admits gets its session's standing share
* at --max-model-len (CheckpointPolicy::held) plus one slot for the checkpoint its running turn
* writes while the previous turn's snapshots are still held. The store is pinned for the life of
* the process, so the count is bounded by two byte budgets the engine measures: `share`, the part
* of host memory the store may take, and `room`, what the host can pin after everything still to
* be allocated. Under the share it never drops below kCheckpointSlotsFloor (or `want`, if fewer);
* the room is a hard bound. */
constexpr int64_t kCheckpointSlotsFloor = 8;
struct CheckpointSlots {
int64_t per_seq = 0; /* snapshots a sequence is given */
int64_t want = 0; /* --max-num-seqs x per_seq */
int64_t slots = 0; /* the store's size */
enum class Bound { Want, Share, Room } bound = Bound::Want;
};
CheckpointSlots checkpoint_slots_auto(const CheckpointPolicy& policy, int64_t max_seqs,
int64_t ctx, int64_t interval, int64_t slot_bytes,
int64_t share_bytes, int64_t room_bytes);
/* ------------------------------------------------------------------ the cache */
class PrefixCache {
public:
@@ -168,11 +200,13 @@ public:
* cached_groups() order, ready for KVManager::adopt().
*
* Never returns the whole prompt: one token must remain to compute a logit from, so a full
* hit is backed off by one block. `cap`, when given, ends the hit early (HitCap). */
* hit is backed off by one block. `cap`, when given, ends the hit early (HitCap). `session`,
* when not 0, is the request being admitted: it takes over the snapshots on the chain it hit
* (take_over). */
CacheHit lookup(const std::vector<int32_t>& tokens,
const std::vector<MMContentKey>& mm,
std::vector<std::vector<int32_t>>* blocks_out = nullptr,
const HitCap* cap = nullptr) const;
const HitCap* cap = nullptr, uint64_t session = 0) const;
/* Publish the whole blocks a sequence just filled. `blocks[i]` is the block table of
* cached_groups()[i]. Takes a KV reference on every newly indexed block. */
@@ -347,6 +381,12 @@ private:
/* Retire one snapshot: free its slot and tell the tiers. The session index is left to the
* caller. */
void retire_ckpt(std::unordered_map<BlockHash, Ckpt, BlockHashHash>::iterator it);
/* Move every snapshot on the chain `hs` at or below `upto` tokens under `session`. A
* conversation's snapshots belong to its latest turn: sessions are request ids, so otherwise
* each earlier turn's deepest snapshot would stay a protected tip, and a running turn would be
* a second session beside its conversation, two ladders where retention should keep one.
* The admission's lookup and the publish both call it. */
void take_over(uint64_t session, const std::vector<BlockHash>& hs, int64_t upto) const;
/* Take one key out of a session's index entry, and the entry when it empties. */
void unindex_ckpt(uint64_t session, const BlockHash& key);
/* For the debug lines: whether `c` is its session's deepest snapshot, and seconds since a
@@ -375,7 +415,7 @@ private:
std::unordered_map<BlockHash, int32_t, BlockHashHash> held_;
bool released_ = false;
mutable std::unordered_map<BlockHash, Ckpt, BlockHashHash> ck_by_prefix_;
std::unordered_map<uint64_t, std::vector<BlockHash>> ck_by_session_;
mutable std::unordered_map<uint64_t, std::vector<BlockHash>> ck_by_session_;
/* Snapshots lookup handed out since begin_step; kept in their slots until the next one. */
mutable std::vector<BlockHash> handed_;
bool handed(const BlockHash& h) const {
+405
View File
@@ -0,0 +1,405 @@
/* mp4.cpp -- Mp4Writer (mp4.h) over libavformat, libavcodec and libswscale. */
#include "mm/mp4.h"
#include <algorithm>
#include <cstring>
#include <mutex>
#ifdef RAD_HAVE_FFMPEG
extern "C" {
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libavutil/channel_layout.h>
#include <libavutil/opt.h>
#include <libswscale/swscale.h>
}
#endif
namespace rad {
namespace mm {
#ifndef RAD_HAVE_FFMPEG
struct Mp4Writer::Impl {};
Mp4Writer::Mp4Writer() = default;
Mp4Writer::~Mp4Writer() = default;
static int no_ffmpeg(std::string* why) {
if (why) *why = "this build has no libavcodec, so it writes no video";
return RAD_E_UNSUPPORTED;
}
int Mp4Writer::open(int32_t, int32_t, int64_t, int64_t, int64_t, int64_t, std::string* why) {
return no_ffmpeg(why);
}
int Mp4Writer::add_frames(const uint8_t*, int32_t, std::string* why) { return no_ffmpeg(why); }
int Mp4Writer::add_audio(const float*, int64_t, std::string* why) { return no_ffmpeg(why); }
int Mp4Writer::finish(std::string*, std::string* why) { return no_ffmpeg(why); }
#else
namespace {
/* The file in memory. The MP4 muxer seeks back to patch sizes and, to put the moov atom first,
* reopens its output for reading and moves the media data up (FFmpeg's shift_data): the reader is
* a second handle on the same bytes with a position of its own. */
struct MemFile {
std::string data;
int64_t pos = 0;
};
struct MemReader {
MemFile* f = nullptr;
int64_t pos = 0;
};
int mem_write(void* op, const uint8_t* buf, int n) {
MemFile* f = static_cast<MemFile*>(op);
const int64_t end = f->pos + n;
if (end > (int64_t)f->data.size()) f->data.resize((size_t)end);
std::memcpy(&f->data[(size_t)f->pos], buf, (size_t)n);
f->pos = end;
return n;
}
int64_t mem_seek(void* op, int64_t off, int whence) {
MemFile* f = static_cast<MemFile*>(op);
const int64_t size = (int64_t)f->data.size();
switch (whence & ~AVSEEK_FORCE) {
case AVSEEK_SIZE: return size;
case SEEK_SET: f->pos = off; break;
case SEEK_CUR: f->pos += off; break;
case SEEK_END: f->pos = size + off; break;
default: return AVERROR(EINVAL);
}
return f->pos < 0 ? AVERROR(EINVAL) : f->pos;
}
int mem_read(void* op, uint8_t* buf, int n) {
MemReader* r = static_cast<MemReader*>(op);
const int64_t size = (int64_t)r->f->data.size();
if (r->pos >= size) return AVERROR_EOF;
const int k = (int)std::min<int64_t>(n, size - r->pos);
std::memcpy(buf, r->f->data.data() + r->pos, (size_t)k);
r->pos += k;
return k;
}
int64_t mem_read_seek(void* op, int64_t off, int whence) {
MemReader* r = static_cast<MemReader*>(op);
const int64_t size = (int64_t)r->f->data.size();
switch (whence & ~AVSEEK_FORCE) {
case AVSEEK_SIZE: return size;
case SEEK_SET: r->pos = off; break;
case SEEK_CUR: r->pos += off; break;
case SEEK_END: r->pos = size + off; break;
default: return AVERROR(EINVAL);
}
return r->pos < 0 ? AVERROR(EINVAL) : r->pos;
}
constexpr int kIoBuf = 1 << 16;
std::string av_why(const char* what, int e) {
char b[AV_ERROR_MAX_STRING_SIZE] = {};
av_strerror(e, b, sizeof b);
return std::string(what) + ": " + b;
}
} /* namespace */
struct Mp4Writer::Impl {
MemFile file;
AVFormatContext* oc = nullptr;
AVCodecContext* vc = nullptr;
AVCodecContext* ac = nullptr;
AVStream* vs = nullptr;
AVStream* as = nullptr;
SwsContext* sws = nullptr;
AVFrame* vf = nullptr;
AVFrame* af = nullptr;
AVPacket* pkt = nullptr;
int32_t w = 0, h = 0;
int64_t channels = 0;
int64_t next_frame = 0;
std::vector<float> audio; /* interleaved, encoded at finish */
bool header = false;
~Impl() {
if (oc) {
if (oc->pb) {
av_freep(&oc->pb->buffer);
avio_context_free(&oc->pb);
}
avformat_free_context(oc);
}
avcodec_free_context(&vc);
avcodec_free_context(&ac);
sws_freeContext(sws);
av_frame_free(&vf);
av_frame_free(&af);
av_packet_free(&pkt);
}
/* Every packet `c` has ready, onto stream `st`. */
int drain(AVCodecContext* c, AVStream* st, std::string* why) {
for (;;) {
const int e = avcodec_receive_packet(c, pkt);
if (e == AVERROR(EAGAIN) || e == AVERROR_EOF) return RAD_OK;
if (e < 0) {
if (why) *why = av_why("encoding", e);
return RAD_E_INVAL;
}
av_packet_rescale_ts(pkt, c->time_base, st->time_base);
pkt->stream_index = st->index;
const int w2 = av_interleaved_write_frame(oc, pkt);
if (w2 < 0) {
if (why) *why = av_why("writing the file", w2);
return RAD_E_INVAL;
}
}
}
};
/* The reader shift_data opens on the output's own URL; any other URL is refused. */
static int open_reader(AVFormatContext* s, AVIOContext** pb, const char*, int flags, AVDictionary**) {
if (!(flags & AVIO_FLAG_READ) || (flags & AVIO_FLAG_WRITE)) return AVERROR(EINVAL);
MemFile* f = static_cast<MemFile*>(s->opaque);
MemReader* r = new MemReader{ f, 0 };
uint8_t* buf = static_cast<uint8_t*>(av_malloc(kIoBuf));
*pb = buf ? avio_alloc_context(buf, kIoBuf, 0, r, mem_read, nullptr, mem_read_seek) : nullptr;
if (!*pb) {
av_free(buf);
delete r;
return AVERROR(ENOMEM);
}
return 0;
}
static int close_reader(AVFormatContext*, AVIOContext* pb) {
if (!pb) return 0;
delete static_cast<MemReader*>(pb->opaque);
av_freep(&pb->buffer);
avio_context_free(&pb);
return 0;
}
Mp4Writer::Mp4Writer() : p_(std::make_unique<Impl>()) {}
Mp4Writer::~Mp4Writer() = default;
int Mp4Writer::open(int32_t width, int32_t height, int64_t fps_num, int64_t fps_den,
int64_t sample_rate, int64_t channels, std::string* why) {
Impl& p = *p_;
/* The encoders print their settings and a file's statistics at FFmpeg's info level, on stderr,
* for every video; a failure comes back through the calls here, so only errors are let
* through. */
static std::once_flag quiet;
std::call_once(quiet, [] { if (av_log_get_level() > AV_LOG_ERROR) av_log_set_level(AV_LOG_ERROR); });
if (width <= 0 || height <= 0 || (width & 1) || (height & 1) || fps_num <= 0 || fps_den <= 0) {
if (why) *why = "the frames must be a positive even size at a positive rate";
return RAD_E_INVAL;
}
p.w = width;
p.h = height;
p.channels = channels;
if (avformat_alloc_output_context2(&p.oc, nullptr, "mp4", nullptr) < 0 || !p.oc) {
if (why) *why = "this libavformat has no MP4 muxer";
return RAD_E_UNSUPPORTED;
}
p.oc->url = av_strdup("radiance.mp4");
p.oc->opaque = &p.file;
p.oc->io_open = open_reader;
p.oc->io_close2 = close_reader;
uint8_t* buf = static_cast<uint8_t*>(av_malloc(kIoBuf));
p.oc->pb = buf ? avio_alloc_context(buf, kIoBuf, 1, &p.file, nullptr, mem_write, mem_seek)
: nullptr;
p.pkt = av_packet_alloc();
if (!p.oc->url || !p.oc->pb || !p.pkt) {
if (!p.oc->pb) av_free(buf);
if (why) *why = "out of memory";
return RAD_E_NOMEM;
}
/* ---- video */
const AVCodec* vcodec = nullptr;
for (const char* name : { "libx264", "libopenh264" })
if ((vcodec = avcodec_find_encoder_by_name(name))) break;
if (!vcodec) vcodec = avcodec_find_encoder(AV_CODEC_ID_H264);
if (!vcodec) {
if (why) *why = "this libavcodec has no H.264 encoder";
return RAD_E_UNSUPPORTED;
}
venc_name_ = vcodec->name;
p.vs = avformat_new_stream(p.oc, nullptr);
p.vc = avcodec_alloc_context3(vcodec);
if (!p.vs || !p.vc) {
if (why) *why = "out of memory";
return RAD_E_NOMEM;
}
p.vc->width = width;
p.vc->height = height;
p.vc->pix_fmt = AV_PIX_FMT_YUV420P;
p.vc->time_base = AVRational{ (int)fps_den, (int)fps_num };
p.vc->framerate = AVRational{ (int)fps_num, (int)fps_den };
p.vc->gop_size = (int)std::max<int64_t>(1, 2 * fps_num / fps_den);
p.vc->colorspace = AVCOL_SPC_BT709;
p.vc->color_primaries = AVCOL_PRI_BT709;
p.vc->color_trc = AVCOL_TRC_BT709;
p.vc->color_range = AVCOL_RANGE_MPEG;
if (venc_name_ == "libx264") {
/* Constant quality, visually lossless for generated footage. */
av_opt_set(p.vc->priv_data, "preset", "medium", 0);
av_opt_set(p.vc->priv_data, "crf", "18", 0);
} else {
/* An encoder without a quality mode: 0.2 bits a pixel, about 5 Mbit/s at 1344x768 x 24. */
p.vc->bit_rate = (int64_t)((double)width * height * fps_num / fps_den * 0.2);
}
if (p.oc->oformat->flags & AVFMT_GLOBALHEADER) p.vc->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
int e = avcodec_open2(p.vc, vcodec, nullptr);
if (e < 0) {
if (why) *why = av_why(("opening the " + venc_name_ + " encoder").c_str(), e);
return RAD_E_INVAL;
}
avcodec_parameters_from_context(p.vs->codecpar, p.vc);
p.vs->time_base = p.vc->time_base;
p.vs->avg_frame_rate = p.vc->framerate;
p.vf = av_frame_alloc();
if (!p.vf) return RAD_E_NOMEM;
p.vf->format = AV_PIX_FMT_YUV420P;
p.vf->width = width;
p.vf->height = height;
if (av_frame_get_buffer(p.vf, 0) < 0) return RAD_E_NOMEM;
p.sws = sws_getContext(width, height, AV_PIX_FMT_RGB24, width, height, AV_PIX_FMT_YUV420P,
SWS_BICUBIC | SWS_ACCURATE_RND, nullptr, nullptr, nullptr);
if (!p.sws) {
if (why) *why = "libswscale cannot convert RGB to yuv420p";
return RAD_E_UNSUPPORTED;
}
/* Full-range RGB to limited-range BT.709, what the stream's colour tags say. */
sws_setColorspaceDetails(p.sws, sws_getCoefficients(SWS_CS_DEFAULT), 1,
sws_getCoefficients(SWS_CS_ITU709), 0, 0, 1 << 16, 1 << 16);
/* ---- audio */
if (channels > 0) {
const AVCodec* acodec = avcodec_find_encoder(AV_CODEC_ID_AAC);
if (!acodec) {
if (why) *why = "this libavcodec has no AAC encoder";
return RAD_E_UNSUPPORTED;
}
p.as = avformat_new_stream(p.oc, nullptr);
p.ac = avcodec_alloc_context3(acodec);
if (!p.as || !p.ac) return RAD_E_NOMEM;
p.ac->sample_fmt = AV_SAMPLE_FMT_FLTP;
p.ac->sample_rate = (int)sample_rate;
av_channel_layout_default(&p.ac->ch_layout, (int)channels);
p.ac->bit_rate = 96000 * channels;
p.ac->time_base = AVRational{ 1, (int)sample_rate };
if (p.oc->oformat->flags & AVFMT_GLOBALHEADER) p.ac->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
e = avcodec_open2(p.ac, acodec, nullptr);
if (e < 0) {
if (why) *why = av_why("opening the AAC encoder", e);
return RAD_E_INVAL;
}
avcodec_parameters_from_context(p.as->codecpar, p.ac);
p.as->time_base = p.ac->time_base;
p.af = av_frame_alloc();
if (!p.af) return RAD_E_NOMEM;
p.af->format = AV_SAMPLE_FMT_FLTP;
p.af->sample_rate = p.ac->sample_rate;
av_channel_layout_copy(&p.af->ch_layout, &p.ac->ch_layout);
p.af->nb_samples = p.ac->frame_size > 0 ? p.ac->frame_size : 1024;
if (av_frame_get_buffer(p.af, 0) < 0) return RAD_E_NOMEM;
}
AVDictionary* opts = nullptr;
av_dict_set(&opts, "movflags", "+faststart", 0);
e = avformat_write_header(p.oc, &opts);
av_dict_free(&opts);
if (e < 0) {
if (why) *why = av_why("writing the MP4 header", e);
return RAD_E_INVAL;
}
p.header = true;
return RAD_OK;
}
int Mp4Writer::add_frames(const uint8_t* rgb, int32_t n, std::string* why) {
Impl& p = *p_;
if (!p.header) {
if (why) *why = "the writer is not open";
return RAD_E_STATE;
}
const int64_t frame_bytes = (int64_t)p.w * p.h * 3;
for (int32_t i = 0; i < n; ++i) {
if (av_frame_make_writable(p.vf) < 0) return RAD_E_NOMEM;
const uint8_t* src[1] = { rgb + i * frame_bytes };
const int stride[1] = { p.w * 3 };
sws_scale(p.sws, src, stride, 0, p.h, p.vf->data, p.vf->linesize);
p.vf->pts = p.next_frame++;
const int e = avcodec_send_frame(p.vc, p.vf);
if (e < 0) {
if (why) *why = av_why("encoding a frame", e);
return RAD_E_INVAL;
}
RAD_TRY(p.drain(p.vc, p.vs, why));
}
return RAD_OK;
}
int Mp4Writer::add_audio(const float* samples, int64_t n_frames, std::string* why) {
Impl& p = *p_;
if (!p.header || !p.ac) {
if (why) *why = "the writer has no soundtrack";
return RAD_E_STATE;
}
p.audio.insert(p.audio.end(), samples, samples + n_frames * p.channels);
return RAD_OK;
}
int Mp4Writer::finish(std::string* out, std::string* why) {
Impl& p = *p_;
if (!p.header) {
if (why) *why = "the writer is not open";
return RAD_E_STATE;
}
if (p.ac) {
/* The soundtrack in the encoder's frames, deinterleaved; the last frame padded with
* silence, which the encoder's own length bookkeeping trims. */
const int64_t total = (int64_t)p.audio.size() / p.channels;
const int fs = p.af->nb_samples;
for (int64_t at = 0; at < total; at += fs) {
if (av_frame_make_writable(p.af) < 0) return RAD_E_NOMEM;
const int64_t k = std::min<int64_t>(fs, total - at);
p.af->nb_samples = (int)k;
for (int64_t c = 0; c < p.channels; ++c) {
float* d = reinterpret_cast<float*>(p.af->data[c]);
for (int64_t i = 0; i < k; ++i)
d[i] = p.audio[(size_t)((at + i) * p.channels + c)];
}
p.af->pts = at;
const int e = avcodec_send_frame(p.ac, p.af);
if (e < 0) {
if (why) *why = av_why("encoding the soundtrack", e);
return RAD_E_INVAL;
}
RAD_TRY(p.drain(p.ac, p.as, why));
p.af->nb_samples = fs;
}
avcodec_send_frame(p.ac, nullptr);
RAD_TRY(p.drain(p.ac, p.as, why));
}
avcodec_send_frame(p.vc, nullptr);
RAD_TRY(p.drain(p.vc, p.vs, why));
const int e = av_write_trailer(p.oc);
if (e < 0) {
if (why) *why = av_why("finishing the MP4 file", e);
return RAD_E_INVAL;
}
avio_flush(p.oc->pb);
*out = std::move(p.file.data);
p.file.data.clear();
p.header = false;
return RAD_OK;
}
#endif /* RAD_HAVE_FFMPEG */
} /* namespace mm */
} /* namespace rad */
+52
View File
@@ -0,0 +1,52 @@
/* mp4.h -- a video and its soundtrack written as an MP4 file in memory: H.264 video in yuv420p
* (BT.709, limited range) and AAC audio, the moov atom at the front so a player can start before
* the whole file has arrived.
*
* The frames arrive in order, in any number of calls; the soundtrack may come before, between or
* after them, whole or in pieces. Nothing is written until finish(), which encodes the soundtrack
* and interleaves it with the video: a video is at most tens of seconds, and its frames are
* encoded as they come so the RGB is never all held at once.
*
* The H.264 encoder is the best the linked libavcodec has: libx264 (constant quality), else
* libopenh264, else whatever encoder it registers for H.264. Without libavcodec every call
* returns RAD_E_UNSUPPORTED.
*/
#pragma once
#include "rad_core.h"
#include <memory>
#include <string>
#include <vector>
namespace rad {
namespace mm {
class Mp4Writer {
public:
Mp4Writer();
~Mp4Writer();
Mp4Writer(const Mp4Writer&) = delete;
Mp4Writer& operator=(const Mp4Writer&) = delete;
/* A video of `width` x `height` (even) at fps_num / fps_den frames a second, with a soundtrack
* of `channels` channels at `sample_rate` (0 channels: none). */
int open(int32_t width, int32_t height, int64_t fps_num, int64_t fps_den, int64_t sample_rate,
int64_t channels, std::string* why);
/* `n` frames, each [height, width, 3] u8 RGB, after those already added. */
int add_frames(const uint8_t* rgb, int32_t n, std::string* why);
/* Samples interleaved over the channels, in [-1, 1], after those already added. */
int add_audio(const float* samples, int64_t n_frames, std::string* why);
/* Flushes both encoders and writes the file into `out`. */
int finish(std::string* out, std::string* why);
/* The H.264 encoder in use, for the log. */
const std::string& video_encoder() const { return venc_name_; }
private:
struct Impl;
std::unique_ptr<Impl> p_;
std::string venc_name_;
};
} /* namespace mm */
} /* namespace rad */
+6
View File
@@ -219,6 +219,12 @@ int Registry::commit_(Staged& s, int order) {
/* Optional: absent means the model serves no speech route. */
p.arch_audio_format = dl_fn<const RadAudioFormat* (*)(const RadModelMeta*)>(
s.handle, "rad_arch_audio_format");
/* Optional: absent means an audio generator's prompt takes a request's texts as given. */
p.arch_text_prepare = dl_fn<int64_t (*)(int, const char*, char*, int64_t)>(
s.handle, "rad_arch_text_prepare");
/* A video generator's rotary positions; the driver refuses to start without it. */
p.arch_video_positions = dl_fn<int64_t (*)(int, const RadVideoGeom*, float*, int64_t)>(
s.handle, "rad_arch_video_positions");
/* The (architecture id, quantisation) pair selects the plugin, so no two plugins may claim
* the same pair (§2.4). Sharing an id at different quantisations is normal (qwen35_bf16
+5
View File
@@ -89,6 +89,11 @@ struct Plugin {
const RadChatFormat* (*arch_chat_format)(const RadModelMeta*) = nullptr;
/* Optional (rad_builder.h); null means the model serves no speech route. */
const RadAudioFormat* (*arch_audio_format)(const RadModelMeta*) = nullptr;
/* Optional (rad_builder.h); null means a request's texts go into the audio generator's
* prompt as given. */
int64_t (*arch_text_prepare)(int, const char*, char*, int64_t) = nullptr;
/* Required of a video generator (rad_builder.h); null for every other plugin. */
int64_t (*arch_video_positions)(int, const RadVideoGeom*, float*, int64_t) = nullptr;
RadPluginCloseFn close = nullptr;
};
+36 -17
View File
@@ -265,15 +265,15 @@ struct OpInfo {
const RadOpSchema* schema = nullptr;
int32_t index = 0; /* position in the declared order */
bool issued = false; /* did the run phase ever issue it */
/* RUNTIME LoRA (core/lora/). `anchor`: an op the CORE appended after the plugin's declare and
* issues inside another op's issue -- its buffers are that op's, so buffer liveness is judged
* at the anchor's position, not at this op's own (which is past every plugin op). -1 for every
* plugin op. `lora_site`: on a targeted gemm, its row in Program::lora_sites; -1 otherwise. */
/* Runtime LoRA (core/lora/). `anchor`: the op a core-appended op is issued inside of; its
* buffers are that op's, so their liveness is judged at the anchor's position rather than this
* op's own (past every plugin op). -1 for a plugin op. `lora_site`: a targeted gemm's row in
* Program::lora_sites, -1 otherwise. */
int32_t anchor = -1;
int32_t lora_site = -1;
/* Declined at declare because runtime LoRA targets its weight (a fused GEMM no delta can follow):
* recorded unresolved on purpose, its handle never handed to the plugin, so it is never issued
* and the reference-kernel gate does not count it. */
/* Declined at declare because runtime LoRA targets its weight (a fused GEMM no delta can
* follow): recorded unresolved and never handed to the plugin, so it is never issued and the
* reference-kernel gate does not count it. */
bool lora_declined = false;
};
@@ -300,9 +300,9 @@ inline int64_t conv_window_entries(const RadKVGroupDecl& d, int64_t n_spec) {
return (d.conv_width > 0 ? d.conv_width - 1 : 0) + (n_spec > 0 ? n_spec : 0);
}
/* ONE TARGETED GEMM OF A RUNTIME-LoRA PROGRAM (core/lora/), as the issue path needs it: the two ops
* the core appended for it, where in the gemm's own operand list its activation and output are,
* and the buffers the appended ops read. Built once at declare; issue reads it and nothing else. */
/* One targeted GEMM of a runtime-LoRA program (core/lora/), as the issue path needs it: the two ops
* the core appended for it, where the gemm's activation and output are in its operand list, and
* the buffers the appended ops read. Built once at declare. */
struct LoraIssueSite {
uint32_t gemm = 0, shrink = 0, expand = 0; /* op handles */
int8_t opd_a = -1, opd_a_scale = -1, opd_y = -1; /* positions in the GEMM's schema */
@@ -312,7 +312,7 @@ struct LoraIssueSite {
int64_t R = 0, K = 0, N = 0;
};
/* One targeted weight's adapter slots: A [S, R, K], B [S, N, R] bf16 and the per-column scale
* [S, N] f32 -- PERSIST buffers, so the arena plan (and with it the KV budget) holds them. */
* [S, N] f32, persistent buffers, so the arena plan (and with it the KV budget) holds them. */
struct LoraPool {
std::string weight;
rad_buf a = 0, b = 0, scale = 0;
@@ -345,7 +345,7 @@ public:
* no logits buffer. */
rad_buf pooled_buf = 0;
/* RUNTIME LoRA (core/lora/), empty unless the engine was started with adapters enabled. */
/* Runtime LoRA (core/lora/), empty unless the engine was started with adapters enabled. */
std::vector<LoraIssueSite> lora_sites;
std::vector<LoraPool> lora_pools;
std::vector<LoraScratch> lora_t;
@@ -380,6 +380,24 @@ public:
std::vector<double> sigmas;
} gen_str;
bool is_generator() const { return generator.layout != 0; }
/* The declared audio generator (rad_declare_audio_generator); `max_lanes` 0 when none. Its
* strings point at `agen_str`, as the image generator's do at `gen_str`. */
RadAudioGenDecl audio_gen{};
struct AudioGenStrings {
std::string name, tmpl, tmpl_plain, neg_tmpl; /* "" for an absent template */
} agen_str;
bool is_audio_generator() const { return audio_gen.max_lanes != 0; }
/* The declared video generator (rad_declare_video_generator); `max_lanes` 0 when none. */
RadVideoGenDecl video_gen{};
struct VideoGenStrings {
std::string name, tmpl;
std::vector<double> rungs; /* RadVideoGenDecl::rungs; the declaration's pointer is null */
} vgen_str;
bool is_video_generator() const { return video_gen.max_lanes != 0; }
/* Driven by passes, not token steps: any generator. */
bool is_pass_driven() const {
return is_generator() || is_audio_generator() || is_video_generator();
}
/* Two arenas, because a host-site activation cannot index device memory. The buffer plan
* colours each domain separately (transients share storage only within a domain), so each is
@@ -578,9 +596,9 @@ struct TokenScores {
struct Request {
uint64_t id = 0;
/* THE RUNTIME LoRA ADAPTER this request is served with (core/lora/): its slot in the adapter
* pools, -1 for the base model, and the uid of the load that slot held when the request was
* admitted -- the prefix cache keys on the uid, so a reload under the same name starts cold. */
/* The runtime LoRA adapter this request runs with (core/lora/): its slot in the adapter pools,
* -1 for the base model, and the uid of the load that slot held at admission. The prefix cache
* keys on the uid, so a reload under the same name starts cold. */
int32_t lora_slot = -1;
uint64_t lora_uid = 0;
std::vector<int32_t> prompt;
@@ -769,8 +787,9 @@ struct Config {
/* Cap on linear-state (or sliding-window) snapshots held at once, for the whole server. The
* slots are pinned host memory, all allocated at startup and never on the card (spec §7.3).
* A slot is a sizeable fraction of a gigabyte on a linear-attention model, so raising the cap
* trades host RAM for retained checkpoints. */
int64_t checkpoint_slots = 8;
* trades host RAM for retained checkpoints. -1 is `auto`, resolved by the engine when the
* store is opened (checkpoint_slots_auto in core/mem/prefix.h). */
int64_t checkpoint_slots = -1;
bool prefix_cache = true;
/* geometric-backoff | tip-only | keep-all. §19.1 records the default as unmeasured;
* core/mem/prefix.h ships the two extremes so they can be compared. */
+7 -6
View File
@@ -899,8 +899,9 @@ int Ctx::lane_join(int from, int to) {
/* The key below reads every RadBatch field a pass's shape or arguments can depend on, by hand. A
* field added to RadBatch changes its size: decide whether the key must read it, then update the
* size here. */
static_assert(sizeof(void*) != 8 || sizeof(RadBatch) == 320,
* size here. `agen_b` and `vgen_b` are set only on generator passes, which are never recorded
* (below). */
static_assert(sizeof(void*) != 8 || sizeof(RadBatch) == 336,
"RadBatch changed: check that Ctx::pass_key reads every new field a pass depends on");
static_assert(sizeof(void*) != 8 || sizeof(RadKVGroupBatch) == 72,
"RadKVGroupBatch changed: check that Ctx::pass_key reads every new field");
@@ -909,7 +910,8 @@ uint64_t Ctx::pass_key(const RadBatch* b) const {
/* Not recordable: encoder passes are shaped by their media, and passes carrying encoder rows
* issue the scatter only when they have some. */
if (b->enc || b->n_mm_rows > 0) return 0;
/* A generator pass is shaped by what RadBatch::gen_b carries, which no key below reads. */
/* A generator pass is shaped by what RadBatch::gen_b, agen_b or vgen_b carries, which no key
* below reads. */
if (b->gen) return 0;
uint64_t h = 0x9e3779b97f4a7c15ull;
auto mix = [&](uint64_t v) {
@@ -927,9 +929,8 @@ uint64_t Ctx::pass_key(const RadBatch* b) const {
ptr(b->token_ids); ptr(b->positions); ptr(b->cu_seqlens); ptr(b->seq_ids);
ptr(b->out_ids); ptr(b->q_lens); ptr(b->ctx_lens); ptr(b->num_accepted);
ptr(b->spec_parent); ptr(b->checkpoint_tok); ptr(b->checkpoint_slot); ptr(b->draft_out_ids);
/* The adapter ops' slot pointer. One address per rank for the engine's life, null without
* adapters; the slots themselves are read on the card, and the ops are issued whether or not a
* row has an adapter, so what a recorded pass launches never depends on their values. */
/* Null on a step with no adapter row, which then issues no adapter op (Ctx::issue_lora): the
* two are different passes. The slots themselves are read on the card. */
ptr(b->lora_slot);
for (int g = 0; g < b->n_kv_groups; ++g) {
const RadKVGroupBatch& k = b->kv[g];
+1 -1
View File
@@ -86,7 +86,7 @@ struct OpPlan {
/* The conventional all_reduce, whose `n` is the message's element count, so its link bytes
* can be counted (ar_bytes) apart from the expert mover's. */
bool billed = false;
/* RUNTIME LoRA: this gemm's row in Program::lora_sites, -1 for every op that is not one. */
/* Runtime LoRA: this gemm's row in Program::lora_sites, -1 for every op that is not one. */
int32_t lora_site = -1;
};
+32 -27
View File
@@ -415,27 +415,37 @@ int Ctx::issue(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
return rc;
}
/* RUNTIME LoRA: the two ops the core appended for a targeted gemm, issued right behind it on the
/* Runtime LoRA: the two ops the core appended for a targeted gemm, issued right behind it on the
* same stream, over the same rows, through the ordinary issue path (bands, tape, hazards).
*
* t = A[slot] . x lora_shrink, x = the gemm's own activation operand(s)
* y += scale . B[slot] . t lora_expand, y = the gemm's own output operand
*
* Here and only here: a row-parallel gemm's y is this rank's PARTIAL sum and the plugin reduces it
* after this returns, so the delta rides the same reduction (B.A.x is linear in x's shards). Only
* the trunk pass: a draft pass runs the drafter's weights, an encoder pass the tower's. A base row
* (slot -1) is not touched by either kernel, so a step with no adapter rows computes exactly what
* the same step without LoRA does. */
* A row-parallel gemm's y is this rank's partial sum and the plugin reduces it after this returns,
* so the delta rides the same reduction (B.A.x is linear in x's shards). Nothing is issued on a
* step with no adapter row (RadBatch::lora_slot null), which is then the pass an engine without
* adapters runs, nor on a draft pass, whose proposals the trunk verifies. An encoder or generator
* pass never reaches a site: such a weight is outside the targets' scope rule (core/lora/lora.h),
* so reaching one here is refused rather than run without its delta. */
int Ctx::issue_lora(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
if (!batch_ || batch_->draft_pass != 0 || batch_->enc != 0 || batch_->gen != 0) return RAD_OK;
if (!batch_) return RAD_OK;
if (batch_->enc != 0 || batch_->gen != 0)
return abort_step_msg(h, RAD_E_UNSUPPORTED,
"a LoRA-targeted gemm was issued by an encoder or generator pass, "
"which runtime LoRA does not reach; leave its module out of "
"--lora-target-modules");
if (!batch_->lora_slot || batch_->draft_pass != 0) return RAD_OK;
const OpPlan& p = plans_[h];
const LoraIssueSite& s = program_->lora_sites[(size_t)p.lora_site];
if (n == RAD_N_BATCH) n = batch_->n_tok;
if (n <= 0) return RAD_OK;
if (op_domain_[h].load(std::memory_order_relaxed) != RAD_DOMAIN_DEVICE)
/* The adapter ops run in the gemm's domain and read the pools, which are device buffers: on a
* card that is the device domain, and on the host backend every domain is host memory. */
const int dom = (int)op_domain_[h].load(std::memory_order_relaxed);
if (dom != RAD_DOMAIN_DEVICE && !device_is_host())
return abort_step_msg(h, RAD_E_UNSUPPORTED,
"a LoRA-targeted gemm was placed on the host; its adapter delta has "
"no host path, so the step would compute the base model's output");
"a LoRA-targeted gemm was placed on the host, and the adapter pools "
"are on the card");
if (s.opd_a < 0 || s.opd_a >= n_opd || s.opd_y < 0 || s.opd_y >= n_opd)
return abort_step_msg(h, RAD_E_STATE, "LoRA site: the gemm was issued with fewer operands "
"than its schema names");
@@ -445,9 +455,9 @@ int Ctx::issue_lora(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
(size_t)ya.handle >= program_->buffers.size() || (size_t)xa.handle >= program_->buffers.size())
return abort_step_msg(h, RAD_E_UNSUPPORTED, "LoRA site: the gemm's activation or output is "
"not a declared buffer");
/* THE ROWS THE GEMM WROTE ARE ROWS OF THE STEP'S TOKENS starting at r0, so the slot array is
* read from r0 too. A row slice offsets by whole rows of the buffer's declared width; a column
* slice offsets by less than one row. Anything else is a view this code cannot place. */
/* The rows the gemm wrote are the step's token rows from r0 on, so the slot array is read from
* r0 too. A row slice offsets by whole rows of the buffer's declared width and a column slice
* by less than one row; any other view cannot be placed. */
const RadBufDecl& yd = program_->buffers[ya.handle].decl;
const RadBufDecl& xd = program_->buffers[xa.handle].decl;
if (yd.dtype != s.y_dtype || xd.dtype != s.a_dtype)
@@ -461,30 +471,25 @@ int Ctx::issue_lora(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
return abort_step_msg(h, RAD_E_STATE, "LoRA site: the gemm's output view starts inside a "
"row, so its token rows cannot be told");
const int64_t r0 = ya.offset / yw;
/* ...and the activation must be the SAME rows: shrink reads x's row m and expand writes y's
* row m with one slot, so a GEMM whose two views start at different tokens cannot be followed. */
/* The activation must start at the same row: shrink reads x's row m and expand writes y's row
* m with one slot. */
{
const int64_t xw = xd.rank >= 2 ? xd.shape[xd.rank - 1] : 0;
if (xw <= 0 || (xa.cols == 0 && xa.offset % xw != 0) || xa.offset / xw != r0)
return abort_step_msg(h, RAD_E_STATE, "LoRA site: the gemm's activation and output "
"views do not start at the same token row");
}
if (op_domain_[s.shrink].load(std::memory_order_relaxed) != RAD_DOMAIN_DEVICE ||
op_domain_[s.expand].load(std::memory_order_relaxed) != RAD_DOMAIN_DEVICE)
return abort_step_msg(h, RAD_E_UNSUPPORTED, "LoRA site: the adapter ops were placed off "
"the device the gemm runs on");
if ((int)op_domain_[s.shrink].load(std::memory_order_relaxed) != dom ||
(int)op_domain_[s.expand].load(std::memory_order_relaxed) != dom)
return abort_step_msg(h, RAD_E_UNSUPPORTED, "LoRA site: the adapter ops were placed in "
"another domain than the gemm they follow");
if (r0 < 0 || r0 + n > batch_->n_tok)
return abort_step_msg(h, RAD_E_STATE,
fmt("LoRA site: the gemm wrote rows [%lld, %lld) of a %lld-token step",
(long long)r0, (long long)(r0 + n), (long long)batch_->n_tok));
/* Each row's adapter is the step batch's (RadBatch::lora_slot), which the builder fills from
* every request's slot. It sits at one address per rank for the engine's life and is
* rewritten in stream order before each step's kernels, so the pointer this launch records is
* the one a replay of it reads. */
if (!batch_->lora_slot)
return abort_step_msg(h, RAD_E_STATE, "LoRA site: the step batch carries no per-row adapter "
"slot (RadBatch::lora_slot), so the engine was started "
"without adapters and should have declared no site");
/* Each row's adapter is the step batch's (RadBatch::lora_slot), rewritten in stream order
* before each step's kernels, so the pointer this launch records is the one a replay of it
* reads. */
const LoraPool& pool = program_->lora_pools[(size_t)s.pool];
const rad_buf t = program_->lora_t[(size_t)s.t].lane[lane_ ? 1 : 0];
RadOperand slot = RAD_P_T(batch_->lora_slot + r0, RAD_I32);
+7 -3
View File
@@ -124,8 +124,8 @@ void BatchBuilder::carve(Set& s, char* h) {
* moves a rotary position off the token index. */
pair(&s.h_rope, &s.d_rope, mm_on_ ? 3 * T : 0);
pair(&s.h_mmrow, &s.d_mmrow, mm_on_ ? T : 0);
/* Each row's adapter slot, only when the engine serves adapters: with none the slab and every
* offset in it are what they were before adapters existed. */
/* Each row's adapter slot, carved only when the engine serves adapters, so an engine without
* them lays the slab out as if the array did not exist. */
pair(&s.h_lora, &s.d_lora, lora_on_ ? T : 0);
/* Host-only (derived metadata is copied into the planned arena), but carved on both sides to
* keep device offsets equal to host offsets. */
@@ -871,6 +871,7 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
int64_t n_out = 0, n_dout = 0;
int32_t rope_mixed = 0;
int64_t n_mm = 0;
bool lora_rows = false;
s.h_cu[0] = 0;
for (int64_t i = 0; i < n_seq; ++i) {
const StepEntry& e = plan.e[(size_t)i];
@@ -902,6 +903,7 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
if (lora_on_) {
const int32_t ls = e.req ? e.req->lora_slot : -1;
for (int32_t j = 0; j < e.n_tokens; ++j) s.h_lora[k + j] = ls;
if (ls >= 0 && e.n_tokens > 0) lora_rows = true;
}
/* Rotary position of each row at its own position (draft-head rows rotate at the index
* they write, not the token they embed). Three planes of n_tok. */
@@ -1108,7 +1110,9 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
B.n_mm_rows = n_mm;
B.mm_rows = n_mm ? on_rank(base, b0, s.d_mmrow) : nullptr;
B.mm_embd = n_mm ? mm_dev_[r] : nullptr;
B.lora_slot = lora_on_ ? on_rank(base, b0, s.d_lora) : nullptr;
/* Null on a step with no adapter row: the core then issues no adapter op, and the step
* runs the same pass as an engine serving no adapters. */
B.lora_slot = lora_rows ? on_rank(base, b0, s.d_lora) : nullptr;
B.enc = 0;
B.enc_n_patch = 0;
B.enc_pixels = nullptr;
+6 -6
View File
@@ -284,11 +284,10 @@ struct KVBinding final : IKVManager {
* and segment: the same picture at the same place hits, two pictures never alias. */
inline void media_keys(const Request& r, std::vector<MMContentKey>* out) {
out->clear();
/* THE RUNTIME LoRA ADAPTER IS PART OF EVERY BLOCK'S KEY. KV written under an adapter is not
* the base's, so it rides into the chain as one span over the whole sequence, keyed by the
* adapter's load uid -- every block overlaps it, and with uid 0 (the base) there is no span and
* every hash is what it was before adapters existed. The uid, never the name: a reload under
* the same name is new weights and must start cold. */
/* The runtime LoRA adapter is part of every block's key: KV written under an adapter is not
* the base's. It enters the chain as one span over the whole sequence, keyed by the adapter's
* load uid, so every block overlaps it; the base (uid 0) adds no span and its hashes are
* unchanged. The uid and not the name, because a reload under the same name is new weights. */
if (r.lora_uid != 0) {
MMContentKey k;
k.tok_begin = 0;
@@ -319,7 +318,8 @@ struct PCBinding final : IPrefixCache {
CacheHit lookup(const Request& r, std::vector<std::vector<int32_t>>* out,
const HitCap* cap) const override {
media_keys(r, &mm_);
return m->lookup(r.prompt, mm_, out, cap);
/* r.id: the admission takes its conversation's snapshots over. */
return m->lookup(r.prompt, mm_, out, cap, r.id);
}
/* Installed by the engine when the idle tiers are on; empty otherwise. */
+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 */