Archived
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:
1 parent
4e750fed01
commit
bdc5c5b063
13 files changed
+396
-24
No files matched your search
+25
-6
@@ -974,6 +974,24 @@ typedef struct RadAudioGenDecl {
|
||||
* text always is, so a caller can write the model's speaker tags. The plugin's
|
||||
* rad_arch_text_prepare then refuses the control tokens a caller must not write. */
|
||||
int32_t input_special;
|
||||
/* References (voice cloning): with `tmpl_ref`, a request may carry up to `ref_max` of them,
|
||||
* each a transcript and a clip of the voice saying it, which the plugin encodes into frames
|
||||
* in the request's PROMPT pass (whole prompts only: `prompt_whole`). `tmpl_ref` is the prompt
|
||||
* of a request with references, `{references}` each of them rendered from `ref_item` in turn
|
||||
* and `{input}` as in `tmpl_plain`. `ref_item` is one reference: `{index}` its number from 1,
|
||||
* `{text}` its transcript (rewritten by rad_arch_text_prepare as RAD_TEXT_REFERENCE) and
|
||||
* `{audio}` its frames, one prompt row each (RadAudioGenBatch::ref_frame); the text before
|
||||
* `{audio}` is tokenised as one segment with its special tokens (the transcript's own, which
|
||||
* prepare() has limited to those a caller may write), and so is the text after it. A clip is
|
||||
* mono f32 in [-1, 1] at `ref_rate`, right-padded with zeros to a whole number of `ref_hop`
|
||||
* samples, each `ref_hop` samples one frame; a request's clips hold at most `ref_max_samples`
|
||||
* samples together. NULL `tmpl_ref`: references are refused. */
|
||||
const char* tmpl_ref;
|
||||
const char* ref_item;
|
||||
int64_t ref_rate;
|
||||
int64_t ref_hop;
|
||||
int64_t ref_max_samples;
|
||||
int32_t ref_max;
|
||||
} RadAudioGenDecl;
|
||||
|
||||
int rad_declare_audio_generator(RadBuilder* b, const RadAudioGenDecl* d);
|
||||
@@ -1429,12 +1447,13 @@ const RadAudioFormat* rad_arch_audio_format(const RadModelMeta* meta);
|
||||
* as given. Training data has conventions a client does not know -- section tags on lines of
|
||||
* their own and lower case, no markdown in a description -- and only the plugin knows them.
|
||||
*
|
||||
* `field` is RAD_TEXT_*, `in` NUL-terminated UTF-8. Writes at most `cap` bytes, the NUL included,
|
||||
* and returns the length the whole result needs without its NUL (call again with more room when
|
||||
* it is >= cap), or a negative status for text the model cannot take, with the reason in `out`
|
||||
* (NUL-terminated within `cap`) when it has one to give the caller. Called on HTTP threads, so it
|
||||
* keeps no state. */
|
||||
enum { RAD_TEXT_INSTRUCTIONS = 1, RAD_TEXT_INPUT = 2 };
|
||||
* `field` is RAD_TEXT_*, `in` NUL-terminated UTF-8: the instructions, the input, or a
|
||||
* reference's transcript (RadAudioGenDecl::ref_item's `{text}`). Writes at most `cap` bytes, the
|
||||
* NUL included, and returns the length the whole result needs without its NUL (call again with
|
||||
* more room when it is >= cap), or a negative status for text the model cannot take, with the
|
||||
* reason in `out` (NUL-terminated within `cap`) when it has one to give the caller. Called on
|
||||
* HTTP threads, so it keeps no state. */
|
||||
enum { RAD_TEXT_INSTRUCTIONS = 1, RAD_TEXT_INPUT = 2, RAD_TEXT_REFERENCE = 3 };
|
||||
int64_t rad_arch_text_prepare(int field, const char* in, char* out, int64_t cap);
|
||||
|
||||
/* The layout of a video generator's passes (rad_declare_video_generator), which only the model
|
||||
|
||||
@@ -475,6 +475,20 @@ typedef struct RadAudioGenBatch {
|
||||
const int32_t* prev_slot;
|
||||
const int32_t* prev_pos;
|
||||
const int32_t* prev_used;
|
||||
|
||||
/* PROMPT of a request with references (RadAudioGenDecl::tmpl_ref; n_ref 0 without): its
|
||||
* clips' samples end to end (`ref_samples` f32 on the device), the clips' bounds in samples
|
||||
* ([n_ref + 1], each a whole number of RadAudioGenDecl::ref_hop), and for every row of the
|
||||
* pass the frame of the clips it is or -1 for a token row ([n_tok]), frames counted over the
|
||||
* clips in order, frame f the samples [f ref_hop, (f + 1) ref_hop). A frame's row stages
|
||||
* token 0; the plugin embeds the frame there instead. */
|
||||
int64_t n_ref;
|
||||
int64_t ref_samples;
|
||||
const float* ref_audio;
|
||||
const int32_t* ref_cu;
|
||||
const int32_t* ref_cu_h;
|
||||
const int32_t* ref_frame;
|
||||
const int32_t* ref_frame_h;
|
||||
} RadAudioGenBatch;
|
||||
|
||||
/* A window entry's flags on a WINDOW pass. FIRST is RAD_GEN_F_FIRST's bit and the others are clear
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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 */
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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
@@ -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
@@ -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;
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -140,6 +140,13 @@ ABI_FIELD(RadAudioGenBatch, voc_frame0)
|
||||
ABI_FIELD(RadAudioGenBatch, prev_slot)
|
||||
ABI_FIELD(RadAudioGenBatch, prev_pos)
|
||||
ABI_FIELD(RadAudioGenBatch, prev_used)
|
||||
ABI_FIELD(RadAudioGenBatch, n_ref)
|
||||
ABI_FIELD(RadAudioGenBatch, ref_samples)
|
||||
ABI_FIELD(RadAudioGenBatch, ref_audio)
|
||||
ABI_FIELD(RadAudioGenBatch, ref_cu)
|
||||
ABI_FIELD(RadAudioGenBatch, ref_cu_h)
|
||||
ABI_FIELD(RadAudioGenBatch, ref_frame)
|
||||
ABI_FIELD(RadAudioGenBatch, ref_frame_h)
|
||||
ABI_STRUCT(RadAudioGenDecl)
|
||||
ABI_FIELD(RadAudioGenDecl, name)
|
||||
ABI_FIELD(RadAudioGenDecl, tmpl)
|
||||
@@ -174,6 +181,12 @@ ABI_FIELD(RadAudioGenDecl, voc_chunk)
|
||||
ABI_FIELD(RadAudioGenDecl, voc_context)
|
||||
ABI_FIELD(RadAudioGenDecl, branches)
|
||||
ABI_FIELD(RadAudioGenDecl, input_special)
|
||||
ABI_FIELD(RadAudioGenDecl, tmpl_ref)
|
||||
ABI_FIELD(RadAudioGenDecl, ref_item)
|
||||
ABI_FIELD(RadAudioGenDecl, ref_rate)
|
||||
ABI_FIELD(RadAudioGenDecl, ref_hop)
|
||||
ABI_FIELD(RadAudioGenDecl, ref_max_samples)
|
||||
ABI_FIELD(RadAudioGenDecl, ref_max)
|
||||
ABI_STRUCT(RadAudioFormat)
|
||||
ABI_FIELD(RadAudioFormat, struct_size)
|
||||
ABI_FIELD(RadAudioFormat, audio_open)
|
||||
|
||||
@@ -201,6 +201,115 @@ TEST(a_model_that_asks_has_its_input_read_with_special_tokens_and_one_branch_has
|
||||
CHECK(!m.f->tok.last_parse_special);
|
||||
}
|
||||
|
||||
/* A 16-bit mono WAV of the given samples at `rate`. */
|
||||
static std::string wav_of(const std::vector<int16_t>& x, uint32_t rate) {
|
||||
std::string d;
|
||||
for (int16_t v : x) {
|
||||
d.push_back((char)(v & 0xff));
|
||||
d.push_back((char)((v >> 8) & 0xff));
|
||||
}
|
||||
auto u32 = [](uint32_t v) {
|
||||
std::string b;
|
||||
for (int i = 0; i < 4; ++i) b.push_back((char)((v >> (8 * i)) & 0xff));
|
||||
return b;
|
||||
};
|
||||
auto u16 = [](uint16_t v) { return std::string{ (char)(v & 0xff), (char)(v >> 8) }; };
|
||||
return "RIFF" + u32((uint32_t)(36 + d.size())) + "WAVEfmt " + u32(16) + u16(1) + u16(1) +
|
||||
u32(rate) + u32(rate * 2) + u16(2) + u16(16) + "data" + u32((uint32_t)d.size()) + d;
|
||||
}
|
||||
|
||||
/* A model that clones a voice takes references: each clip decoded at its rate and padded to
|
||||
* whole frames, the prompt its references' template with each one's header, transcript and a row
|
||||
* a frame (token 0, the clips' frames numbered in order), the rest of the rows -1. A data: URL and
|
||||
* bare base64 both carry a clip. Refused by name: references on a model without them, too many,
|
||||
* a reference without its text or clip or with an unknown field, a clip past the budget, and
|
||||
* instructions beside them. */
|
||||
TEST(a_cloning_model_takes_references_as_clips_and_transcripts_in_its_prompt) {
|
||||
if (!mm::decoder_available()) return;
|
||||
Speech s;
|
||||
s.gen.inf.tmpl_plain = "<s>{input}";
|
||||
s.gen.inf.tmpl_ref = "<s>R{references}|{input}";
|
||||
s.gen.inf.ref_item = "[{index}:{text}]{audio}.";
|
||||
s.gen.inf.ref_rate = 8000;
|
||||
s.gen.inf.ref_hop = 4;
|
||||
s.gen.inf.ref_max_samples = 16;
|
||||
s.gen.inf.ref_max = 2;
|
||||
s.gen.inf.default_steps = 0;
|
||||
s.gen.inf.branches = 1;
|
||||
const std::string w1 = wav_of({ 1000, -2000, 3000, 4000, 5000 }, 8000);
|
||||
const std::string w2 = wav_of({ -16384, 16384 }, 8000);
|
||||
const std::string b1 = base64_encode((const uint8_t*)w1.data(), w1.size());
|
||||
const std::string b2 = base64_encode((const uint8_t*)w2.data(), w2.size());
|
||||
json refs = json::array({ json{ { "audio", b1 }, { "text", "one" } },
|
||||
json{ { "audio", "data:audio/wav;base64," + b2 },
|
||||
{ "text", "two" } } });
|
||||
CHECK_EQ(s.post({ { "input", "hi" }, { "references", refs } }).status, 200);
|
||||
const gen::AudioRequest& q = s.last();
|
||||
/* "<s>R", "[1:one]", 2 frames, ".", "[2:two]", 1 frame, ".", "|hi". */
|
||||
const std::string head = "<s>R[1:one]";
|
||||
std::vector<int32_t> want_tok, want_frame;
|
||||
auto text = [&](const std::string& t) {
|
||||
for (unsigned char c : t) { want_tok.push_back(c); want_frame.push_back(-1); }
|
||||
};
|
||||
auto frames = [&](int32_t f0, int32_t n) {
|
||||
for (int32_t f = 0; f < n; ++f) { want_tok.push_back(0); want_frame.push_back(f0 + f); }
|
||||
};
|
||||
text(head);
|
||||
frames(0, 2);
|
||||
text(".[2:two]");
|
||||
frames(2, 1);
|
||||
text(".|hi");
|
||||
CHECK(q.tokens == want_tok);
|
||||
CHECK(q.ref_frame == want_frame);
|
||||
REQUIRE(q.ref_cu.size() == 3);
|
||||
CHECK_EQ(q.ref_cu[1], 8);
|
||||
CHECK_EQ(q.ref_cu[2], 12);
|
||||
REQUIRE(q.ref_audio.size() == 12);
|
||||
CHECK(std::fabs(q.ref_audio[0] - 1000.0f / 32768.0f) < 1e-6f);
|
||||
CHECK(std::fabs(q.ref_audio[1] + 2000.0f / 32768.0f) < 1e-6f);
|
||||
CHECK_EQ(q.ref_audio[5], 0.0f);
|
||||
CHECK_EQ(q.ref_audio[7], 0.0f);
|
||||
CHECK(std::fabs(q.ref_audio[8] + 0.5f) < 1e-6f);
|
||||
CHECK_EQ(q.ref_audio[11], 0.0f);
|
||||
/* Without references the plain prompt, and no clips. */
|
||||
CHECK_EQ(s.post({ { "input", "hi" }, { "references", json::array() } }).status, 200);
|
||||
CHECK(s.last().ref_cu.empty() && s.last().ref_frame.empty() && s.last().ref_audio.empty());
|
||||
|
||||
const json one = json{ { "audio", b1 }, { "text", "one" } };
|
||||
CHECK_EQ(s.refused({ { "input", "hi" }, { "references", json::array({ one, one, one }) } }),
|
||||
std::string("references"));
|
||||
CHECK_EQ(s.refused({ { "input", "hi" }, { "references", one } }), std::string("references"));
|
||||
CHECK_EQ(s.refused({ { "input", "hi" },
|
||||
{ "references", json::array({ json{ { "audio", b1 } } }) } }),
|
||||
std::string("references[0].text"));
|
||||
CHECK_EQ(s.refused({ { "input", "hi" },
|
||||
{ "references", json::array({ json{ { "text", "x" } } }) } }),
|
||||
std::string("references[0].audio"));
|
||||
CHECK_EQ(s.refused({ { "input", "hi" },
|
||||
{ "references", json::array({ json{ { "audio", b1 }, { "text", "x" },
|
||||
{ "speaker", 1 } } }) } }),
|
||||
std::string("references[0].speaker"));
|
||||
CHECK_EQ(s.refused({ { "input", "hi" },
|
||||
{ "references", json::array({ json{ { "audio", "@@@" },
|
||||
{ "text", "x" } } }) } }),
|
||||
std::string("references[0].audio"));
|
||||
/* 8 and 8 samples fit the 16; a third frame past them does not. */
|
||||
const std::string w3 = wav_of(std::vector<int16_t>(9, 7), 8000);
|
||||
const std::string b3 = base64_encode((const uint8_t*)w3.data(), w3.size());
|
||||
CHECK_EQ(s.refused({ { "input", "hi" },
|
||||
{ "references", json::array({ one, json{ { "audio", b3 },
|
||||
{ "text", "x" } } }) } }),
|
||||
std::string("references[1].audio"));
|
||||
CHECK_EQ(s.refused({ { "input", "hi" }, { "instructions", "calm" }, { "references", refs } }),
|
||||
std::string("instructions"));
|
||||
CHECK_EQ(s.refused({ { "input", "hi" },
|
||||
{ "references", json::array({ json{ { "audio", b1 },
|
||||
{ "text", "REFUSE" } } }) } }),
|
||||
std::string("references[0].text"));
|
||||
Speech m;
|
||||
CHECK_EQ(m.refused(Speech::body({ { "references", refs } })), std::string("references"));
|
||||
}
|
||||
|
||||
/* ================================================================== the response */
|
||||
|
||||
/* The whole piece: the windows in order whatever order they were played in, as a WAV whose header
|
||||
|
||||
Reference in new issue
Block a user