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

+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 */