core: references for an audio generator -- a request's clips of a voice and their transcripts (RadAudioGenDecl::tmpl_ref, ref_item), decoded to mono at the model's rate and padded to whole frames, each frame a prompt row the plugin encodes in the PROMPT pass (RadAudioGenBatch::ref_audio, ref_cu, ref_frame); /v1/audio/speech's and the streaming session's references

This commit is contained in:
zivius committed 2026-10-21 01:00:13 +02:00
1 parent 4e750fed01
commit bdc5c5b063
13 files changed
+396 -24

No files matched your search

+36
View File
@@ -1376,6 +1376,33 @@ int Builder::declare_audio_generator(const RadAudioGenDecl* d) {
"instructions and needs {input} alone", nm);
return RAD_E_INVAL;
}
/* References: a template with both of its slots, an item with one transcript before its one
* clip, and the clips' geometry; read whole by one branch's prompt (an unconditional branch
* would need references of its own). */
if (d->tmpl_ref) {
auto once = [](const char* t, const char* k) {
const char* a = t ? std::strstr(t, k) : nullptr;
return a && !std::strstr(a + 1, k);
};
const char* au = d->ref_item ? std::strstr(d->ref_item, "{audio}") : nullptr;
const char* tx = d->ref_item ? std::strstr(d->ref_item, "{text}") : nullptr;
if (!once(d->tmpl_ref, "{references}") || !once(d->tmpl_ref, "{input}") ||
std::strstr(d->tmpl_ref, "{instructions}") || !once(d->ref_item, "{audio}") ||
!once(d->ref_item, "{text}") || !au || !tx || tx > au) {
err(RAD_E_INVAL, "declare_audio_generator '%s': tmpl_ref needs {references} and "
"{input} once each, and ref_item {text} before its one {audio}", nm);
return RAD_E_INVAL;
}
if (d->branches != 1 || !d->prompt_whole || d->ref_rate <= 0 || d->ref_hop <= 0 ||
d->ref_max <= 0 || d->ref_max_samples < d->ref_hop) {
err(RAD_E_INVAL, "declare_audio_generator '%s': references are read by a model of one "
"branch from whole prompts, clips at a rate (%lld Hz) in frames of "
"%lld samples, at most %d of them and %lld samples a request", nm,
(long long)d->ref_rate, (long long)d->ref_hop, (int)d->ref_max,
(long long)d->ref_max_samples);
return RAD_E_INVAL;
}
}
if (d->branches != 0 && d->branches != 1 && d->branches != 2) {
err(RAD_E_INVAL, "declare_audio_generator '%s': branches is %d; a request runs 1 sequence "
"or 2 (0 means 2)", nm, (int)d->branches);
@@ -1468,12 +1495,21 @@ int Builder::declare_audio_generator(const RadAudioGenDecl* d) {
prog_.agen_str.tmpl = d->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_.agen_str.tmpl_ref = d->tmpl_ref ? d->tmpl_ref : "";
prog_.agen_str.ref_item = d->tmpl_ref && d->ref_item ? d->ref_item : "";
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;
prog_.audio_gen.tmpl_ref = nullptr;
prog_.audio_gen.ref_item = nullptr;
/* Without references the clips' geometry is nothing: the driver stages none. */
if (!d->tmpl_ref) {
prog_.audio_gen.ref_rate = prog_.audio_gen.ref_hop = prog_.audio_gen.ref_max_samples = 0;
prog_.audio_gen.ref_max = 0;
}
return RAD_OK;
}
+6
View File
@@ -2501,6 +2501,12 @@ int Engine::run_server() {
in.max_lanes = ad.max_lanes;
in.branches = ad.branches == 1 ? 1 : 2;
in.input_special = ad.input_special != 0;
in.tmpl_ref = pg.agen_str.tmpl_ref;
in.ref_item = pg.agen_str.ref_item;
in.ref_rate = ad.ref_rate;
in.ref_hop = ad.ref_hop;
in.ref_max_samples = ad.ref_max_samples;
in.ref_max = ad.ref_max;
audio_bridge.drv = aud_gen_;
audio_bridge.plugins = &plugins_;
d.audio = &audio_bridge;
+6
View File
@@ -65,6 +65,12 @@ struct AudioRequest {
* conditional prompt as the declaration says (neg_token), and `neg_tokens` is empty. */
std::vector<int32_t> tokens;
std::vector<int32_t> neg_tokens;
/* References (RadAudioGenDecl::tmpl_ref): the clips' samples end to end, each padded to whole
* frames; their bounds in samples, [clips + 1]; and for each row of `tokens` the frame of the
* clips it is, -1 for a token. All empty without references. */
std::vector<float> ref_audio;
std::vector<int32_t> ref_cu;
std::vector<int32_t> ref_frame;
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 */
+51
View File
@@ -69,6 +69,7 @@ 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;
int64_t NG = 0; /* stateful KV groups */
int64_t RS = 0, RN = 0; /* references: samples and clips a request */
};
/* The paged full-attention group, and how many stateful groups sit beside it. */
@@ -92,6 +93,8 @@ Sizes sizes_of(const Program& prog, int64_t block_size) {
z.L = d.max_lanes;
z.NB = block_size > 0 ? (AudioDriver::max_seq_rows(d) + block_size - 1) / block_size : 0;
full_group(prog, &z.NG);
z.RS = d.ref_max_samples;
z.RN = d.ref_max;
return z;
}
@@ -132,6 +135,9 @@ int64_t carve(const Sizes& z, int64_t (*bytes)[2], int n) {
z.S * I, /* R_PSLOT */
z.S * I, /* R_PPOS */
z.S * I, /* R_PUSED */
z.RS * 4, /* R_RAUD */
z.RN > 0 ? (z.RN + 1) * I : 0, /* R_RCU */
z.RN > 0 ? z.T * I : 0, /* R_RFRM */
};
int64_t off = 0;
for (int r = 0; r < n; ++r) {
@@ -286,6 +292,25 @@ int AudioDriver::submit(std::unique_ptr<AudioRequest> r, std::string* why) {
" 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");
/* References: the clips the declaration allows, each a whole number of frames, and a frame
* for every row that names one. */
if (!r->ref_cu.empty() || !r->ref_frame.empty() || !r->ref_audio.empty()) {
const int64_t n_ref = (int64_t)r->ref_cu.size() - 1, hop = d.ref_hop;
bool ok = d.ref_max > 0 && n_ref >= 1 && n_ref <= d.ref_max && r->ref_cu[0] == 0 &&
r->ref_cu.back() == (int64_t)r->ref_audio.size() &&
(int64_t)r->ref_audio.size() <= d.ref_max_samples &&
(int64_t)r->ref_frame.size() == T;
for (int64_t i = 0; ok && i < n_ref; ++i)
ok = r->ref_cu[(size_t)i + 1] > r->ref_cu[(size_t)i] && r->ref_cu[(size_t)i + 1] % hop == 0;
const int64_t frames = ok ? r->ref_cu.back() / hop : 0;
for (int64_t t = 0; ok && t < T; ++t)
ok = r->ref_frame[(size_t)t] >= -1 && r->ref_frame[(size_t)t] < frames;
if (!ok)
return no(d.ref_max > 0 ? "the references do not fit this model: at most " +
std::to_string(d.ref_max) + " clips of whole frames, " +
std::to_string(d.ref_max_samples) + " samples together"
: std::string("this model takes no reference audio"));
}
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 "
@@ -669,6 +694,22 @@ const RadBatch* AudioDriver::build_prompt(Job& j, int step) {
reg_[R_USED].used = nb_ * 4;
reg_[R_LANE].used = reg_[R_LAST].used = 4;
reg_[R_SEED].used = 8;
/* The references: their clips, bounds and each row's frame (a whole prompt, so the rows are
* the prompt's own). */
const AudioRequest& q = *j.req;
const int64_t n_ref = q.ref_cu.empty() ? 0 : (int64_t)q.ref_cu.size() - 1;
h_rcu_.clear();
h_rfrm_.clear();
if (n_ref > 0) {
std::memcpy(hptr<float>(R_RAUD), q.ref_audio.data(), q.ref_audio.size() * 4);
std::memcpy(hptr<int32_t>(R_RCU), q.ref_cu.data(), q.ref_cu.size() * 4);
std::memcpy(hptr<int32_t>(R_RFRM), q.ref_frame.data() + p0, (size_t)cb[0] * 4);
reg_[R_RAUD].used = (int64_t)q.ref_audio.size() * 4;
reg_[R_RCU].used = (int64_t)q.ref_cu.size() * 4;
reg_[R_RFRM].used = cb[0] * 4;
h_rcu_ = q.ref_cu;
h_rfrm_.assign(q.ref_frame.begin() + p0, q.ref_frame.begin() + p0 + cb[0]);
}
if (upload() < 0) return nullptr;
base_batches(rows, nb_, (int32_t)cmax, (int32_t)(p0 + cmax), step, true, pitch);
h_lane_.assign(1, j.lane);
@@ -679,6 +720,16 @@ const RadBatch* AudioDriver::build_prompt(Job& j, int step) {
A.n_lane = 1;
A.lane_h = h_lane_.data();
A.last_h = h_last_.data();
if (n_ref > 0) {
const int ri = (int)r;
A.n_ref = n_ref;
A.ref_samples = (int64_t)q.ref_audio.size();
A.ref_audio = dptr<float>(ri, R_RAUD);
A.ref_cu = dptr<int32_t>(ri, R_RCU);
A.ref_cu_h = h_rcu_.data();
A.ref_frame = dptr<int32_t>(ri, R_RFRM);
A.ref_frame_h = h_rfrm_.data();
}
}
pass_.kind = RAD_GEN_PASS_PROMPT;
pass_.jobs.assign(1, j.id);
+2 -2
View File
@@ -125,7 +125,7 @@ private:
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_CTX, R_ACC, R_SBT, R_SIDX, R_PSLOT, R_PPOS, R_PUSED,
R_N };
R_RAUD, R_RCU, R_RFRM, R_N };
/* A hybrid model's stateful groups (linear-attention state, convolution history), each staged
* as one block-table word a sequence (its slot) and its state_index row. */
struct StateGroup { int32_t g = 0; int64_t width = 1; };
@@ -190,7 +190,7 @@ private:
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_;
h_wf0_, h_wnf_, h_lcu_, h_rcu_, h_rfrm_;
mutable std::mutex mu_;
std::deque<std::unique_ptr<Job>> jobs_; /* arrival order */
+2 -1
View File
@@ -411,7 +411,8 @@ public:
* 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 */
/* "" for an absent template; tmpl_ref and ref_item RadAudioGenDecl's references */
std::string name, tmpl, tmpl_plain, neg_tmpl, tmpl_ref, ref_item;
} 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. */
+126 -14
View File
@@ -11,6 +11,12 @@
* `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`.
*
* References, for a model that clones a voice (RadAudioGenDecl::tmpl_ref): `references` is an
* array of {"audio", "text"}, a clip of the voice (a data: URL or the base64 of an audio file,
* decoded to mono at the model's rate and padded to whole frames) and what it says; at most the
* model's count of them and seconds together. The prompt is then the references' template, each
* reference rendered from the model's item, its transcript and a row a frame of its clip.
*
* 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
@@ -30,6 +36,7 @@
#include "oai.h"
#include "gen/audio.h"
#include "mm/media.h"
#include "rad_internal.h"
#include <nlohmann/json.hpp>
@@ -176,36 +183,141 @@ int Server::speech_request(const json& body, const std::string& text,
r->seed = (((uint64_t)rd() << 32) ^ rd()) & (((uint64_t)1 << 53) - 1);
}
/* ---- the references: a clip of a voice and what it says, each */
struct Ref { std::string text; int64_t frames = 0; };
std::vector<Ref> refs;
if (body.contains("references") && !body["references"].is_null()) {
const json& rs = body["references"];
if (!rs.is_array())
return fail(err_bad("references", "expected an array of {\"audio\", \"text\"}"));
if (!rs.empty() && info.tmpl_ref.empty())
return fail(err_unsupported("references", "this model takes no reference audio; its "
"voice is described in the input"));
if ((int64_t)rs.size() > info.ref_max)
return fail(err_bad("references", "at most " + std::to_string(info.ref_max) +
" references a request"));
const int64_t hop = std::max<int64_t>(1, info.ref_hop);
r->ref_cu.assign(1, 0);
for (size_t i = 0; i < rs.size(); ++i) {
const std::string at = "references[" + std::to_string(i) + "]";
const json& e = rs[i];
if (!e.is_object())
return fail(err_bad(at, "expected an object {\"audio\", \"text\"}"));
for (auto it = e.begin(); it != e.end(); ++it)
if (it.key() != "audio" && it.key() != "text")
return fail(err_bad(at + "." + it.key(), "a reference is its audio and its "
"text"));
if (!e.contains("audio") || !e["audio"].is_string())
return fail(err_bad(at + ".audio", "the clip is required, as a data: URL or "
"base64 of an audio file"));
if (!e.contains("text") || !e["text"].is_string() || blank(e["text"].get<std::string>()))
return fail(err_bad(at + ".text", "the clip's transcript is required, as a "
"non-empty string"));
/* The file: a data: URL, or its base64 alone (as fish-speech's server takes it). */
const std::string& a = e["audio"].get_ref<const std::string&>();
std::vector<uint8_t> bytes;
if (a.rfind("data:", 0) == 0) {
ApiError ue;
if (decode_media_url(a, at + ".audio", &bytes, &ue) < 0) return fail(ue);
} else if (!base64_decode(a, &bytes)) {
return fail(err_bad(at + ".audio", "invalid base64"));
}
/* Mono at the model's rate; one sample past what is left of the budget is decoded,
* so a clip too long is refused rather than cut. */
const int64_t left = info.ref_max_samples - (int64_t)r->ref_audio.size();
std::vector<float> pcm;
std::string dwhy;
if (left < hop)
return fail(err_bad(at + ".audio", "the references are longer than this model "
"takes"));
if (mm::decode_audio(bytes.data(), bytes.size(), (int32_t)info.ref_rate, left + 1,
&pcm, &dwhy) < 0)
return fail(err_bad(at + ".audio", "the clip could not be used: " + dwhy));
if (pcm.empty()) return fail(err_bad(at + ".audio", "the clip holds no audio"));
const int64_t padded = ((int64_t)pcm.size() + hop - 1) / hop * hop;
if (padded > left)
return fail(err_bad(at + ".audio", "the references hold more than " +
rad::fmt("%g", (double)info.ref_max_samples /
(double)info.ref_rate) +
" seconds together; this model takes no "
"more"));
pcm.resize((size_t)padded, 0.0f);
r->ref_audio.insert(r->ref_audio.end(), pcm.begin(), pcm.end());
r->ref_cu.push_back((int32_t)r->ref_audio.size());
Ref ref;
std::string why;
if (deps_.audio->prepare(RAD_TEXT_REFERENCE, e["text"].get<std::string>(), &ref.text,
&why) < 0)
return fail(err_bad(at + ".text", why));
ref.frames = padded / hop;
refs.push_back(std::move(ref));
}
if (refs.empty()) r->ref_cu.clear();
}
if (!refs.empty() && !inst.empty())
return fail(err_unsupported("instructions", "a request with references takes no "
"instructions; the clips set the voice"));
/* ---- 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));
auto encode = [&](const std::string& t, bool special, std::vector<int32_t>* ids_out) {
if (t.empty()) return;
const auto ids = deps_.tok->encode(t, false, /*parse_special=*/special);
ids_out->insert(ids_out->end(), ids.begin(), ids.end());
};
auto subst = [](std::string t, const std::string& key, const std::string& v) {
for (size_t p = t.find(key); p != std::string::npos; p = t.find(key, p + v.size()))
t.replace(p, key.size(), v);
return t;
};
/* One reference (ref_item): its header, the transcript in it, tokenised as one segment with
* its special tokens (the speaker tags prepare() allows), a row a frame of its clip, and what
* follows the clip as another segment. */
int64_t frame0 = 0;
auto render_ref = [&](size_t i, std::vector<int32_t>* ids_out) {
static const std::string kAudio = "{audio}";
const std::string idx = std::to_string(i + 1);
const size_t a = info.ref_item.find(kAudio);
encode(subst(subst(info.ref_item.substr(0, a), "{index}", idx), "{text}", refs[i].text),
true, ids_out);
r->ref_frame.resize(ids_out->size(), -1);
for (int64_t f = 0; f < refs[i].frames; ++f) {
ids_out->push_back(0);
r->ref_frame.push_back((int32_t)(frame0 + f));
}
frame0 += refs[i].frames;
encode(subst(info.ref_item.substr(a + kAudio.size()), "{index}", idx), true, ids_out);
};
/* 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}";
static const std::string kInst = "{instructions}", kInput = "{input}",
kRefs = "{references}";
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());
}
const size_t a = t.find(kInst, at), b = t.find(kInput, at), c = t.find(kRefs, at);
const size_t p = std::min(a, std::min(b, c));
encode(t.substr(at, p == std::string::npos ? std::string::npos : p - at), true,
ids_out);
if (p == std::string::npos) break;
if (p == c) {
for (size_t i = 0; i < refs.size(); ++i) render_ref(i, ids_out);
at = p + kRefs.size();
continue;
}
const bool is_inst = p == a;
/* The input keeps its special tokens only for a model that asks (its speaker tags);
* the plugin's prepare() has refused the ones a caller may not write. */
const auto ids = deps_.tok->encode(is_inst ? i2 : t2, false,
/*parse_special=*/!is_inst && info.input_special);
ids_out->insert(ids_out->end(), ids.begin(), ids.end());
encode(is_inst ? i2 : t2, !is_inst && info.input_special, ids_out);
at = p + (is_inst ? kInst : kInput).size();
}
};
render(inst.empty() ? info.tmpl_plain : info.tmpl, &r->tokens);
render(!refs.empty() ? info.tmpl_ref : inst.empty() ? info.tmpl_plain : info.tmpl,
&r->tokens);
if (!refs.empty()) r->ref_frame.resize(r->tokens.size(), -1);
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)
@@ -234,7 +346,7 @@ HttpResponse Server::handle_speech(const HttpRequest& req) {
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",
"guidance_scale", "user", "references",
};
for (auto it = body.begin(); it != body.end(); ++it) {
bool known = false;
+5
View File
@@ -653,6 +653,11 @@ struct AudioGenInfo {
* tokenised with special tokens). */
int32_t branches = 2;
bool input_special = false;
/* RadAudioGenDecl's references: the prompt with them and one reference ("" when the model
* takes none), the clips' rate and frame, and the most of them and their samples. */
std::string tmpl_ref, ref_item;
int64_t ref_rate = 0, ref_hop = 0, ref_max_samples = 0;
int32_t ref_max = 0;
};
class IAudioGen {
+1 -1
View File
@@ -214,7 +214,7 @@ bool Server::speech_stream_loop(SpeechSession& s, WsConn& ws) {
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",
"references", "stream_audio", "split_granularity", "text_input_mode",
};
json fields = json::object();
for (auto it = j.begin(); it != j.end(); ++it) {