radiance 1.6.0

- Qwen-Image 2.1 and 2.1 Turbo: text to image and image edits over OpenAI's images API,
  /v1/images/generations and /v1/images/edits. An edit takes up to ten pictures and an optional
  mask, outside which the picture comes back exactly as it was; `background: transparent`, png,
  jpeg and webp output, `n` pictures from one prompt, streamed previews (`partial_images`), and
  vLLM-Omni's seed, negative_prompt with true_cfg_scale, num_inference_steps, width and height.
  arch/qwenimage21 serves the diffusers pipeline directory, converted with
  data/recipes/qwen-image-2.1-fp8.recipe (block fp8) or qwen-image-2.1-bf16.recipe.
  deploy/compose/qwen-image-2.1.yaml and qwen-image-2.1-turbo.yaml serve the fp8 containers on
  two cards. Two R9700s make a 2048x2048 picture in 61 s at the base model's 40 steps and in
  13 s with Turbo (56 and 12 s with --tp-wire wht6), a 1024x1024 one in 6.0 and 2.6 s. The
  models are under Qwen's research license, which is non-commercial
- an image generator is a program kind of its own (core/gen): an architecture declares its
  conditioning, denoising and decoding passes, and the driver runs the schedule, the pictures of
  a batch and the conditioning cache. An image model's /v1/models entry is its generator's name
  (qwen-image-2.1, qwen-image-2.1-turbo), and its capabilities and startup banner list only the
  images endpoints
- the tiled prefill GEMMs run their tiles in groups of activation bands, 16 for fp8 and 8 for
  bf16, so an operand larger than the 64 MB cache is read once a group instead of once a band. A
  bf16 GEMM with more than 64 MB of weight runs up to twice as fast
- fixed: a second lane opened in the middle of a step started beside work lane 0 had not
  finished. Gemma 4 26B-A4B opens its lane that way, so its first step after startup could read
  rows not yet written
- startup no longer warns about --checkpoint-slots when it was not passed, nor about an expert
  floor on a model with no experts
- the image's FFmpeg writes png, jpeg and webp (libwebp)
- for out-of-tree plugins: RAD_ABI_VERSION is 16. The op vocabulary gains the image generator's
  ops (conv2d_nhwc, ln_mod, ln_mod_quant_fp8, flow_euler, attn_prefix_self and others; docs/OPS.md,
  "Image generation"), and all_reduce takes an optional `overlap`. Plugins built against 1.5.0
  must be rebuilt
This commit is contained in:
Deadcode committed 2026-10-14 14:03:59 +02:00
1 parent b93b531f63
commit b068190326
66 files changed
+9035 -87

No files matched your search

+1 -1
View File
@@ -3,7 +3,7 @@
#
# Sources are globbed per subdirectory with CONFIGURE_DEPENDS so that adding a file to a component
# does not mean editing a file another component owns. Re-run cmake if a new file does not appear.
set(RAD_CORE_DIRS util device plugin build runtime mem sched place sample text server format mm diag)
set(RAD_CORE_DIRS util device plugin build runtime mem sched place sample text server format mm diag gen)
set(RAD_CORE_SRC "")
foreach(d ${RAD_CORE_DIRS})
+1
View File
@@ -137,6 +137,7 @@ public:
int declare_drafter(const RadDrafterDecl* d);
int drafter_shared_kv(int pos_offset);
int declare_encoder(const RadEncoderDecl* d);
int declare_generator(const RadGeneratorDecl* d);
void note_v (const char* f, va_list ap);
/* The buffer operands of an op.
+114
View File
@@ -1067,6 +1067,11 @@ int Builder::declare_logits(rad_buf b) {
prog_.buffers[prog_.pooled_buf].name.c_str());
return RAD_E_STATE;
}
if (prog_.generator.layout != 0) {
err(RAD_E_STATE, "declare_logits: this program already declared the image generator '%s'",
prog_.gen_str.name.c_str());
return RAD_E_STATE;
}
prog_.logits_buf = b;
return RAD_OK;
}
@@ -1093,6 +1098,11 @@ int Builder::declare_pooled(rad_buf b) {
prog_.buffers[prog_.logits_buf].name.c_str());
return RAD_E_STATE;
}
if (prog_.generator.layout != 0) {
err(RAD_E_STATE, "declare_pooled: this program already declared the image generator '%s'",
prog_.gen_str.name.c_str());
return RAD_E_STATE;
}
const RadBufDecl& d = prog_.buffers[b].decl;
if (d.dtype != RAD_F32 || d.domain != RAD_DOMAIN_DEVICE || d.rank != 2 ||
d.shape[0] < prog_.ctx.max_seqs || d.shape[1] <= 0) {
@@ -1173,6 +1183,105 @@ int Builder::declare_encoder(const RadEncoderDecl* d) {
return RAD_OK;
}
/* WHAT THE GENERATOR IS. Checked whole here: a generator's every request runs all three of its
* passes, so a declaration the core cannot drive fails the first request rather than a rare one,
* and the first request is the wrong place to learn that the plugin sized its image buffer for a
* smaller picture than it says it makes. The strings are copied: the plugin's storage is not the
* Program's, and the Program outlives a declare. */
int Builder::declare_generator(const RadGeneratorDecl* d) {
if (finished_) { err(RAD_E_STATE, "declare_generator after declare finished"); return RAD_E_STATE; }
if (!d) { err(RAD_E_INVAL, "declare_generator: null declaration"); return RAD_E_INVAL; }
const char* nm = d->name && *d->name ? d->name : "(unnamed)";
if (prog_.generator.layout != 0) {
err(RAD_E_STATE, "declare_generator: '%s' was already declared; '%s' is a second one",
prog_.gen_str.name.c_str(), nm);
return RAD_E_STATE;
}
if (prog_.logits_buf != RAD_NULL_HANDLE || prog_.pooled_buf != RAD_NULL_HANDLE) {
err(RAD_E_STATE, "declare_generator '%s': this program already declared %s; a program "
"generates text, embeds or makes images -- one of the three", nm,
prog_.logits_buf != RAD_NULL_HANDLE ? "logits" : "a pooled output");
return RAD_E_STATE;
}
if (d->layout != RAD_GEN_LAYOUT_JOINT_GRID) {
err(RAD_E_INVAL, "declare_generator '%s': layout %d is not one this engine builds", nm,
(int)d->layout);
return RAD_E_INVAL;
}
auto has = [](const char* t, const char* what) { return t && std::strstr(t, what); };
if (!has(d->tmpl_text, "{prompt}") || !has(d->tmpl_edit, "{prompt}") ||
!has(d->tmpl_edit, "{images}") || !has(d->tmpl_image, "{image}")) {
err(RAD_E_INVAL, "declare_generator '%s': tmpl_text needs {prompt}, tmpl_edit {images} and "
"{prompt}, and tmpl_image {image}, where the picture's tokens go", nm);
return RAD_E_INVAL;
}
if (d->latent_channels <= 0 || d->latent_scale <= 0 || d->size_multiple <= 0 ||
d->size_multiple % d->latent_scale != 0 || d->pixel_channels <= 0 ||
d->pixel_channels > 4 || d->slot_rows <= 0 || d->max_tokens <= 0 || d->max_refs < 0 ||
d->ref_area <= 0 || d->default_width <= 0 || d->default_height <= 0 ||
d->default_width % d->size_multiple != 0 || d->default_height % d->size_multiple != 0 ||
(d->default_width / d->latent_scale) * (d->default_height / d->latent_scale) > d->max_tokens ||
d->max_lanes <= 0) {
err(RAD_E_INVAL, "declare_generator '%s': a geometry field is out of range (latent %lld x "
"%lld px, multiple %lld, %lld channels, slot rows %lld, max %lld tokens, "
"default %lldx%lld, %lld lanes)", nm, (long long)d->latent_channels,
(long long)d->latent_scale, (long long)d->size_multiple, (long long)d->pixel_channels,
(long long)d->slot_rows, (long long)d->max_tokens, (long long)d->default_width,
(long long)d->default_height, (long long)d->max_lanes);
return RAD_E_INVAL;
}
if (d->n_sigmas < 0 || (d->n_sigmas > 0 && !d->sigmas) ||
(d->n_sigmas == 0 && d->default_steps <= 0) || !(d->default_cfg >= 1.0) ||
(d->dyn_shift && (d->max_seq <= d->base_seq || d->base_seq <= 0)) ||
(!d->dyn_shift && !(d->shift > 0)) || d->shift_terminal < 0 || d->shift_terminal >= 1) {
err(RAD_E_INVAL, "declare_generator '%s': the sampler is incomplete (%d fixed sigmas, %lld "
"default steps, shift %g, dynamic %d over %lld..%lld, terminal %g, "
"guidance %g)", nm, (int)d->n_sigmas, (long long)d->default_steps,
d->shift, (int)d->dyn_shift, (long long)d->base_seq, (long long)d->max_seq,
d->shift_terminal, d->default_cfg);
return RAD_E_INVAL;
}
for (int i = 0; i < d->n_sigmas; ++i)
if (!(d->sigmas[i] > 0.0 && d->sigmas[i] <= 1.0) ||
(i > 0 && !(d->sigmas[i] < d->sigmas[i - 1]))) {
err(RAD_E_INVAL, "declare_generator '%s': fixed sigma %d (%g) is not in (0, 1] below "
"the one before it", nm, i, d->sigmas[i]);
return RAD_E_INVAL;
}
if (d->image_out == RAD_NULL_HANDLE || (size_t)d->image_out >= prog_.buffers.size()) {
err(RAD_E_INVAL, "declare_generator '%s': image_out %u is not a declared buffer", nm,
(unsigned)d->image_out);
return RAD_E_INVAL;
}
const RadBufDecl& ob = prog_.buffers[d->image_out].decl;
int64_t numel = 1;
for (uint32_t i = 0; i < ob.rank; ++i) numel *= ob.shape[i];
const int64_t px = d->max_tokens * d->latent_scale * d->latent_scale;
if (ob.dtype != RAD_U8 || ob.domain != RAD_DOMAIN_DEVICE || numel < px * d->pixel_channels) {
err(RAD_E_INVAL, "declare_generator '%s': image_out '%s' must be a device u8 buffer of at "
"least %lld x %lld -- the largest image", nm,
prog_.buffers[d->image_out].name.c_str(), (long long)px, (long long)d->pixel_channels);
return RAD_E_INVAL;
}
Program::GenStrings& g = prog_.gen_str;
g.name = nm;
g.tmpl_text = d->tmpl_text;
g.tmpl_edit = d->tmpl_edit;
g.tmpl_image = d->tmpl_image;
g.tmpl_image_sep = d->tmpl_image_sep ? d->tmpl_image_sep : "";
g.drop_prefix = d->drop_prefix ? d->drop_prefix : "";
g.tmpl_transparent = d->tmpl_transparent ? d->tmpl_transparent : "";
g.sigmas.assign(d->sigmas, d->sigmas + d->n_sigmas);
prog_.generator = *d;
/* The Program is moved after declare, and a pointer into a moved string is a pointer into the
* old one's storage: nothing here may be read through the decl, only through gen_str. */
RadGeneratorDecl& c = prog_.generator;
c.name = c.tmpl_text = c.tmpl_edit = c.tmpl_image = c.tmpl_image_sep = nullptr;
c.drop_prefix = c.tmpl_transparent = nullptr;
c.sigmas = nullptr;
return RAD_OK;
}
/* WHAT THE DRAFT HEAD IS. Every field is checked here rather than at the first draft pass: a
* drafter is exercised only once a request is speculating, so a decl that is wrong in a way the
* engine cannot act on would otherwise surface as acceptance that is quietly zero.
@@ -1822,6 +1931,11 @@ int rad_declare_encoder(RadBuilder* b, const RadEncoderDecl* d) {
return B(b)->declare_encoder(d);
}
int rad_declare_generator(RadBuilder* b, const RadGeneratorDecl* d) {
if (!b) return RAD_E_INVAL;
return B(b)->declare_generator(d);
}
void rad_note(RadBuilder* b, const char* f, ...) {
if (!b) return;
va_list ap;
+3 -3
View File
@@ -386,9 +386,9 @@ int rad_tools_declare(const LoadedPlugins& lp, const RadModelMeta& meta, const R
* the same resolution as the plugin's. A sampler op that does not resolve is deliberately NOT
* a declare failure -- a deployment that never sends `typical_p` does not need a typical
* kernel -- so this returning negative means something structural, not a miss. */
/* NOT FOR AN EMBEDDING PROGRAM (rad_declare_pooled): it samples nothing, so a sampler chain
* in it would be ops and buffers no step ever issues. */
if (also && b.program().pooled_buf == RAD_NULL_HANDLE) {
/* NOT FOR AN EMBEDDING PROGRAM (rad_declare_pooled) OR AN IMAGE GENERATOR: neither samples a
* token, so a sampler chain in it would be ops and buffers no step ever issues. */
if (also && b.program().pooled_buf == RAD_NULL_HANDLE && !b.program().is_generator()) {
/* THE WIDTH THE PLUGIN ACTUALLY DECLARED, handed over rather than re-derived. The sampler
* needs to know how much vocabulary THIS RANK produces, and the one place that is a fact
* is the logits buffer the plugin just named. Computing it a second time from n_vocab and
+105 -6
View File
@@ -5,6 +5,7 @@
* engine_priv.h for what the four share.
*/
#include "engine_priv.h"
#include "gen/driver.h"
#include "kld.h"
#include "mm/processor.h"
@@ -321,7 +322,7 @@ void Engine::rank_loop(int index) {
/* This rank's view of the step: the same numbers, pointed at this card's staging.
* The upload that filled it was issued on THIS stream, so the ordering is an
* ordinary same-stream dependency and no cross-rank fence is needed. */
const RadBatch* mine = sched_.batch_for(index);
const RadBatch* mine = gen_ ? gen_->batch_for(index) : sched_.batch_for(index);
if (!mine) {
RAD_ERR("rank %d: the builder has no batch for this rank", index);
step_status_.store(RAD_E_STATE, std::memory_order_release);
@@ -1596,12 +1597,30 @@ int Engine::serve() {
return RAD_E_STATE;
}
embedding_ = ranks_[0]->program.pooled_buf != RAD_NULL_HANDLE;
if (ranks_[0]->program.logits_buf == RAD_NULL_HANDLE && !embedding_) {
RAD_ERR("the '%s' plugin declared no logits buffer (rad_declare_logits) and no pooled "
"output (rad_declare_pooled), so a step produces nothing anyone can read. An "
"encoder-only plugin cannot serve.", plugins_.arch_plugin.c_str());
const bool generator = ranks_[0]->program.is_generator();
if (ranks_[0]->program.logits_buf == RAD_NULL_HANDLE && !embedding_ && !generator) {
RAD_ERR("the '%s' plugin declared no logits buffer (rad_declare_logits), no pooled output "
"(rad_declare_pooled) and no image generator (rad_declare_generator), so a step "
"produces nothing anyone can read. An encoder-only plugin cannot serve.",
plugins_.arch_plugin.c_str());
return RAD_E_UNSUPPORTED;
}
if (generator) {
if (cfg_.kld() || cfg_.n_spec > 0) {
RAD_ERR("the '%s' plugin makes images: --kld and speculative decoding have no tokens to "
"work on", plugins_.arch_plugin.c_str());
return RAD_E_UNSUPPORTED;
}
for (size_t i = 1; i < ranks_.size(); ++i)
if (!ranks_[i]->program.is_generator()) {
RAD_ERR("rank %zu declared no image generator and rank 0 did", i);
return RAD_E_STATE;
}
cfg_.prefix_cache = false;
prefix_off_why_ = "an image generator: a conditioning is read by its own request's images "
"and by nothing after them";
decide("--no-prefix-cache", "prefix caching off", prefix_off_why_);
}
if (embedding_) {
if (cfg_.kld() || cfg_.n_spec > 0) {
RAD_ERR("the '%s' plugin is an embedding model: it generates nothing, so --kld and "
@@ -1747,6 +1766,16 @@ int Engine::serve() {
rio.reserve(ranks_.size());
for (auto& rk : ranks_)
rio.push_back({ rk->device, rk->ctx.stream(), &rk->program });
if (generator) {
/* THE GENERATOR'S DRIVER IN PLACE OF THE SCHEDULER: the scheduler is never initialised,
* so its step staging -- sized for token steps the generator never runs -- is never
* allocated, and nothing calls it. */
std::vector<gen::Driver::RankIO> gio;
for (auto& rk : ranks_) gio.push_back({ rk->device, rk->ctx.stream() });
gen_ = std::make_unique<gen::Driver>();
RAD_TRY(gen_->init(ranks_[0]->program, cfg_, kv_iface_.get(), gio));
RAD_TRY(rad_dev_set(ranks_[0]->device));
} else
RAD_TRY(sched_.init(ranks_[0]->program, cfg_, kv_iface_.get(), pc_iface_.get(), rio, &geo_));
/* THE SMALLEST STEP THE PREFILL STAGER OVERLAPS. A prefill chunk the scheduler holds back for
* other work in the step (--busy-prefill-chunk) is kept at or above it: under it every routed
@@ -1769,7 +1798,7 @@ int Engine::serve() {
rank_threads_.clear();
for (int i = 0; i < cfg_.tp; ++i) rank_threads_.emplace_back([this, i] { rank_loop(i); });
std::thread stepper([this] { step_loop(); });
std::thread stepper([this] { if (gen_) gen_loop(); else step_loop(); });
if (cfg_.kld()) print_startup_report(RAD_OK);
int s = cfg_.kld() ? run_kld() : run_server();
@@ -2290,6 +2319,8 @@ int Engine::run_server() {
chat_bridge.init(*vocab_, declared_format, plugins_.arch_plugin) >= 0 &&
chat_bridge.ready())
embed_info.tpl = &chat_bridge;
} else if (gen_) {
/* An image model's template is its conditioning network's; nothing is served as chat. */
} else if (vocab_ && !vocab_->chat_template().empty() &&
chat_bridge.init(*vocab_, declared_format, plugins_.arch_plugin) >= 0 &&
chat_bridge.ready()) {
@@ -2301,6 +2332,7 @@ int Engine::run_server() {
server::ServerOptions o{};
o.embedding_model = embedding_;
o.image_model = gen_ != nullptr;
o.decision_type = rad_meta_gets(&meta_, "decision.type", "");
o.model_id = !cfg_.served_model_name.empty() ? cfg_.served_model_name
: meta_.name && *meta_.name ? meta_.name : "radiance";
@@ -2536,6 +2568,68 @@ int Engine::run_server() {
d.mm = mm_bridge.get();
}
/* AN IMAGE GENERATOR'S ENDPOINTS: the driver's queue, the model's declared prompts and sizes,
* and the processor for the conditioning network's view of a reference picture. */
struct ImageBridge final : server::IImageGen {
gen::Driver* drv = nullptr;
const mm::Processor* proc = nullptr;
server::ImageGenInfo inf;
const server::ImageGenInfo& info() const override { return inf; }
int submit(std::unique_ptr<gen::Request> r, std::string* why) override {
return drv->submit(std::move(r), why);
}
int picture(const mm::Frame& f, std::shared_ptr<mm::Item>* out, std::string* why) override {
if (!proc) {
if (why) *why = "this model reads no pictures";
return RAD_E_UNSUPPORTED;
}
return proc->image_from(f, out, why);
}
int64_t queued() const override { return drv->queued(); }
int64_t running() const override { return drv->running(); }
} image_bridge;
if (gen_) {
const Program& pg = ranks_[0]->program;
const RadGeneratorDecl& gd = pg.generator;
server::ImageGenInfo& in = image_bridge.inf;
in.name = pg.gen_str.name;
in.tmpl_text = pg.gen_str.tmpl_text;
in.tmpl_edit = pg.gen_str.tmpl_edit;
in.tmpl_image = pg.gen_str.tmpl_image;
in.tmpl_image_sep = pg.gen_str.tmpl_image_sep;
in.drop_prefix = pg.gen_str.drop_prefix;
in.tmpl_transparent = pg.gen_str.tmpl_transparent;
in.latent_scale = gd.latent_scale;
in.size_multiple = gd.size_multiple;
in.pixel_channels = gd.pixel_channels;
in.max_tokens = gd.max_tokens;
/* Edits need the conditioning network to read pictures. */
in.max_refs = mm_proc ? gd.max_refs : 0;
in.ref_area = gd.ref_area;
in.default_width = gd.default_width;
in.default_height = gd.default_height;
in.default_steps = gd.default_steps;
in.max_lanes = gd.max_lanes;
in.max_cond_tokens = gen_->max_cond_tokens();
in.fixed_schedule = !pg.gen_str.sigmas.empty();
in.fixed_steps = (int64_t)pg.gen_str.sigmas.size();
in.default_cfg = gd.default_cfg;
image_bridge.drv = gen_.get();
image_bridge.proc = mm_proc.get();
d.images = &image_bridge;
/* The model a client lists and names is the generator's own (qwen-image-2.1), not the
* architecture a diffusers pipeline's container is named after. */
if (cfg_.served_model_name.empty() && !in.name.empty()) {
o.model_id = in.name;
decide("--served-model-name", o.model_id, "an image generator: its own name");
}
RAD_INFO("images: '%s', %lldx%lld by default, up to %lld latent tokens, %lld picture(s) an "
"edit, %s", in.name.c_str(), (long long)in.default_width,
(long long)in.default_height, (long long)in.max_tokens, (long long)in.max_refs,
in.fixed_schedule ? (std::to_string(in.fixed_steps) + " fixed steps").c_str()
: (std::to_string(in.default_steps) + " steps by default").c_str());
}
if (encd.modalities == 0 && aend.modalities == 0 && cfg_.media_flags_set())
RAD_WARN("media: the media flags do nothing here -- this model %s",
cfg_.mm_max_patches == 0 ? "is served text only (--mm-max-patches 0)"
@@ -2595,6 +2689,11 @@ int Engine::run_server() {
if (embedding_)
RAD_INFO("serving on http://%s:%d (/v1/embeddings; completions and chat are 501)%s",
o.host.c_str(), o.port, o.api_key.empty() ? "" : " -- a bearer key is required");
else if (gen_)
RAD_INFO("serving on http://%s:%d (/v1/images/generations%s; completions and chat are "
"501)%s", o.host.c_str(), o.port,
d.images && d.images->info().max_refs > 0 ? " and /v1/images/edits" : "",
o.api_key.empty() ? "" : " -- a bearer key is required");
else
RAD_INFO("serving on http://%s:%d (/v1/completions%s)%s", o.host.c_str(), o.port,
d.chat ? "; /v1/chat/completions with tools and reasoning" : "; chat is 501",
+6
View File
@@ -42,6 +42,7 @@
namespace rad {
class Kld;
namespace gen { class Driver; }
struct TierPump;
struct TierJob;
struct StepSlot;
@@ -294,6 +295,11 @@ private:
float* pooled_host_ = nullptr;
int collect_pooled_issue(const RadBatch* b, StepOut& so);
int collect_pooled(const RadBatch* b, StepOut& so);
/* AN IMAGE GENERATOR (rad_declare_generator): the driver that turns its requests into passes
* and the loop that runs them, in place of the scheduler and the step loop (engine_gen.cpp).
* Null for every other program. */
std::unique_ptr<gen::Driver> gen_;
int gen_loop();
bool serial_drafting() const;
int advance_all(int mode, int round, bool from_proposal, int rows = -1);
int issue_serial_drafter(int step, const RadBatch* b, StepOut& so);
+48 -1
View File
@@ -8,6 +8,7 @@
* path and shares nothing with this but the Engine's fields. See engine_priv.h.
*/
#include "engine_priv.h"
#include "gen/driver.h"
#include "build/startup.h"
#include "build/rad_build.h"
@@ -979,6 +980,40 @@ int Engine::declare() {
"the KL mode: a prefix hit would start a document past positions the reference holds";
decide("--no-prefix-cache", "prefix caching off", prefix_off_why_);
}
/* AN IMAGE GENERATOR SIZES THE STEP ITSELF (RadArchProbe::gen_rows): a denoise pass carries an
* image's every latent row at once -- twice with guidance -- and a conditioning pass encodes
* every reference picture a request may carry. What the operator named is kept; what they did
* not is the generator's. A generator samples no tokens, so it drafts none, and a conditioning
* is read only by its own request's images, so there is no prefix to cache. */
{
RadArchProbe pb{};
(void)rad_tools_probe(plugins_, meta_, &pb);
if (pb.gen_rows > 0) {
if (!cfg_.given.count("--max-num-batched-tokens")) {
cfg_.max_tok = pb.gen_rows;
decide("--max-num-batched-tokens", std::to_string(cfg_.max_tok),
"an image generator: a denoise pass carries the largest image's latent "
"rows twice (with guidance)");
}
if (!cfg_.given.count("--max-num-seqs")) {
cfg_.max_seqs = 16;
decide("--max-num-seqs", "16", "an image generator: images in one pass");
}
if (!cfg_.given.count("--max-model-len") && cfg_.max_ctx == 0) {
cfg_.max_ctx = pb.gen_rows;
decide("--max-model-len", std::to_string(cfg_.max_ctx),
"an image generator: the longest conditioning, a prompt and its pictures, "
"as the generator's rows");
}
if (cfg_.mm_max_patches < 0 && pb.gen_patches > 0) {
cfg_.mm_max_patches = pb.gen_patches;
decide("--mm-max-patches", std::to_string(cfg_.mm_max_patches),
"an image generator: every reference picture of a request at once");
}
if (cfg_.n_spec < 0) cfg_.n_spec = 0;
cfg_.prefix_cache = false;
}
}
if (cfg_.n_spec < 0) {
RadArchProbe pb{};
(void)rad_tools_probe(plugins_, meta_, &pb);
@@ -1381,7 +1416,8 @@ int Engine::plan() {
const int64_t w = probe.state_index_width((int32_t)i);
if (w > 0) kg.g[i].sidx_width = w;
}
f.staging = BatchBuilder::device_bytes(r->program, cfg_, kg);
f.staging = r->program.is_generator() ? gen::Driver::device_bytes(r->program, cfg_)
: BatchBuilder::device_bytes(r->program, cfg_, kg);
if (f.staging < 0) return RAD_E_INVAL;
late_step_bytes_ = std::max(late_step_bytes_, f.staging);
int64_t lazy = r->program.scratch_regions > 1 ? f.queue_bytes : 0;
@@ -3167,6 +3203,17 @@ int Engine::configure_kv() {
* in vram_budget.cpp says it.) What is never acceptable is a pool that cannot
* hold ONE max-length sequence:
* that request is accepted by the API and can never complete, whatever the load. */
/* An image generator's sequence is a conditioning, and its driver refuses one the
* cache can never hold by name at admission; the limit is the operator's to know,
* in its own terms, with nothing about experts the model does not have. */
if (ranks_[0]->program.is_generator()) {
RAD_WARN("kv group '%s' holds %lld rows: a conditioning longer than that -- a "
"prompt with its pictures, up to %lld rows -- is refused. A picture "
"costs a latent row per 16x16 pixels of the reference area; more ranks "
"give the cache more room.",
p->name.c_str(), (long long)cap, (long long)want);
continue;
}
RAD_WARN("kv group '%s' holds %lld tokens but the context limit is %lld: ONE request "
"longer than %lld tokens is accepted by the API and then refused as too "
"large to ever fit -- this is a hard limit, not a backing ratio. Give the "
+72
View File
@@ -0,0 +1,72 @@
/* engine_gen.cpp -- the image generator's loop: the driver's passes (core/gen/driver.h) run on the
* ranks the way the step loop runs token steps, one at a time and each drained before the next.
*
* WHY EACH PASS IS DRAINED. A generator pass is tens to thousands of milliseconds of device work,
* and what decides the next one -- which image finished, which preview a step marked -- is the
* driver's bookkeeping of the pass just run, not anything the card computes. Waiting for the card
* between passes costs the few microseconds the host takes to build the next one; issuing ahead
* would need a second staging region and a commit protocol, for nothing a client could measure.
*/
#include "engine_priv.h"
#include "gen/driver.h"
#include <chrono>
#include <thread>
namespace rad {
int Engine::gen_loop() {
if (rad_dev_set(ranks_[0]->device) < 0)
RAD_ERR("image generator loop: could not bind rank 0's device");
int step = 0, idle = 0;
const rad_buf img = ranks_[0]->program.generator.image_out;
while (!stopping_.load(std::memory_order_acquire)) {
const RadBatch* b = gen_->next(step);
if (!b) {
step_batch_.store(nullptr, std::memory_order_release);
if (idle < 200) ++idle;
std::this_thread::sleep_for(std::chrono::microseconds(idle * 50));
continue;
}
idle = 0;
if (const int ps = prepare_release(b); ps < 0) {
gen_->shutdown("the engine stopped on an error and is not serving", ps);
return fail_loop(ps);
}
issue_what_.store(kIssueModel, std::memory_order_release);
step_batch_.store(b, std::memory_order_release);
barrier_->arrive_and_wait(); /* release the ranks */
barrier_->arrive_and_wait(); /* wait for them */
int st = step_status_.load(std::memory_order_acquire);
if (st < 0) {
RAD_ERR("generator pass %d failed: %s -- the engine cannot continue", step,
rad_strerror(st));
gen_->shutdown("the engine stopped on an error and is not serving", st);
return fail_loop(st);
}
/* A DECODE PASS'S IMAGE, behind it on rank 0's stream: every rank decodes the same pixels. */
if (const int64_t n = gen_->decode_bytes(); n > 0) {
const void* src = ranks_[0]->ctx.buf_ptr(img);
if (!src) {
RAD_ERR("the generator's image buffer was declared but never planned");
gen_->shutdown("the engine stopped on an error and is not serving", RAD_E_STATE);
return fail_loop(RAD_E_STATE);
}
st = rad_memcpy_async(gen_->host_image(), src, n, ranks_[0]->ctx.stream());
}
for (auto& rk : ranks_)
if (st >= 0) st = rad_stream_sync(rk->ctx.stream());
if (st < 0) {
RAD_ERR("generator pass %d: the device failed: %s", step, rad_strerror(st));
gen_->shutdown("the engine stopped on an error and is not serving", st);
return fail_loop(st);
}
if ((int)log_level() >= (int)Log::Trace)
dump_buffers(ranks_[0]->ctx, step, std::getenv("RADIANCE_DUMP_BUF"));
gen_->done();
++step;
}
return RAD_OK;
}
} /* namespace rad */
+94
View File
@@ -5,6 +5,7 @@
#include <nlohmann/json.hpp>
#include <algorithm>
#include <cctype>
#include <cstdio>
#include <cstring>
#include <fstream>
@@ -76,6 +77,7 @@ static void flatten_json(const nlohmann::json& j, const std::string& prefix, Met
if (e.is_number_integer()) s += fmt("%lld", (long long)e.get<int64_t>());
else if (e.is_number()) s += fmt("%.17g", e.get<double>());
else if (e.is_string()) s += e.get<std::string>();
else if (e.is_boolean()) s += e.get<bool>() ? "1" : "0";
else { ok = false; break; }
}
if (ok) out->kv(key, s);
@@ -480,6 +482,95 @@ int shard_list(const std::string& dir, const std::string& index, bool index_give
} /* namespace */
/* A JSON file flattened under `prefix`; absent is not an error when `optional`. */
static int meta_merge_json_file(const std::string& path, const std::string& prefix, bool optional,
MetaOwn* out) {
std::ifstream f(path);
if (!f) {
if (optional) return RAD_OK;
RAD_ERR("%s: cannot read it", path.c_str());
return RAD_E_NOTFOUND;
}
nlohmann::json j;
try { f >> j; }
catch (const std::exception& e) { RAD_ERR("%s: %s", path.c_str(), e.what()); return RAD_E_FORMAT; }
if (!j.is_object()) {
RAD_ERR("%s: not a JSON object", path.c_str());
return RAD_E_FORMAT;
}
flatten_json(j, prefix, out);
return RAD_OK;
}
static bool path_exists(const std::string& p) { std::ifstream f(p); return (bool)f; }
/* A DIFFUSERS PIPELINE: model_index.json at the top and one folder a component, each with its own
* config and weights. It is read as ONE checkpoint, because the components are one model to the
* architecture plugin that serves them:
*
* text_encoder/ its config.json is the container's model config -- the typed dimensions and
* the bare keys -- and its tensors keep their names;
* transformer/ tensors under `transformer.`, config.json under `transformer.` keys;
* vae/ tensors under `vae.`, config.json under `vae.` keys;
* scheduler/ scheduler_config.json under `scheduler.` keys;
* processor/ (or tokenizer/) the tokenizer, the chat template and the preprocessor configs.
*
* model_index.json itself goes under `pipeline.` keys, and its `_class_name` names the
* architecture: `QwenImage21Pipeline` is `qwenimage21`. A component folder may be a link to
* another pipeline's (a distilled release sharing its base's text encoder). */
int Checkpoint::open_diffusers() {
kind_ = SafeT;
RAD_TRY(meta_merge_json_file(dir_ + "/model_index.json", "pipeline", false, &meta_));
const std::string te = dir_ + "/text_encoder";
if (path_exists(te + "/config.json")) {
std::vector<std::string> shards;
std::unordered_map<std::string, std::string> owner;
RAD_TRY(shard_list(te, te + "/model.safetensors.index.json", false, &shards, &owner));
for (const auto& sh : shards) RAD_TRY(add_shard(sh, "", owner.empty() ? nullptr : &owner));
RAD_TRY(meta_from_config_json(te, &meta_));
RAD_TRY(meta_merge_generation_config(te, &meta_));
}
for (const char* comp : { "transformer", "vae" }) {
const std::string d = dir_ + "/" + comp;
if (!path_exists(d + "/config.json")) continue;
const std::string idx = d + "/diffusion_pytorch_model.safetensors.index.json";
std::vector<std::string> shards;
std::unordered_map<std::string, std::string> owner;
if (path_exists(idx)) {
RAD_TRY(shard_list(d, idx, true, &shards, &owner));
} else {
shards.push_back(d + "/diffusion_pytorch_model.safetensors");
}
for (const auto& sh : shards)
RAD_TRY(add_shard(sh, std::string(comp) + ".", owner.empty() ? nullptr : &owner));
RAD_TRY(meta_merge_json_file(d + "/config.json", comp, false, &meta_));
}
RAD_TRY(meta_merge_json_file(dir_ + "/scheduler/scheduler_config.json", "scheduler", true,
&meta_));
for (const char* sub : { "processor", "tokenizer" }) {
const std::string d = dir_ + "/" + sub;
if (!path_exists(d + "/tokenizer.json")) continue;
tok_dir_ = d;
RAD_TRY(meta_merge_preprocessor_configs(d, &meta_));
break;
}
/* The architecture is the pipeline's, whatever the text encoder calls itself. */
if (const char* cn = meta_.get("pipeline._class_name")) {
std::string a = cn;
const std::string suf = "Pipeline";
if (a.size() > suf.size() && a.compare(a.size() - suf.size(), suf.size(), suf) == 0)
a.resize(a.size() - suf.size());
for (char& ch : a) ch = (char)std::tolower((unsigned char)ch);
meta_.arch = a;
}
if (tensors_.empty()) {
RAD_ERR("%s: a diffusers pipeline with no component weights", dir_.c_str());
return RAD_E_NOTFOUND;
}
meta_.finish();
return RAD_OK;
}
int Checkpoint::open_safetensors(const std::string& path) {
kind_ = SafeT;
/* One shard, an index, or the directory holding either: one namespace whichever it is. */
@@ -488,6 +579,9 @@ int Checkpoint::open_safetensors(const std::string& path) {
const bool is_index = path.size() > 10 && path.compare(path.size() - 10, 10, "index.json") == 0;
const bool is_file = path.size() > 12 &&
path.compare(path.size() - 12, 12, ".safetensors") == 0;
if (!is_file && !is_index && path_exists(dir_ + "/model_index.json") &&
!path_exists(dir_ + "/config.json"))
return open_diffusers();
if (is_file) {
shards.push_back(path);
} else {
+5 -1
View File
@@ -125,6 +125,9 @@ public:
GgufFile& gguf() { return gguf_; }
const std::string& path() const { return path_; }
const std::string& dir() const { return dir_; } /* where config.json and tokenizer.json sit */
/* Where tokenizer.json, tokenizer_config.json and the chat template sit: dir() for a model
* repository, the `processor/` (or `tokenizer/`) folder of a diffusers pipeline. */
const std::string& tok_dir() const { return tok_dir_.empty() ? dir_ : tok_dir_; }
MetaOwn& meta() { return meta_; }
const MetaOwn& meta() const { return meta_; }
@@ -162,11 +165,12 @@ private:
int add_shard(const std::string& p, const std::string& prefix = "",
const std::unordered_map<std::string, std::string>* owner = nullptr);
int open_safetensors(const std::string& path);
int open_diffusers();
int open_gguf(const std::string& path);
void detect_import();
enum Kind { None, Gguf, SafeT } kind_ = None;
std::string path_, dir_;
std::string path_, dir_, tok_dir_;
GgufFile gguf_;
MetaOwn meta_;
std::vector<std::unique_ptr<SafeTensorsFile>> shards_;
+916
View File
@@ -0,0 +1,916 @@
/* driver.cpp -- the image generator's pass driver (driver.h). */
#include "driver.h"
#include "sched/mem_iface.h"
#include <algorithm>
#include <cmath>
#include <cstring>
namespace rad {
namespace gen {
namespace {
constexpr int64_t kAlign = 256;
int64_t align_up(int64_t v) { return (v + kAlign - 1) / kAlign * kAlign; }
/* A reference picture's latent tokens at most: its area, a little over for the rounding of its
* sides to the size multiple. */
int64_t ref_tokens_max(const RadGeneratorDecl& d) {
const int64_t s2 = d.latent_scale * d.latent_scale;
return (d.ref_area + s2 - 1) / s2 * 11 / 10 + 64;
}
struct Sizes {
int64_t T = 0, S = 0, EP = 0, PD = 0, R = 0, P = 0, PX = 0, NT = 0, NB = 0;
};
Sizes sizes_of(const Program& prog, int64_t block_size) {
const RadGeneratorDecl& d = prog.generator;
Sizes z;
z.T = prog.ctx.max_tok;
z.S = prog.ctx.max_seqs;
z.EP = prog.encoder.modalities ? prog.ctx.max_enc_patches : 0;
z.PD = prog.encoder.modalities ? prog.encoder.patch_dim : 0;
z.R = d.max_refs;
z.P = z.T + z.R * ref_tokens_max(d);
const int64_t s2 = d.latent_scale * d.latent_scale;
z.PX = z.R * (ref_tokens_max(d) * s2) + d.max_tokens * s2;
z.NT = d.max_tokens;
z.NB = block_size > 0 ? (z.P + block_size - 1) / block_size : 0;
return z;
}
/* The regions, in order, and the total. One function for both the allocation and the budget's
* count of it, so the two cannot disagree. */
int64_t carve(const Sizes& z, int64_t pixel_ch, int64_t (*bytes)[2], int n) {
const int64_t I = 4, H = 2;
const int64_t rope_rows = std::max(z.P, z.T);
const int64_t want[][2] = {
{ 0, z.T * I }, /* R_TOK */
{ 0, z.T * I }, /* R_POS */
{ 0, 3 * z.T * I }, /* R_ROPE */
{ 0, (z.S + 1) * I }, /* R_CU */
{ 0, z.T * I }, /* R_MMROW */
{ 0, z.EP * z.PD * H }, /* R_ENCPIX */
{ 0, 4 * z.EP * I }, /* R_ENCCRD */
{ 0, (z.R + 2) * I }, /* R_ENCCU */
{ 0, z.P * I }, /* R_SRC */
{ 0, 3 * rope_rows * I }, /* R_GROPE */
{ 0, (12 * z.R + 24) * I }, /* R_SEG: offsets, {0, length} and start a segment, {0, tokens} a picture */
{ 0, z.P * I }, /* R_SLOT */
{ 0, z.PX * pixel_ch * H }, /* R_PX */
{ 0, z.NT * 4 }, /* R_MASK */
{ 0, z.S * 4 }, /* R_SIG */
{ 0, z.S * 4 }, /* R_SIGN */
{ 0, z.S * 4 }, /* R_CFG */
{ 0, z.S * I }, /* R_PAIR */
{ 0, z.S * I }, /* R_LANE */
{ 0, z.S * I }, /* R_FLAGS */
{ 0, 2 * z.S * 4 }, /* R_SEED */
{ 0, z.S * z.NB * I }, /* R_BT */
{ 0, z.S * I }, /* R_USED */
};
int64_t off = 0;
for (int r = 0; r < n; ++r) {
bytes[r][0] = off;
bytes[r][1] = want[r][1];
off = align_up(off + want[r][1]);
}
return off;
}
} /* namespace */
int64_t Driver::device_bytes(const Program& prog, const Config& cfg) {
(void)cfg;
if (!prog.is_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, prog.generator.pixel_channels, b, R_N);
}
int Driver::init(const Program& prog, const Config& cfg, IKVManager* kv,
const std::vector<RankIO>& ranks) {
(void)cfg;
fini();
if (!prog.is_generator()) return RAD_E_STATE;
decl_ = prog.generator;
fixed_ = prog.gen_str.sigmas;
kv_ = kv;
ranks_ = ranks;
/* ONE KV GROUP, PAGED: the conditioning's keys and values. A generator with no conditioning
* cache, or two, is not a shape this driver stages. Group handles start at 1 -- the program's
* group 0 is the null handle -- and the KV manager and a batch both index by handle. */
if (prog.kv_groups.size() != 2 || prog.kv_groups[1].decl.kind != RAD_KV_FULL ||
prog.kv_groups[1].block_size <= 0) {
RAD_ERR("image generator: the program declares %zu KV group(s); the driver stages exactly "
"one full-attention group, the conditioning'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_enc_ = z.EP;
patch_dim_ = z.PD;
max_rows_ = z.P;
max_px_ = z.PX;
max_blocks_ = z.NB;
int64_t b[R_N][2];
bytes_ = carve(z, decl_.pixel_channels, 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));
img_bytes_ = decl_.max_tokens * decl_.latent_scale * decl_.latent_scale * decl_.pixel_channels;
img_host_ = rad_dev_alloc(img_bytes_, RAD_MEM_HOST_PINNED);
if (!host_ || !img_host_) {
RAD_ERR("image generator: no pinned host memory for the pass staging (%lld + %lld bytes)",
(long long)bytes_, (long long)img_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("image 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{});
gout_.assign(ranks_.size(), RadGenBatch{});
kout_.assign(ranks_.size(), RadKVGroupBatch{});
lanes_.assign((size_t)decl_.max_lanes, Lane{});
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 Driver::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 (img_host_) rad_dev_free(img_host_, RAD_MEM_HOST_PINNED);
host_ = nullptr;
img_host_ = nullptr;
}
/* ================================================================== requests */
int Driver::submit(std::unique_ptr<Request> r, std::string* why) {
if (!r || !r->ticket) return RAD_E_INVAL;
const RadGeneratorDecl& d = decl_;
auto no = [&](const std::string& w) {
if (why) *why = w;
return RAD_E_INVAL;
};
if (r->width <= 0 || r->height <= 0 || r->width % d.size_multiple || r->height % d.size_multiple)
return no("the size must be whole multiples of " + std::to_string(d.size_multiple) +
" pixels");
const int64_t tokens = (int64_t)(r->width / d.latent_scale) * (r->height / d.latent_scale);
const int nb = r->has_neg ? 2 : 1;
if (tokens > d.max_tokens)
return no("the image is " + std::to_string(r->width) + "x" + std::to_string(r->height) +
"; the largest this model makes is " + std::to_string(d.max_tokens) +
" latent tokens (" + std::to_string(d.max_tokens * d.latent_scale * d.latent_scale) +
" pixels)");
if (tokens * nb > max_tok_)
return no("an image of this size with guidance needs " + std::to_string(tokens * nb) +
" rows a step and a step carries " + std::to_string(max_tok_) +
" (--max-num-batched-tokens)");
if (r->n < 1 || r->n > d.max_lanes)
return no("n must be 1.." + std::to_string(d.max_lanes));
if ((int64_t)r->refs.size() > d.max_refs)
return no("at most " + std::to_string(d.max_refs) + " pictures a request");
for (const Branch* b : { &r->pos, &r->neg }) {
if (b == &r->neg && !r->has_neg) continue;
if ((int64_t)b->tokens.size() > max_tok_)
return no("the prompt is " + std::to_string(b->tokens.size()) + " tokens with its "
"pictures; a conditioning pass carries " + std::to_string(max_tok_));
int64_t np = 0;
if (b->media)
for (const mm::Placed& p : b->media->items) np += p.item ? p.item->n_patch : 0;
if (np > max_enc_)
return no("the pictures are " + std::to_string(np) + " patches together and a "
"conditioning pass encodes " + std::to_string(max_enc_) +
" (--mm-max-patches)");
}
int64_t px = 0;
for (const Pixels& p : r->refs) px += (int64_t)p.w * p.h;
if (r->inpaint) px += (int64_t)r->inp_src.w * r->inp_src.h;
if (px > max_px_) return no("the pictures are larger than the staging holds");
if (r->inpaint && ((int64_t)r->inp_mask.size() != tokens || r->inp_src.w != r->width ||
r->inp_src.h != r->height))
return no("the mask's picture is not at the size being made");
if (r->previews < 0 || r->previews > 3) return no("partial_images must be 0..3");
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->n_branch = nb;
j->tokens = tokens;
j->h_lat = (int32_t)(r->height / d.latent_scale);
j->w_lat = (int32_t)(r->width / d.latent_scale);
j->req = std::move(r);
jobs_.push_back(std::move(j));
return RAD_OK;
}
void Driver::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 Driver::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 Driver::running() const {
std::lock_guard<std::mutex> lk(mu_);
int64_t n = 0;
for (const auto& j : jobs_) if (j->admitted) ++n;
return n;
}
bool Driver::busy() const {
std::lock_guard<std::mutex> lk(mu_);
return !jobs_.empty();
}
Driver::Job* Driver::job_locked(uint64_t id) {
for (auto& j : jobs_) if (j->id == id) return j.get();
return nullptr;
}
void Driver::release_locked(Job& j) {
for (int b = 0; b < 2; ++b)
if (j.cond[b].have_kv) {
kv_->free_sequence(j.cond[b].seq);
j.cond[b].have_kv = false;
}
for (int32_t l : j.lanes) {
lanes_[(size_t)l] = Lane{};
free_lanes_.push_back(l);
}
j.lanes.clear();
}
void Driver::fail_locked(Job& j, int status, const std::string& why) {
j.failed = true;
j.req->ticket->finish(status, why);
}
/* IN ORDER, AND A REQUEST THAT DOES NOT FIT STOPS THE ONES BEHIND IT. */
int Driver::admit_locked() {
for (auto& jp : jobs_) {
Job& j = *jp;
if (j.admitted || j.failed) continue;
Request& r = *j.req;
if ((int64_t)free_lanes_.size() < r.n) break;
/* The sequences, once: their length is what the KV has to hold. */
if (j.cond[0].lay.rows == 0) {
j.ref_hw.clear();
for (const Pixels& p : r.refs)
j.ref_hw.push_back({ (int32_t)(p.h / decl_.latent_scale),
(int32_t)(p.w / decl_.latent_scale) });
for (int b = 0; b < j.n_branch; ++b) {
std::string why;
const int s = build_layout(b ? r.neg : r.pos, decl_.slot_rows, j.ref_hw,
&j.cond[b].lay, &why);
if (s < 0) { fail_locked(j, s, why); break; }
if (j.cond[b].lay.rows > max_rows_) {
fail_locked(j, RAD_E_INVAL, "the conditioning is " +
std::to_string(j.cond[b].lay.rows) + " rows; the driver stages " +
std::to_string(max_rows_));
break;
}
}
if (j.failed) continue;
}
bool ok = true;
for (int b = 0; b < j.n_branch && ok; ++b) {
Cond& c = j.cond[b];
if (c.have_kv) continue;
if (!kv_->can_ever_fit(c.lay.rows)) {
fail_locked(j, RAD_E_INVAL, "the conditioning's " + std::to_string(c.lay.rows) +
" rows do not fit the KV cache even when it is empty");
ok = false;
break;
}
c.seq = ((uint64_t)1 << 62) | next_seq_++;
if (kv_->add_sequence(c.seq) < 0) { ok = false; break; }
const int s = kv_->ensure(c.seq, c.lay.rows);
if (s < 0) {
kv_->free_sequence(c.seq);
ok = false;
break;
}
c.have_kv = true;
}
if (j.failed) continue;
if (!ok) {
/* The KV is short now: give back what this one took and wait. */
for (int b = 0; b < 2; ++b)
if (j.cond[b].have_kv) { kv_->free_sequence(j.cond[b].seq); j.cond[b].have_kv = false; }
break;
}
j.sigmas = schedule(decl_, fixed_, r.steps, j.tokens);
const int32_t n_steps = (int32_t)j.sigmas.size() - 1;
for (int b = 0; b < j.n_branch; ++b) {
Cond& c = j.cond[b];
c.rope_img.assign((size_t)(3 * j.tokens), 0);
image_rope(c.lay.next_pos, j.h_lat, j.w_lat, c.rope_img.data(), j.tokens);
}
for (int32_t i = 0; i < r.n; ++i) {
const int32_t l = free_lanes_.back();
free_lanes_.pop_back();
Lane& ln = lanes_[(size_t)l];
ln = Lane{};
ln.job = 0;
ln.job_id = j.id;
ln.index = i;
ln.seed = r.seed + (uint64_t)i;
for (int32_t k = 1; k <= r.previews; ++k) {
const int32_t at = (int32_t)((int64_t)n_steps * k / (r.previews + 1));
if (at >= 1 && at < n_steps &&
(ln.preview_at.empty() || ln.preview_at.back() != at))
ln.preview_at.push_back(at);
}
j.lanes.push_back(l);
}
r.ticket->steps = n_steps;
int64_t in_tok = (int64_t)r.pos.tokens.size();
if (r.has_neg) in_tok += (int64_t)r.neg.tokens.size();
r.ticket->in_tokens = in_tok;
r.ticket->out_tokens = j.tokens * r.n;
j.admitted = true;
}
return RAD_OK;
}
/* ================================================================== staging */
int Driver::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 Driver::finish_batches(int64_t n_tok, int64_t n_seq, int32_t max_q, int step) {
for (size_t r = 0; r < ranks_.size(); ++r) {
RadBatch& B = out_[r];
RadGenBatch& G = gout_[r];
RadKVGroupBatch& K = kout_[r];
const int ri = (int)r;
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.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);
B.q_lens = nullptr;
B.ctx_lens = nullptr;
B.n_seq_decode = 0;
B.n_tok_decode = 0;
B.max_q_len_prefill = max_q;
K.group = (rad_kvgroup)kv_group_;
K.slot_mapping = reg_[R_SLOT].used > 0 ? dptr<int32_t>(ri, R_SLOT) : nullptr;
K.block_table = dptr<int32_t>(ri, R_BT);
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;
B.gen_b = &G;
G.src = dptr<int32_t>(ri, R_SRC);
G.rope = dptr<int32_t>(ri, R_GROPE);
G.seg = dptr<int32_t>(ri, R_SEG);
G.seg_h = hptr<int32_t>(R_SEG);
G.slot_mapping = dptr<int32_t>(ri, R_SLOT);
G.px = dptr<uint16_t>(ri, R_PX);
G.inp_mask = dptr<float>(ri, R_MASK);
G.sigma = dptr<float>(ri, R_SIG);
G.sigma_next = dptr<float>(ri, R_SIGN);
G.cfg = dptr<float>(ri, R_CFG);
G.pair = dptr<int32_t>(ri, R_PAIR);
G.lane = dptr<int32_t>(ri, R_LANE);
G.lane_dh = hptr<int32_t>(R_LANE);
G.flags = dptr<int32_t>(ri, R_FLAGS);
G.seed = dptr<uint32_t>(ri, R_SEED);
}
}
/* ================================================================== the passes */
const RadBatch* Driver::next(int step) {
std::lock_guard<std::mutex> lk(mu_);
pass_ = Pass{};
dec_bytes_ = 0;
if (closed_) return nullptr;
/* What finished, failed or was given up on since the last pass leaves now: its KV and lanes
* go back before anything is admitted. Nothing is in flight -- next() runs between passes. */
for (auto it = jobs_.begin(); it != jobs_.end();) {
Job& j = **it;
const bool gone = j.failed || j.req->ticket->cancel.load(std::memory_order_acquire) ||
(j.admitted && j.images_done >= j.req->n);
if (!gone) { ++it; continue; }
if (j.req->ticket->cancel.load(std::memory_order_acquire) && !j.failed &&
j.images_done < j.req->n)
j.req->ticket->finish(RAD_E_CANCELLED, "the request was cancelled");
release_locked(j);
it = jobs_.erase(it);
}
admit_locked();
/* 1. A decode an image is owed. */
for (int32_t l = 0; l < (int32_t)lanes_.size(); ++l) {
Lane& ln = lanes_[(size_t)l];
if (ln.job < 0 || ln.finished) continue;
if (ln.preview_due) return build_decode(l, true, step);
if (ln.final_due) return build_decode(l, false, step);
}
/* 2. A conditioning an admitted request is owed. */
for (auto& jp : jobs_) {
Job& j = *jp;
if (!j.admitted || j.failed) continue;
for (int b = 0; b < j.n_branch; ++b)
if (!j.cond[b].encoded) return build_cond(j, b, step);
}
/* 3. A denoise step over what is in flight, oldest request first. */
std::vector<int32_t> take;
int64_t rows = 0, entries = 0;
for (auto& jp : jobs_) {
Job& j = *jp;
if (!j.admitted || j.failed) continue;
bool ready = true;
for (int b = 0; b < j.n_branch; ++b) ready = ready && j.cond[b].encoded;
if (!ready) continue;
const int32_t n_steps = (int32_t)j.sigmas.size() - 1;
for (int32_t l : j.lanes) {
const Lane& ln = lanes_[(size_t)l];
if (ln.finished || ln.final_due || ln.preview_due || ln.step >= n_steps) continue;
const int64_t need = j.tokens * j.n_branch;
if (rows + need > max_tok_ || entries + j.n_branch > max_seqs_) break;
rows += need;
entries += j.n_branch;
take.push_back(l);
}
}
if (take.empty()) return nullptr;
return build_denoise(take, step);
}
const RadBatch* Driver::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* Driver::build_cond(Job& j, int branch, int step) {
for (int g = 0; g < R_N; ++g) reg_[g].used = 0;
const Request& r = *j.req;
const Branch& br = branch ? r.neg : r.pos;
const Cond& c = j.cond[branch];
const int64_t T = (int64_t)br.tokens.size(), P = c.lay.rows;
int32_t* tok = hptr<int32_t>(R_TOK);
int32_t* pos = hptr<int32_t>(R_POS);
int32_t* rope = hptr<int32_t>(R_ROPE);
std::memcpy(tok, br.tokens.data(), (size_t)T * 4);
for (int64_t i = 0; i < T; ++i) pos[i] = (int32_t)i;
for (int64_t i = 0; i < T; ++i) {
int32_t p3[3] = { (int32_t)i, (int32_t)i, (int32_t)i };
if (br.media) br.media->rope.at(i, p3);
rope[i] = p3[0];
rope[T + i] = p3[1];
rope[2 * T + i] = p3[2];
}
int32_t* cu = hptr<int32_t>(R_CU);
cu[0] = 0;
cu[1] = (int32_t)T;
reg_[R_TOK].used = reg_[R_POS].used = T * 4;
reg_[R_ROPE].used = 3 * T * 4;
reg_[R_CU].used = 2 * 4;
/* The pictures, for the conditioning network's encoder: every item's patches in prompt order,
* one segment an item, and the prompt rows the encoder's output rows replace. */
int64_t n_patch = 0, n_seg = 0, n_mm = 0;
int32_t max_seg = 0;
if (br.media) {
uint16_t* pix = hptr<uint16_t>(R_ENCPIX);
int32_t* crd = hptr<int32_t>(R_ENCCRD);
int32_t* ecu = hptr<int32_t>(R_ENCCU);
int64_t total = 0;
for (const mm::Placed& p : br.media->items) total += p.item->n_patch;
std::vector<int64_t> row0;
int64_t rows_at = 0;
ecu[0] = 0;
std::vector<int32_t> tmp;
for (const mm::Placed& p : br.media->items) {
const mm::Item& it = *p.item;
std::memcpy(pix + n_patch * patch_dim_, it.pixels.data(),
(size_t)(it.n_patch * patch_dim_) * 2);
tmp.resize((size_t)(4 * it.n_patch));
it.coords(0, it.n_patch, tmp.data());
for (int cc = 0; cc < 4; ++cc)
std::memcpy(crd + cc * total + n_patch, tmp.data() + cc * it.n_patch,
(size_t)it.n_patch * 4);
for (int32_t s = 0; s < it.n_seg; ++s) {
const int64_t a = it.patch_at(s), e = it.patch_at(s + 1);
ecu[n_seg + 1] = (int32_t)(n_patch + e);
max_seg = std::max<int32_t>(max_seg, (int32_t)(e - a));
++n_seg;
}
row0.push_back(rows_at);
rows_at += it.n_rows();
n_patch += it.n_patch;
}
int32_t* mmr = hptr<int32_t>(R_MMROW);
for (const mm::RopeLayout::Run& run : br.media->rope.runs) {
const int64_t base = row0[(size_t)run.item] + run.row0;
(void)base;
for (int32_t k = 0; k < run.n; ++k) mmr[n_mm++] = run.tok + k;
}
reg_[R_ENCPIX].used = n_patch * patch_dim_ * 2;
reg_[R_ENCCRD].used = 4 * total * 4;
reg_[R_ENCCU].used = (n_seg + 1) * 4;
reg_[R_MMROW].used = n_mm * 4;
}
/* The generator's sequence, which the plugin runs a segment at a time: each segment's rotary
* positions as one dense [3, length] block, its own {0, length} and its first row. */
std::memcpy(hptr<int32_t>(R_SRC), c.lay.src.data(), (size_t)P * 4);
const int64_t nsg = (int64_t)c.lay.bidi.size();
int32_t* grope = hptr<int32_t>(R_GROPE);
int32_t* segp = hptr<int32_t>(R_SEG);
std::memcpy(segp, c.lay.seg.data(), (size_t)(nsg + 1) * 4);
for (int64_t s = 0; s < nsg; ++s) {
const int32_t a = c.lay.seg[(size_t)s], len = c.lay.seg[(size_t)s + 1] - a;
for (int cc = 0; cc < 3; ++cc)
std::memcpy(grope + 3 * (int64_t)a + cc * (int64_t)len,
&c.lay.rope[(size_t)(cc * P + a)], (size_t)len * 4);
segp[nsg + 1 + 2 * s] = 0;
segp[nsg + 1 + 2 * s + 1] = len;
segp[nsg + 1 + 2 * nsg + s] = a;
}
reg_[R_SRC].used = P * 4;
reg_[R_GROPE].used = 3 * P * 4;
reg_[R_SEG].used = (4 * nsg + 1) * 4;
const std::vector<int32_t>& bt = kv_->block_table(c.seq, kv_group_);
int32_t* slot = hptr<int32_t>(R_SLOT);
for (int64_t p = 0; p < P; ++p) {
const int64_t bi = p / block_size_;
slot[p] = bi < (int64_t)bt.size() ? (int32_t)(bt[(size_t)bi] * block_size_ + p % block_size_)
: -1;
}
reg_[R_SLOT].used = P * 4;
int32_t* btab = hptr<int32_t>(R_BT);
for (size_t i = 0; i < bt.size(); ++i) btab[i] = bt[i];
reg_[R_BT].used = (int64_t)bt.size() * 4;
hptr<int32_t>(R_USED)[0] = (int32_t)P;
reg_[R_USED].used = 4;
/* The pictures again, for the generator's own encoder, and with a mask the picture being
* repainted -- only the positive conditioning's pass writes the lanes. */
const int64_t ch = decl_.pixel_channels;
uint16_t* px = hptr<uint16_t>(R_PX);
std::vector<int32_t> pxh;
int64_t at = 0;
for (const Pixels& p : r.refs) {
std::memcpy(px + at * ch, p.bf16.data(), (size_t)((int64_t)p.w * p.h * ch) * 2);
pxh.insert(pxh.end(), { (int32_t)at, p.h, p.w });
at += (int64_t)p.w * p.h;
}
const bool inp = r.inpaint && branch == 0;
if (inp) {
const Pixels& p = r.inp_src;
std::memcpy(px + at * ch, p.bf16.data(), (size_t)((int64_t)p.w * p.h * ch) * 2);
pxh.insert(pxh.end(), { (int32_t)at, p.h, p.w });
at += (int64_t)p.w * p.h;
std::memcpy(hptr<float>(R_MASK), r.inp_mask.data(), r.inp_mask.size() * 4);
reg_[R_MASK].used = (int64_t)r.inp_mask.size() * 4;
}
reg_[R_PX].used = at * ch * 2;
/* Each picture's latent tokens as a cu pair, after the segments' arrays. */
const int64_t npx = (int64_t)pxh.size() / 3;
int32_t* pxcu = hptr<int32_t>(R_SEG) + 4 * nsg + 1;
for (int64_t b = 0; b < npx; ++b) {
pxcu[2 * b] = 0;
pxcu[2 * b + 1] = (pxh[(size_t)(3 * b + 1)] / (int32_t)decl_.latent_scale) *
(pxh[(size_t)(3 * b + 2)] / (int32_t)decl_.latent_scale);
}
reg_[R_SEG].used = (4 * nsg + 1 + 2 * npx) * 4;
/* The conditioning is modulated at t = 0. */
hptr<float>(R_SIG)[0] = 0.0f;
reg_[R_SIG].used = 4;
/* The host arrays the plugin reads on the host: the segments' kinds, the pixel blocks and the
* lanes. Kept here, in the driver, for the life of the pass. */
host_bidi_ = c.lay.bidi;
host_px_ = pxh;
host_lanes_ = inp ? j.lanes : std::vector<int32_t>{};
/* ...and the lanes on the device too: the repainted picture's latent and mask are copied into
* each of them by an op. */
if (!host_lanes_.empty()) {
std::memcpy(hptr<int32_t>(R_LANE), host_lanes_.data(), host_lanes_.size() * 4);
reg_[R_LANE].used = (int64_t)host_lanes_.size() * 4;
}
if (upload() < 0) return nullptr;
finish_batches(T, 1, (int32_t)T, step);
for (size_t rr = 0; rr < ranks_.size(); ++rr) {
RadBatch& B = out_[rr];
RadGenBatch& G = gout_[rr];
const int ri = (int)rr;
B.max_ctx_len = (int32_t)P;
B.rope_pos = dptr<int32_t>(ri, R_ROPE);
B.rope_mixed = br.media ? 1 : 0;
B.n_mm_rows = n_mm;
B.mm_rows = n_mm ? dptr<int32_t>(ri, R_MMROW) : nullptr;
B.mm_embd = nullptr;
B.enc = 0;
B.enc_n_patch = n_patch;
B.enc_pixels = n_patch ? dptr<uint16_t>(ri, R_ENCPIX) : nullptr;
B.enc_coord = n_patch ? dptr<int32_t>(ri, R_ENCCRD) : nullptr;
B.enc_n_seg = n_seg;
B.enc_cu = n_seg ? dptr<int32_t>(ri, R_ENCCU) : nullptr;
B.enc_max_seg = max_seg;
B.gen = RAD_GEN_PASS_COND;
kout_[rr].block_table_pitch = (int64_t)bt.size();
G = RadGenBatch{};
G.rows = P;
G.src = dptr<int32_t>(ri, R_SRC);
G.rope = dptr<int32_t>(ri, R_GROPE);
G.n_seg = nsg;
G.seg = dptr<int32_t>(ri, R_SEG);
G.seg_h = hptr<int32_t>(R_SEG);
G.seg_bidi_h = host_bidi_.data();
G.seg_cu = dptr<int32_t>(ri, R_SEG) + nsg + 1;
G.seg_start = dptr<int32_t>(ri, R_SEG) + nsg + 1 + 2 * nsg;
G.slot_mapping = dptr<int32_t>(ri, R_SLOT);
G.n_px = (int64_t)pxh.size() / 3;
G.px = at ? dptr<uint16_t>(ri, R_PX) : nullptr;
G.px_h = host_px_.data();
G.px_cu = dptr<int32_t>(ri, R_SEG) + 4 * nsg + 1;
G.sigma = dptr<float>(ri, R_SIG);
G.inpaint = inp ? 1 : 0;
G.inp_mask = inp ? dptr<float>(ri, R_MASK) : nullptr;
G.n_lane = (int64_t)host_lanes_.size();
G.lane_h = host_lanes_.data();
G.lane = G.n_lane ? dptr<int32_t>(ri, R_LANE) : nullptr;
}
pass_.kind = RAD_GEN_PASS_COND;
pass_.job = j.id;
pass_.branch = branch;
return &out_[0];
}
const RadBatch* Driver::build_denoise(const std::vector<int32_t>& take, int step) {
for (int g = 0; g < R_N; ++g) reg_[g].used = 0;
/* Two passes over the images: the entries and their rows, then the per-entry arrays. */
struct E { const Job* j; int32_t lane; int branch; };
std::vector<E> es;
for (int32_t l : take) {
const Job* j = nullptr;
for (auto& jp : jobs_) if (jp->id == lanes_[(size_t)l].job_id) { j = jp.get(); break; }
if (!j) continue;
for (int b = 0; b < j->n_branch; ++b) es.push_back({ j, l, b });
}
const int64_t S = (int64_t)es.size();
int64_t n_tok = 0;
int32_t max_q = 0, max_ctx = 0;
int64_t pitch = 1;
for (const E& e : es) {
n_tok += e.j->tokens;
max_q = std::max<int32_t>(max_q, (int32_t)e.j->tokens);
max_ctx = std::max<int32_t>(max_ctx, (int32_t)e.j->cond[e.branch].lay.rows);
pitch = std::max<int64_t>(pitch, (int64_t)kv_->block_table(e.j->cond[e.branch].seq, kv_group_).size());
}
int32_t* cu = hptr<int32_t>(R_CU);
int32_t* pos = hptr<int32_t>(R_POS);
int32_t* tok = hptr<int32_t>(R_TOK);
int32_t* grope = hptr<int32_t>(R_GROPE);
float* sig = hptr<float>(R_SIG);
float* sign = hptr<float>(R_SIGN);
float* cfg = hptr<float>(R_CFG);
int32_t* pair = hptr<int32_t>(R_PAIR);
int32_t* lane = hptr<int32_t>(R_LANE);
int32_t* flags = hptr<int32_t>(R_FLAGS);
uint32_t* seed = hptr<uint32_t>(R_SEED);
int32_t* btab = hptr<int32_t>(R_BT);
int32_t* used = hptr<int32_t>(R_USED);
int64_t row = 0;
cu[0] = 0;
pass_.lanes.clear();
pass_.marks.clear();
for (int64_t i = 0; i < S; ++i) {
const E& e = es[(size_t)i];
const Job& j = *e.j;
const Lane& ln = lanes_[(size_t)e.lane];
const Cond& c = j.cond[e.branch];
const int64_t N = j.tokens;
for (int64_t k = 0; k < N; ++k) { pos[row + k] = (int32_t)k; tok[row + k] = 0; }
for (int cc = 0; cc < 3; ++cc)
std::memcpy(grope + cc * n_tok + row, c.rope_img.data() + cc * N, (size_t)N * 4);
row += N;
cu[i + 1] = (int32_t)row;
sig[i] = j.sigmas[(size_t)ln.step];
sign[i] = j.sigmas[(size_t)ln.step + 1];
const bool neg = e.branch == 1;
cfg[i] = neg ? 0.0f : (j.n_branch > 1 ? j.req->cfg : 1.0f);
pair[i] = neg ? -2 : (j.n_branch > 1 ? (int32_t)(i + 1) : -1);
lane[i] = e.lane;
int32_t f = 0;
bool mark = false;
if (!neg) {
if (ln.step == 0) f |= RAD_GEN_F_FIRST;
if (j.req->inpaint) f |= RAD_GEN_F_INPAINT;
if (ln.previews_done < (int32_t)ln.preview_at.size() &&
ln.step + 1 == ln.preview_at[(size_t)ln.previews_done]) {
f |= RAD_GEN_F_PREVIEW;
mark = true;
}
pass_.lanes.push_back(e.lane);
pass_.marks.push_back(mark ? 1 : 0);
}
flags[i] = f;
seed[2 * i] = (uint32_t)(ln.seed & 0xffffffffu);
seed[2 * i + 1] = (uint32_t)(ln.seed >> 32);
const std::vector<int32_t>& bt = kv_->block_table(c.seq, kv_group_);
for (int64_t b = 0; b < pitch; ++b)
btab[i * pitch + b] = b < (int64_t)bt.size() ? bt[(size_t)b] : -1;
used[i] = (int32_t)c.lay.rows;
}
reg_[R_CU].used = (S + 1) * 4;
reg_[R_POS].used = reg_[R_TOK].used = n_tok * 4;
reg_[R_GROPE].used = 3 * n_tok * 4;
reg_[R_SIG].used = reg_[R_SIGN].used = reg_[R_CFG].used = S * 4;
reg_[R_PAIR].used = reg_[R_LANE].used = reg_[R_FLAGS].used = S * 4;
reg_[R_SEED].used = 2 * S * 4;
reg_[R_BT].used = S * pitch * 4;
reg_[R_USED].used = S * 4;
if (upload() < 0) return nullptr;
finish_batches(n_tok, S, max_q, step);
for (size_t rr = 0; rr < ranks_.size(); ++rr) {
RadBatch& B = out_[rr];
const int ri = (int)rr;
B.max_ctx_len = max_ctx;
B.rope_pos = nullptr;
B.rope_mixed = 0;
B.n_mm_rows = 0;
B.mm_rows = nullptr;
B.enc_n_patch = 0;
B.enc_pixels = nullptr;
B.enc_coord = nullptr;
B.enc_n_seg = 0;
B.enc_cu = nullptr;
B.gen = RAD_GEN_PASS_DENOISE;
kout_[rr].block_table_pitch = pitch;
kout_[rr].slot_mapping = nullptr;
RadGenBatch& G = gout_[rr];
G.rows = 0;
G.n_seg = 0;
G.seg_bidi_h = nullptr;
G.n_px = 0;
G.px_h = nullptr;
G.inpaint = 0;
G.n_lane = 0;
G.lane_h = nullptr;
G.rope = dptr<int32_t>(ri, R_GROPE);
G.lane_dh = hptr<int32_t>(R_LANE);
}
pass_.kind = RAD_GEN_PASS_DENOISE;
return &out_[0];
}
const RadBatch* Driver::build_decode(int32_t l, bool preview, int step) {
for (int g = 0; g < R_N; ++g) reg_[g].used = 0;
const Lane& ln = lanes_[(size_t)l];
const Job* j = nullptr;
for (auto& jp : jobs_) if (jp->id == ln.job_id) { j = jp.get(); break; }
if (!j) return nullptr;
int32_t* cu = hptr<int32_t>(R_CU);
cu[0] = 0;
cu[1] = (int32_t)j->tokens;
reg_[R_CU].used = 2 * 4;
if (upload() < 0) return nullptr;
finish_batches(j->tokens, 1, (int32_t)j->tokens, step);
for (size_t rr = 0; rr < ranks_.size(); ++rr) {
RadBatch& B = out_[rr];
B.max_ctx_len = 0;
B.rope_pos = nullptr;
B.rope_mixed = 0;
B.n_mm_rows = 0;
B.mm_rows = nullptr;
B.enc_n_patch = 0;
B.enc_pixels = nullptr;
B.enc_coord = nullptr;
B.enc_n_seg = 0;
B.enc_cu = nullptr;
B.gen = RAD_GEN_PASS_DECODE;
B.n_kv_groups = 0;
B.kv = nullptr;
RadGenBatch& G = gout_[rr];
G = RadGenBatch{};
G.dec_lane = l;
G.dec_height = j->req->height;
G.dec_width = j->req->width;
G.dec_preview = preview ? 1 : 0;
}
dec_bytes_ = (int64_t)j->req->width * j->req->height * decl_.pixel_channels;
pass_.kind = RAD_GEN_PASS_DECODE;
pass_.job = j->id;
pass_.lane = l;
pass_.preview = preview;
return &out_[0];
}
int Driver::done() {
std::lock_guard<std::mutex> lk(mu_);
const uint64_t now = rad_mono_ns();
switch (pass_.kind) {
case RAD_GEN_PASS_COND: {
Job* j = job_locked(pass_.job);
if (!j) break;
j->cond[pass_.branch].encoded = true;
bool all = true;
for (int b = 0; b < j->n_branch; ++b) all = all && j->cond[b].encoded;
if (all) j->req->ticket->t_cond_ns = (int64_t)now;
break;
}
case RAD_GEN_PASS_DENOISE:
for (size_t i = 0; i < pass_.lanes.size(); ++i) {
Lane& ln = lanes_[(size_t)pass_.lanes[i]];
Job* j = job_locked(ln.job_id);
if (!j) continue;
if (ln.step == 0 && j->req->ticket->t_first_step_ns == 0)
j->req->ticket->t_first_step_ns = (int64_t)now;
++ln.step;
const int32_t n_steps = (int32_t)j->sigmas.size() - 1;
if (pass_.marks[i]) ln.preview_due = true;
if (ln.step >= n_steps) {
ln.final_due = true;
j->req->ticket->t_denoised_ns = (int64_t)now;
}
}
break;
case RAD_GEN_PASS_DECODE: {
Lane& ln = lanes_[(size_t)pass_.lane];
Job* j = job_locked(pass_.job);
if (!j) break;
Image im;
im.index = ln.index;
im.w = j->req->width;
im.h = j->req->height;
im.ch = (int32_t)decl_.pixel_channels;
im.seed = ln.seed;
im.px.assign((const uint8_t*)img_host_, (const uint8_t*)img_host_ + dec_bytes_);
if (pass_.preview) {
im.preview = true;
im.preview_no = ln.previews_done;
ln.preview_due = false;
++ln.previews_done;
} else {
ln.final_due = false;
ln.finished = true;
++j->images_done;
}
j->req->ticket->push(std::move(im));
if (j->images_done >= j->req->n) {
j->req->ticket->t_done_ns = (int64_t)now;
j->req->ticket->finish(RAD_OK);
}
break;
}
default:
break;
}
pass_ = Pass{};
dec_bytes_ = 0;
return RAD_OK;
}
} /* namespace gen */
} /* namespace rad */
+186
View File
@@ -0,0 +1,186 @@
/* driver.h -- the image generator's pass driver (gen.h says what the passes are).
*
* ONE THREAD DRIVES IT, the engine's, and it asks two things a pass: `next()` decides what runs
* and stages it, `done()` folds the result back once every rank has run it. Requests arrive from
* HTTP threads through `submit()` and leave through their Ticket; the queue is the only thing the
* two kinds of thread share, behind one mutex.
*
* WHAT RUNS NEXT, in this order, one pass at a time:
*
* 1. a DECODE an image is owed -- a finished image, or a preview its last step marked. First,
* because a finished image frees its lane and answers its caller, and a preview must be read
* before the lane's next step writes the preview latent again.
* 2. a COND an admitted request is owed: its conditioning, so its images can join the next
* denoise pass.
* 3. a DENOISE over as many images in flight as fit the step's rows, oldest request first, each
* at its own step.
*
* A request is ADMITTED when it can get lanes for every image and KV for every conditioning
* sequence; until then it waits, in order -- a request that does not fit blocks the ones behind
* it, so a large request is not starved by a stream of small ones.
*
* THE STAGING is one region per rank on its card and one pinned host region with the same layout.
* Every pass is synchronised before the next is built (Engine::gen_loop), so one host region is
* enough: an image pass is tens of milliseconds and more, and the host work between two is
* microseconds.
*/
#pragma once
#include "gen.h"
#include "device/device.h"
#include <mutex>
#include <unordered_map>
namespace rad {
namespace gen {
class Driver {
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, const Config& cfg, IKVManager* kv, const std::vector<RankIO>& ranks);
void fini();
~Driver() { fini(); }
/* The bytes init() allocates on each rank's card, for the VRAM budget. */
static int64_t device_bytes(const Program& prog, const Config& cfg);
/* ---------------------------------------------------------- HTTP threads */
/* Queue a request. Refused at once -- with `why` -- when it can never run: a size past the
* largest image, more pictures than the model takes, a conditioning longer than a pass. */
int submit(std::unique_ptr<Request> r, std::string* why);
/* What a request may ask for: the model's own limits, for the server to check before it does
* the expensive part of preparing one. */
const RadGeneratorDecl& decl() const { return decl_; }
const std::vector<double>& fixed_sigmas() const { return fixed_; }
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);
/* ---------------------------------------------------------- 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;
/* The bytes of the generator's image buffer the pass just staged makes, 0 for a pass that
* makes none: the engine copies them to `host()` 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();
bool busy() const;
/* For /health, /stats and the dashboard. */
int64_t queued() const;
int64_t running() const;
private:
struct Cond {
Layout lay;
uint64_t seq = 0; /* the KV manager's key */
bool have_kv = false;
bool encoded = false;
std::vector<int32_t> rope_img; /* [3, image tokens]: the image's rows at this sequence */
};
struct Job {
uint64_t id = 0;
std::unique_ptr<Request> req;
int n_branch = 1;
Cond cond[2];
int32_t h_lat = 0, w_lat = 0;
int64_t tokens = 0;
std::vector<float> sigmas;
std::vector<int32_t> lanes;
std::vector<std::pair<int32_t, int32_t>> ref_hw;
int32_t images_done = 0;
bool admitted = false;
bool failed = false;
};
struct Lane {
int64_t job = -1; /* index into jobs_ by id; -1 free */
uint64_t job_id = 0;
int32_t index = 0;
int32_t step = 0;
uint64_t seed = 0;
std::vector<int32_t> preview_at; /* the steps after which a preview is decoded */
int32_t previews_done = 0;
bool preview_due = false;
bool final_due = false;
bool finished = false;
};
/* What the pass being run is, for done(). */
struct Pass {
int kind = 0;
uint64_t job = 0;
int branch = 0;
int32_t lane = -1;
bool preview = false;
std::vector<int32_t> lanes; /* DENOISE: the lanes it stepped, one per image */
std::vector<char> marks; /* ... and whether each was marked for a preview */
};
/* 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_ROPE, R_CU, R_MMROW, R_ENCPIX, R_ENCCRD, R_ENCCU, R_SRC, R_GROPE,
R_SEG, R_SLOT, R_PX, R_MASK, R_SIG, R_SIGN, R_CFG, R_PAIR, R_LANE, R_FLAGS, R_SEED,
R_BT, R_USED, R_N };
int layout_regions();
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 finish_batches(int64_t n_tok, int64_t n_seq, int32_t max_q, int step);
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);
const RadBatch* build_cond(Job& j, int branch, int step);
const RadBatch* build_denoise(const std::vector<int32_t>& lanes, int step);
const RadBatch* build_decode(int32_t lane, bool preview, int step);
RadGeneratorDecl decl_{};
std::vector<double> fixed_;
int64_t max_tok_ = 0, max_seqs_ = 0, max_enc_ = 0, patch_dim_ = 0;
int64_t max_rows_ = 0; /* the longest conditioning sequence */
int64_t max_px_ = 0; /* pixels the staging holds */
int64_t block_size_ = 0, max_blocks_ = 0;
int32_t kv_group_ = 0;
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];
void* img_host_ = nullptr;
int64_t img_bytes_ = 0;
int64_t dec_bytes_ = 0;
std::vector<RadBatch> out_; /* one per rank */
std::vector<RadGenBatch> gout_;
std::vector<RadKVGroupBatch> kout_;
Pass pass_;
/* The host arrays a COND pass's plugin reads on the host (RadGenBatch's _h fields). */
std::vector<int32_t> host_bidi_, host_px_, host_lanes_;
mutable std::mutex mu_;
std::deque<std::unique_ptr<Job>> jobs_; /* arrival order */
std::vector<Lane> lanes_;
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 */
+213
View File
@@ -0,0 +1,213 @@
/* gen.cpp -- the request side of image generation: the ticket a caller waits on, the sampler's
* schedule, and the generator's sequence built from a conditioning prompt (gen.h). */
#include "gen.h"
#include <chrono>
#include <cmath>
#include <cstring>
namespace rad {
namespace gen {
/* ================================================================== the ticket */
void Ticket::push(Image&& im) {
{
std::lock_guard<std::mutex> lk(mu_);
q_.push_back(std::move(im));
}
cv_.notify_all();
}
void Ticket::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();
}
void Ticket::step(int32_t done, int32_t total) {
(void)done;
(void)total;
}
bool Ticket::next(Image* 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 Ticket::finished() const {
std::lock_guard<std::mutex> lk(mu_);
return done_ && q_.empty();
}
int Ticket::status() const {
std::lock_guard<std::mutex> lk(mu_);
return status_;
}
std::string Ticket::why() const {
std::lock_guard<std::mutex> lk(mu_);
return why_;
}
/* ================================================================== the schedule */
/* diffusers' FlowMatchEulerDiscreteScheduler.set_timesteps with explicit sigmas, as the pipeline
* calls it, in the precision it runs at: the sigmas are an f32 array and every shift is numpy f32
* arithmetic, the Python floats in it (exp(mu), the shift, the terminal) taking the array's type. */
std::vector<float> schedule(const RadGeneratorDecl& d, const std::vector<double>& fixed,
int32_t steps, int64_t tokens) {
std::vector<float> s;
if (!fixed.empty()) {
for (double v : fixed) s.push_back((float)v);
} else {
const int32_t n = steps > 0 ? steps : (int32_t)d.default_steps;
/* np.linspace(1.0, 1 / n, n) in f64, then astype(f32). */
const double lo = 1.0 / (double)n;
for (int32_t i = 0; i < n; ++i) {
const double v = n == 1 ? 1.0 : 1.0 + (lo - 1.0) * (double)i / (double)(n - 1);
s.push_back((float)v);
}
}
if (d.dyn_shift) {
const double m = (d.max_shift - d.base_shift) / (double)(d.max_seq - d.base_seq);
const double b = d.base_shift - m * (double)d.base_seq;
const double mu = (double)tokens * m + b;
const float e = d.shift_exp ? (float)std::exp(mu) : (float)mu;
for (float& t : s) t = e / (e + (1.0f / t - 1.0f));
} else {
const float sh = (float)d.shift;
for (float& t : s) t = sh * t / (1.0f + (sh - 1.0f) * t);
}
if (d.shift_terminal > 0 && !s.empty()) {
const float scale = (1.0f - s.back()) / (float)(1.0 - d.shift_terminal);
for (float& t : s) t = 1.0f - ((1.0f - t) / scale);
}
s.push_back(0.0f);
return s;
}
/* ================================================================== the sequence */
void image_rope(int32_t pos, int32_t h, int32_t w, int32_t* planes, int64_t n_total) {
const int32_t h0 = -(h - h / 2), w0 = -(w - w / 2);
int64_t k = 0;
for (int32_t r = 0; r < h; ++r)
for (int32_t c = 0; c < w; ++c, ++k) {
planes[k] = pos;
planes[n_total + k] = h0 + r;
planes[2 * n_total + k] = w0 + c;
}
}
int build_layout(const Branch& b, int64_t slot_rows,
const std::vector<std::pair<int32_t, int32_t>>& ref_hw, Layout* out,
std::string* why) {
*out = Layout{};
const int64_t T = (int64_t)b.tokens.size();
if (b.n_drop < 0 || b.n_drop >= T) {
if (why) *why = "the conditioning prompt is no longer than its fixed prefix";
return RAD_E_INVAL;
}
/* The media runs, in prompt order: [tok, tok + n) placeholder rows of item `item`. */
struct Run { int64_t tok, n; int32_t item; };
std::vector<Run> runs;
if (b.media)
for (const mm::RopeLayout::Run& r : b.media->rope.runs)
runs.push_back({ r.tok, r.n, r.item });
if (runs.size() != ref_hw.size()) {
if (why) *why = "the prompt places " + std::to_string(runs.size()) + " picture(s) and " +
std::to_string(ref_hw.size()) + " were encoded for it";
return RAD_E_INVAL;
}
/* Each picture's rows and where its latent rows start among all the references'. */
std::vector<int64_t> lat0(ref_hw.size() + 1, 0);
for (size_t i = 0; i < ref_hw.size(); ++i)
lat0[i + 1] = lat0[i] + (int64_t)ref_hw[i].first * ref_hw[i].second;
int64_t rows = 0;
{
int64_t text = T - b.n_drop;
for (const Run& r : runs) {
if (r.tok < b.n_drop) {
if (why) *why = "a picture sits inside the prompt's fixed prefix";
return RAD_E_INVAL;
}
text -= r.n;
}
rows = text;
for (size_t i = 0; i < runs.size(); ++i) {
const int64_t lat = (int64_t)ref_hw[i].first * ref_hw[i].second;
if (runs[i].n * slot_rows != lat) {
if (why) *why = "picture " + std::to_string(i + 1) + " has " +
std::to_string(runs[i].n) + " encoder rows, which do not tile its " +
std::to_string(ref_hw[i].first) + " x " +
std::to_string(ref_hw[i].second) + " latent grid";
return RAD_E_INVAL;
}
rows += lat;
}
}
out->rows = rows;
out->src.assign((size_t)rows, 0);
out->rope.assign((size_t)rows * 3, 0);
out->seg.push_back(0);
int32_t pos = 0;
int64_t row = 0;
size_t ri = 0;
int64_t t = b.n_drop;
bool in_text = false;
auto close_text = [&]() {
if (in_text) {
out->seg.push_back((int32_t)row);
out->bidi.push_back(0);
in_text = false;
}
};
while (t < T) {
if (ri < runs.size() && t == runs[ri].tok) {
close_text();
const int32_t h = ref_hw[ri].first, w = ref_hw[ri].second;
const int64_t n = (int64_t)h * w;
for (int64_t k = 0; k < n; ++k) out->src[(size_t)(row + k)] = -(int32_t)(1 + lat0[ri] + k);
std::vector<int32_t> pl((size_t)n * 3);
image_rope(pos, h, w, pl.data(), n);
for (int c = 0; c < 3; ++c)
std::memcpy(&out->rope[(size_t)(c * rows + row)], &pl[(size_t)(c * n)],
(size_t)n * sizeof(int32_t));
pos += h > w ? h : w;
row += n;
out->seg.push_back((int32_t)row);
out->bidi.push_back(1);
t += runs[ri].n;
++ri;
continue;
}
in_text = true;
out->src[(size_t)row] = (int32_t)t;
for (int c = 0; c < 3; ++c) out->rope[(size_t)(c * rows + row)] = pos;
++pos;
++row;
++t;
}
close_text();
out->next_pos = pos;
if (row != rows) {
if (why) *why = "the generator's sequence did not come out at the length it was sized for";
return RAD_E_STATE;
}
return RAD_OK;
}
} /* namespace gen */
} /* namespace rad */
+145
View File
@@ -0,0 +1,145 @@
/* gen.h -- image generation: what a request is, what comes back, and the driver that turns one
* into the passes an image generator declares (rad_declare_generator, abi/rad_builder.h).
*
* A GENERATOR IS NOT DRIVEN BY TOKEN STEPS. Its work is three kinds of pass -- conditioning,
* denoising, decoding -- and an image is tens of denoising passes over thousands of latent rows,
* every one of them read whole, none of them sampled. The scheduler that serves text owns token
* positions, prefix reuse, preemption and speculation, and none of that has a meaning here, so the
* generator gets a driver of its own (this file) and shares everything below the step with the rest
* of the engine: the ranks, the plugin's step function, the KV manager the conditioning lives in.
*
* THE PASSES, as the driver runs them:
*
* COND once for every conditioning sequence a request has -- its prompt, and with guidance
* its negative prompt -- the prompt (and its reference pictures) encoded into the
* generator's KV group. A request is admitted once its lanes and its KV are free.
* DENOISE one step for each image in flight that fits the pass, any mix of requests, sizes and
* step counts: each image carries its own sigma. With guidance an image is two entries,
* its positive and its negative conditioning, which the plugin combines.
* DECODE one image's latent to pixels, read back and handed to its request.
*
* A request's images run in LANES -- the plugin's own latent state, `max_lanes` of them -- so one
* request of n images takes n lanes and shares one conditioning.
*/
#pragma once
#include "rad_core.h"
#include "mm/processor.h"
#include <atomic>
#include <condition_variable>
#include <deque>
#include <memory>
#include <mutex>
#include <string>
#include <vector>
namespace rad {
struct IKVManager;
namespace gen {
/* A picture as the generator's own encoder reads it: RGBA (or `ch` channels), row-major, each value
* bf16 in [-1, 1]. */
struct Pixels {
int32_t w = 0, h = 0, ch = 4;
std::vector<uint16_t> bf16;
};
/* ONE CONDITIONING SEQUENCE: the prompt as tokens, with the media it carries placed, and how many
* of its first tokens the generator does not see (RadGeneratorDecl::drop_prefix). */
struct Branch {
std::vector<int32_t> tokens;
std::shared_ptr<mm::PromptMedia> media; /* null for a prompt with no pictures */
int32_t n_drop = 0;
};
/* ONE IMAGE, or one preview of one, on its way back. */
struct Image {
int32_t index = 0; /* which of the request's n */
int32_t w = 0, h = 0, ch = 4;
std::vector<uint8_t> px; /* [h, w, ch] */
bool preview = false;
int32_t preview_no = 0;
uint64_t seed = 0;
};
/* THE CHANNEL BACK TO THE CALLER: images as they finish, then the end. The driver's thread writes,
* the caller's reads; a mutex is enough -- an image is megabytes and there are a handful a
* request. `cancel` is the caller's, read by the driver at its next pass. */
class Ticket {
public:
/* driver side */
void push(Image&& im);
void finish(int status, const std::string& why = std::string());
void step(int32_t done, int32_t total);
/* caller side: the next image, or false once the request has ended and every image was taken.
* Waits at most `ms` milliseconds; `*timed_out` says a false was a timeout, not the end. */
bool next(Image* out, int ms, bool* timed_out);
bool finished() const;
int status() const;
std::string why() const;
std::atomic<bool> cancel{false};
/* What the request cost, for the response: the conditioning's tokens, the latent rows made, and
* the time each phase took. Written by the driver before finish(). */
int64_t in_tokens = 0, out_tokens = 0;
int64_t t_submit_ns = 0, t_cond_ns = 0, t_first_step_ns = 0, t_denoised_ns = 0, t_done_ns = 0;
int32_t steps = 0;
private:
mutable std::mutex mu_;
std::condition_variable cv_;
std::deque<Image> q_;
bool done_ = false;
int status_ = RAD_OK;
std::string why_;
};
struct Request {
Branch pos, neg;
bool has_neg = false;
float cfg = 1.0f;
int32_t width = 0, height = 0; /* pixels, whole multiples of the declared multiple */
int32_t steps = 0; /* 0: the model's default (or its fixed schedule) */
int32_t n = 1;
uint64_t seed = 0; /* image i draws its noise from seed + i */
int32_t previews = 0; /* partial images per image, 0..3 */
/* The reference pictures' encoder view, one per media item of `pos`, in order. */
std::vector<Pixels> refs;
/* REPAINTING (an edit with a mask): the picture at the size being made, and per latent token
* how much of it is repainted (1) and how much kept (0). */
bool inpaint = false;
Pixels inp_src;
std::vector<float> inp_mask;
std::shared_ptr<Ticket> ticket;
};
/* ================================================================== the sampler's schedule */
/* The sigmas a request steps through, n + 1 of them, the last 0: the decl's fixed schedule, or
* `steps` (0: the default) shifted the way the decl says. `tokens` is the image's latent token
* count, which a dynamic shift reads. f32, as the reference holds them. */
std::vector<float> schedule(const RadGeneratorDecl& d, const std::vector<double>& fixed,
int32_t steps, int64_t tokens);
/* ================================================================== the generator's sequence */
/* ONE CONDITIONING SEQUENCE AS THE GENERATOR SEES IT (RadGeneratorDecl::layout): which prompt row
* or reference latent row each of its rows is, its rotary positions, its segments, and where the
* image being made starts. */
struct Layout {
int64_t rows = 0;
std::vector<int32_t> src; /* [rows] */
std::vector<int32_t> rope; /* [3, rows] component-major */
std::vector<int32_t> seg; /* [n_seg + 1] */
std::vector<int32_t> bidi; /* [n_seg] */
int32_t next_pos = 0; /* the rotary count after the last row: the image's frame */
};
/* `ref_hw` is each reference's latent grid (h, w), in media order. RAD_E_INVAL with `why` when the
* prompt does not start with its drop prefix or a picture's slots do not tile its latent grid. */
int build_layout(const Branch& b, int64_t slot_rows, const std::vector<std::pair<int32_t, int32_t>>& ref_hw,
Layout* out, std::string* why);
/* The rotary positions of an h x w image at frame `pos`: [3, h * w] component-major. */
void image_rope(int32_t pos, int32_t h, int32_t w, int32_t* planes, int64_t n_total);
} /* namespace gen */
} /* namespace rad */
+4 -2
View File
@@ -101,8 +101,10 @@ int KVManager::configure(const std::vector<KVGroupInfo>& groups, const Config& c
int KVManager::plan_groups(const std::vector<KVGroupInfo>& groups, const Config& cfg) {
/* Only to say it is ignored on a model with no recurrent state: the slots are host memory and
* the engine opens them (set_checkpoint_store). */
const int64_t budget_ckpts = cfg.checkpoint_slots > 0 ? cfg.checkpoint_slots : 0;
* the engine opens them (set_checkpoint_store). The operator's own flag, not the default --
* every model without such state would otherwise warn about a flag nobody passed. */
const int64_t budget_ckpts = cfg.given.count("--checkpoint-slots") && cfg.checkpoint_slots > 0
? cfg.checkpoint_slots : 0;
forget();
max_seqs_ = cfg.max_seqs > 0 ? cfg.max_seqs : 1;
+1 -1
View File
@@ -173,7 +173,7 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
exp = std::min(std::max(b.expert_ceiling, b.expert_floor), b.elastic - kv);
/* THE ONE SEQUENCE WINS, and the experts it pushes off the card have no tier: the
* planner refuses them by name. Said here too, with what moves it. */
if (log && exp < b.expert_floor)
if (log && b.expert_floor > 0 && exp < b.expert_floor)
RAD_WARN("one --max-model-len sequence's cache (%s) leaves the experts %s, short of "
"the %s the pinned host pool cannot hold: raise --host-pool-mib or lower "
"--max-model-len",
+167
View File
@@ -0,0 +1,167 @@
/* imaging.cpp -- PIL's Lanczos resize and alpha paste (imaging.h). The constants and the order of
* every operation are Pillow's (src/libImaging/Resample.c, Convert.c, Paste.c). */
#include "mm/imaging.h"
#include <algorithm>
#include <cmath>
#include <cstring>
#include <vector>
namespace rad {
namespace mm {
namespace {
constexpr int kPrecision = 32 - 8 - 2;
double sinc(double x) {
if (x == 0.0) return 1.0;
x *= M_PI;
return std::sin(x) / x;
}
double lanczos(double x) { return (-3.0 <= x && x < 3.0) ? sinc(x) * sinc(x / 3.0) : 0.0; }
/* One axis: for each output index its first input index, its tap count, and `ksize` fixed-point
* coefficients. */
struct Axis {
int ksize = 0;
std::vector<int> bounds; /* [out, 2]: xmin, count */
std::vector<int> kk; /* [out, ksize] */
};
Axis coeffs(int in_size, int out_size) {
Axis a;
const double scale = (double)in_size / (double)out_size;
double filterscale = scale < 1.0 ? 1.0 : scale;
const double support = 3.0 * filterscale;
a.ksize = (int)std::ceil(support) * 2 + 1;
a.bounds.assign((size_t)out_size * 2, 0);
a.kk.assign((size_t)out_size * a.ksize, 0);
std::vector<double> k((size_t)a.ksize);
for (int xx = 0; xx < out_size; ++xx) {
const double center = (xx + 0.5) * scale;
double ww = 0.0;
const double ss = 1.0 / filterscale;
int xmin = (int)(center - support + 0.5);
if (xmin < 0) xmin = 0;
int xmax = (int)(center + support + 0.5);
if (xmax > in_size) xmax = in_size;
xmax -= xmin;
int x = 0;
for (; x < xmax; ++x) {
const double w = lanczos((x + xmin - center + 0.5) * ss);
k[(size_t)x] = w;
ww += w;
}
for (x = 0; x < xmax; ++x)
if (ww != 0.0) k[(size_t)x] /= ww;
for (; x < a.ksize; ++x) k[(size_t)x] = 0.0;
a.bounds[(size_t)xx * 2] = xmin;
a.bounds[(size_t)xx * 2 + 1] = xmax;
for (x = 0; x < a.ksize; ++x) {
const double v = k[(size_t)x] * (double)(1 << kPrecision);
a.kk[(size_t)xx * a.ksize + x] = v < 0 ? (int)(-0.5 + v) : (int)(0.5 + v);
}
}
return a;
}
inline uint8_t clip8(int v) {
if (v >= (1 << kPrecision << 8)) return 255;
if (v <= 0) return 0;
return (uint8_t)(v >> kPrecision);
}
inline unsigned muldiv255(unsigned a, unsigned b) {
const unsigned t = a * b + 128;
return ((t >> 8) + t) >> 8;
}
} /* namespace */
void resize_lanczos_rgba(const FrameRGBA& src, int32_t w, int32_t h, FrameRGBA* out) {
const int iw = src.w, ih = src.h;
/* RGBA -> RGBa: the colour premultiplied by the alpha */
std::vector<uint8_t> pre((size_t)iw * ih * 4);
for (size_t i = 0; i < (size_t)iw * ih; ++i) {
const unsigned al = src.rgba[i * 4 + 3];
for (int c = 0; c < 3; ++c) pre[i * 4 + c] = (uint8_t)muldiv255(src.rgba[i * 4 + c], al);
pre[i * 4 + 3] = (uint8_t)al;
}
const bool horiz = w != iw, vert = h != ih;
const Axis ax = coeffs(iw, w), ay = coeffs(ih, h);
/* the rows the vertical pass reads */
const int y_first = ay.bounds[0];
const int y_last = ay.bounds[(size_t)(h - 1) * 2] + ay.bounds[(size_t)(h - 1) * 2 + 1];
std::vector<uint8_t> tmp;
const uint8_t* rows = pre.data();
int rw = iw, row0 = 0;
if (horiz) {
const int th = vert ? y_last - y_first : ih;
const int off = vert ? y_first : 0;
tmp.assign((size_t)w * th * 4, 0);
for (int yy = 0; yy < th; ++yy)
for (int xx = 0; xx < w; ++xx) {
const int xmin = ax.bounds[(size_t)xx * 2], xn = ax.bounds[(size_t)xx * 2 + 1];
const int* k = &ax.kk[(size_t)xx * ax.ksize];
int s[4] = { 1 << (kPrecision - 1), 1 << (kPrecision - 1), 1 << (kPrecision - 1),
1 << (kPrecision - 1) };
const uint8_t* p = pre.data() + ((size_t)(yy + off) * iw + xmin) * 4;
for (int x = 0; x < xn; ++x)
for (int c = 0; c < 4; ++c) s[c] += (int)p[(size_t)x * 4 + c] * k[x];
for (int c = 0; c < 4; ++c) tmp[((size_t)yy * w + xx) * 4 + c] = clip8(s[c]);
}
rows = tmp.data();
rw = w;
row0 = vert ? y_first : 0;
}
std::vector<uint8_t> res;
if (vert) {
res.assign((size_t)rw * h * 4, 0);
for (int yy = 0; yy < h; ++yy) {
const int ymin = ay.bounds[(size_t)yy * 2] - row0, yn = ay.bounds[(size_t)yy * 2 + 1];
const int* k = &ay.kk[(size_t)yy * ay.ksize];
for (int xx = 0; xx < rw; ++xx) {
int s[4] = { 1 << (kPrecision - 1), 1 << (kPrecision - 1), 1 << (kPrecision - 1),
1 << (kPrecision - 1) };
for (int y = 0; y < yn; ++y) {
const uint8_t* p = rows + ((size_t)(y + ymin) * rw + xx) * 4;
for (int c = 0; c < 4; ++c) s[c] += (int)p[c] * k[y];
}
for (int c = 0; c < 4; ++c) res[((size_t)yy * rw + xx) * 4 + c] = clip8(s[c]);
}
}
} else {
res.assign(rows, rows + (size_t)rw * (horiz ? h : ih) * 4);
}
/* RGBa -> RGBA */
out->w = w;
out->h = h;
out->rgba.resize((size_t)w * h * 4);
for (size_t i = 0; i < (size_t)w * h; ++i) {
const unsigned al = res[i * 4 + 3];
for (int c = 0; c < 3; ++c) {
const unsigned v = res[i * 4 + c];
out->rgba[i * 4 + c] =
(al == 255 || al == 0) ? (uint8_t)v : (uint8_t)std::min(255u, (255u * v) / al);
}
out->rgba[i * 4 + 3] = (uint8_t)al;
}
}
void composite_white(const FrameRGBA& src, Frame* out) {
out->w = src.w;
out->h = src.h;
out->rgb.resize((size_t)src.w * src.h * 3);
for (size_t i = 0; i < (size_t)src.w * src.h; ++i) {
const unsigned a = src.rgba[i * 4 + 3];
for (int c = 0; c < 3; ++c) {
const unsigned t = src.rgba[i * 4 + c] * a + 255u * (255u - a) + 128u;
out->rgb[i * 3 + c] = (uint8_t)(((t >> 8) + t) >> 8);
}
}
}
} /* namespace mm */
} /* namespace rad */
+25
View File
@@ -0,0 +1,25 @@
/* imaging.h -- the picture arithmetic an image generator's reference pipeline does in PIL, done the
* way PIL does it, so a picture reaches the model as the reference's would.
*
* THE RESIZE IS PIL's Image.resize WITH LANCZOS, bit for bit: per-axis filter coefficients
* computed in double (support 3 times the downscale, normalised to sum one), turned into 22-bit
* fixed point, a horizontal pass then a vertical one over 8-bit values, each output rounded and
* clipped -- and an RGBA picture premultiplied by its alpha first and divided back after, which is
* what PIL's resize does to RGBA. Diffusers' VaeImageProcessor resizes a picture exactly this way.
*
* THE COMPOSITE is Image.paste(picture, mask=alpha) onto white: each channel
* (c * a + 255 * (255 - a)) / 255 in PIL's rounding -- how the reference flattens a transparent
* picture for a text encoder that reads RGB. */
#pragma once
#include "mm/media.h"
namespace rad {
namespace mm {
/* `src` resized to w x h. */
void resize_lanczos_rgba(const FrameRGBA& src, int32_t w, int32_t h, FrameRGBA* out);
/* `src` over an opaque white ground. */
void composite_white(const FrameRGBA& src, Frame* out);
} /* namespace mm */
} /* namespace rad */
+179
View File
@@ -34,6 +34,13 @@ static int no_decoder(std::string* why) {
int decode_image(const uint8_t*, size_t, int64_t, Frame*, std::string* why) {
return no_decoder(why);
}
int decode_image_rgba(const uint8_t*, size_t, int64_t, FrameRGBA*, std::string* why) {
return no_decoder(why);
}
int encode_image(const uint8_t*, int32_t, int32_t, int32_t, const std::string&, int32_t,
std::vector<uint8_t>*, std::string* why) {
return no_decoder(why);
}
int decode_video(const uint8_t*, size_t, SampleFn, const void*, int64_t, Video*,
std::string* why) {
return no_decoder(why);
@@ -211,6 +218,46 @@ int to_rgb(const AVFrame* f, SwsContext** sws, Frame* out, std::string* why) {
return RAD_OK;
}
/* The same conversion to packed RGBA, for a picture whose alpha is kept. */
int to_rgba(const AVFrame* f, SwsContext** sws, FrameRGBA* out, std::string* why) {
const AVPixelFormat src = (AVPixelFormat)f->format;
*sws = sws_getCachedContext(*sws, f->width, f->height, src, f->width, f->height,
AV_PIX_FMT_RGBA, SWS_BILINEAR, nullptr, nullptr, nullptr);
if (!*sws) { *why = "no colour conversion from this pixel format"; return RAD_E_UNSUPPORTED; }
int cs = f->colorspace;
if (cs == AVCOL_SPC_UNSPECIFIED || cs == AVCOL_SPC_RGB) cs = AVCOL_SPC_BT470BG;
const int src_full = f->color_range == AVCOL_RANGE_JPEG ||
src == AV_PIX_FMT_YUVJ420P || src == AV_PIX_FMT_YUVJ422P ||
src == AV_PIX_FMT_YUVJ444P || src == AV_PIX_FMT_YUVJ440P;
sws_setColorspaceDetails(*sws, sws_getCoefficients(cs), src_full,
sws_getCoefficients(SWS_CS_DEFAULT), 1, 0, 1 << 16, 1 << 16);
AVFrame* dst = av_frame_alloc();
if (!dst) { *why = "out of memory"; return RAD_E_NOMEM; }
dst->format = AV_PIX_FMT_RGBA;
dst->width = f->width;
dst->height = f->height;
if (av_frame_get_buffer(dst, 0) < 0) {
av_frame_free(&dst);
*why = "out of memory";
return RAD_E_NOMEM;
}
const int e = sws_scale(*sws, f->data, f->linesize, 0, f->height, dst->data, dst->linesize);
if (e != f->height) {
av_frame_free(&dst);
*why = "colour conversion failed";
return RAD_E_INVAL;
}
out->w = f->width;
out->h = f->height;
const size_t row = (size_t)f->width * 4;
out->rgba.resize(row * (size_t)f->height);
for (int y = 0; y < f->height; ++y)
std::memcpy(out->rgba.data() + (size_t)y * row, dst->data[0] + (ptrdiff_t)y * dst->linesize[0],
row);
av_frame_free(&dst);
return RAD_OK;
}
/* THE DECODE LOOP, for both kinds: every frame in presentation order, `keep(i, frame)` told the
* index of each and whether to stop.
*
@@ -313,6 +360,138 @@ int decode_image(const uint8_t* data, size_t n, int64_t max_pixels, Frame* out,
return RAD_OK;
}
int decode_image_rgba(const uint8_t* data, size_t n, int64_t max_pixels, FrameRGBA* out,
std::string* why) {
std::string w;
if (!why) why = &w;
if (!data || n == 0) { *why = "empty"; return RAD_E_INVAL; }
Input in;
RAD_TRY(in.open(data, n, true, why));
const AVCodecParameters* cp = in.fmt->streams[in.stream]->codecpar;
if (cp->width <= 0 || cp->height <= 0) { *why = "the image has no size"; return RAD_E_INVAL; }
if ((int64_t)cp->width * cp->height > max_pixels) {
*why = "the image is " + std::to_string(cp->width) + "x" + std::to_string(cp->height) +
", over the server's " + std::to_string(max_pixels) + "-pixel limit for a source";
return RAD_E_INVAL;
}
SwsContext* sws = nullptr;
bool got = false;
const int s = decode_frames(in, [&](int64_t, const AVFrame* f) -> int {
const int c = to_rgba(f, &sws, out, why);
if (c < 0) return c;
got = true;
return 1;
}, why);
sws_freeContext(sws);
if (s < 0) return s;
if (!got) { *why = "the image decoded to no frame"; return RAD_E_INVAL; }
return RAD_OK;
}
/* ONE PICTURE THROUGH ONE ENCODER. The pixels are converted to the pixel format the encoder takes
* (swscale, full-range BT.601 for jpeg's YUV, as PIL writes it), sent as one frame, and the one
* packet that comes back is the file: png, mjpeg and libwebp all write a complete image file a
* packet. */
int encode_image(const uint8_t* px, int32_t w, int32_t h, int32_t ch, const std::string& format,
int32_t quality, std::vector<uint8_t>* out, std::string* why) {
std::string wy;
if (!why) why = &wy;
if (!px || w <= 0 || h <= 0 || (ch != 3 && ch != 4) || !out) {
*why = "no picture to encode";
return RAD_E_INVAL;
}
const AVCodec* codec = nullptr;
AVPixelFormat pf = AV_PIX_FMT_NONE;
if (format == "png") {
codec = avcodec_find_encoder(AV_CODEC_ID_PNG);
pf = ch == 4 ? AV_PIX_FMT_RGBA : AV_PIX_FMT_RGB24;
} else if (format == "jpeg") {
if (ch == 4) { *why = "jpeg carries no alpha"; return RAD_E_INVAL; }
codec = avcodec_find_encoder(AV_CODEC_ID_MJPEG);
pf = AV_PIX_FMT_YUVJ420P;
} else if (format == "webp") {
codec = avcodec_find_encoder_by_name("libwebp");
pf = AV_PIX_FMT_BGRA;
} else {
*why = "'" + format + "' is not an image format this server writes (png, jpeg, webp)";
return RAD_E_INVAL;
}
if (!codec) {
*why = "this build has no " + format + " encoder";
return RAD_E_UNSUPPORTED;
}
AVCodecContext* cx = avcodec_alloc_context3(codec);
AVFrame* fr = av_frame_alloc();
AVPacket* pk = av_packet_alloc();
SwsContext* sws = nullptr;
int st = RAD_OK;
auto fail = [&](const std::string& m, int code) { *why = m; st = code; };
do {
if (!cx || !fr || !pk) { fail("out of memory", RAD_E_NOMEM); break; }
cx->width = w;
cx->height = h;
cx->pix_fmt = pf;
cx->time_base = AVRational{ 1, 25 };
cx->color_range = format == "jpeg" ? AVCOL_RANGE_JPEG : AVCOL_RANGE_UNSPECIFIED;
if (format == "jpeg") {
const int q = quality > 0 && quality <= 100 ? quality : 90;
/* qscale 2 (best) .. 31 (worst), linear in the quality */
const int qs = 2 + (100 - q) * 29 / 100;
cx->flags |= AV_CODEC_FLAG_QSCALE;
cx->global_quality = FF_QP2LAMBDA * qs;
}
/* PNG AT zlib LEVEL 1 WITH PER-ROW PREDICTION: a 2048^2 picture in 0.16 s and 5.9 MB, where
* the encoder's default (level 6) takes 1.0 s for 5.3 MB -- a second of a few-step image
* model's request, on one core, for a tenth of the bytes. */
if (format == "png") {
cx->compression_level = 1;
av_opt_set(cx->priv_data, "pred", "mixed", 0);
}
if (format == "webp") {
const int q = quality > 0 && quality <= 100 ? quality : 90;
if (q >= 100) av_opt_set_int(cx->priv_data, "lossless", 1, 0);
else av_opt_set_double(cx->priv_data, "quality", (double)q, 0);
}
int r = avcodec_open2(cx, codec, nullptr);
if (r < 0) { fail("the " + format + " encoder would not open (" + averr(r) + ")", RAD_E_INVAL); break; }
fr->format = pf;
fr->width = w;
fr->height = h;
if (av_frame_get_buffer(fr, 0) < 0) { fail("out of memory", RAD_E_NOMEM); break; }
const AVPixelFormat src = ch == 4 ? AV_PIX_FMT_RGBA : AV_PIX_FMT_RGB24;
sws = sws_getContext(w, h, src, w, h, pf, SWS_BILINEAR | SWS_ACCURATE_RND, nullptr,
nullptr, nullptr);
if (!sws) { fail("no colour conversion to the encoder's format", RAD_E_UNSUPPORTED); break; }
if (format == "jpeg")
sws_setColorspaceDetails(sws, sws_getCoefficients(SWS_CS_DEFAULT), 1,
sws_getCoefficients(SWS_CS_ITU601), 1, 0, 1 << 16, 1 << 16);
const uint8_t* sp[1] = { px };
const int sl[1] = { w * ch };
if (sws_scale(sws, sp, sl, 0, h, fr->data, fr->linesize) != h) {
fail("colour conversion failed", RAD_E_INVAL);
break;
}
fr->pts = 0;
r = avcodec_send_frame(cx, fr);
if (r >= 0) r = avcodec_send_frame(cx, nullptr);
if (r < 0) { fail("encoding failed (" + averr(r) + ")", RAD_E_INVAL); break; }
out->clear();
for (;;) {
r = avcodec_receive_packet(cx, pk);
if (r == AVERROR_EOF || r == AVERROR(EAGAIN)) break;
if (r < 0) { fail("encoding failed (" + averr(r) + ")", RAD_E_INVAL); break; }
out->insert(out->end(), pk->data, pk->data + pk->size);
av_packet_unref(pk);
}
if (st == RAD_OK && out->empty()) fail("the encoder wrote nothing", RAD_E_INVAL);
} while (false);
sws_freeContext(sws);
av_packet_free(&pk);
av_frame_free(&fr);
avcodec_free_context(&cx);
return st;
}
int decode_video(const uint8_t* data, size_t n, SampleFn sample, const void* user,
int64_t max_pixels, Video* out, std::string* why) {
std::string w;
+17
View File
@@ -27,6 +27,13 @@ struct Frame {
std::vector<uint8_t> rgb; /* [h, w, 3] */
};
/* A picture with its alpha: packed 8-bit RGBA, row-major, no padding -- what an image generator
* reads and writes. A source without alpha comes back opaque. */
struct FrameRGBA {
int32_t w = 0, h = 0;
std::vector<uint8_t> rgba; /* [h, w, 4] */
};
/* Is there a decoder in this build. */
bool decoder_available();
@@ -34,6 +41,16 @@ bool decoder_available();
* `max_pixels` in the SOURCE, which is what bounds the memory a request can make the server
* allocate before any resize happens. */
int decode_image(const uint8_t* data, size_t n, int64_t max_pixels, Frame* out, std::string* why);
/* The same, keeping the alpha channel. */
int decode_image_rgba(const uint8_t* data, size_t n, int64_t max_pixels, FrameRGBA* out,
std::string* why);
/* A PICTURE TO A FILE: `px` is [h, w, ch] 8-bit, ch 3 (RGB) or 4 (RGBA), and `format` one of png,
* jpeg and webp. `quality` 0..100 is jpeg's and lossy webp's (0 or above 100: the format's own
* default); png is lossless and webp is lossless at 100. jpeg has no alpha and is refused one.
* RAD_E_UNSUPPORTED, with the reason, for a format this build has no encoder for. */
int encode_image(const uint8_t* px, int32_t w, int32_t h, int32_t ch, const std::string& format,
int32_t quality, std::vector<uint8_t>* out, std::string* why);
/* HOW A VIDEO IS SAMPLED, and it happens INSIDE the decode rather than after it: a minute of 1080p
* is 10 GB of RGB, so frames that are not sampled are never converted or kept. The choice of which
+10
View File
@@ -380,6 +380,16 @@ public:
/* ...and the audio encoder, the second a program may declare (RAD_MM_AUDIO). */
RadEncoderDecl audio_encoder{};
std::string audio_encoder_name;
/* THE IMAGE GENERATOR THIS PLUGIN DECLARED (rad_declare_generator); `layout` 0 when it declared
* none. The strings and the fixed schedule it points at are the copies below, not the plugin's
* storage. A generator program has no logits and no pooled vectors. */
RadGeneratorDecl generator{};
struct GenStrings {
std::string name, tmpl_text, tmpl_edit, tmpl_image, tmpl_image_sep, drop_prefix,
tmpl_transparent;
std::vector<double> sigmas;
} gen_str;
bool is_generator() const { return generator.layout != 0; }
/* Two arenas, because a host-site activation cannot index device memory. The buffer plan
* colours the domains SEPARATELY -- a transient may share storage only with a transient in the
+13 -2
View File
@@ -994,6 +994,14 @@ int Ctx::lane_init() {
/* Local: a lane join orders one card's two queues and nothing else reads through it. */
for (int i = 0; i < 2; ++i)
if (!lane_ev_[i]) RAD_TRY(rad_event_create_local(&lane_ev_[i]));
/* A NEW LANE STARTS BEHIND EVERYTHING LANE 0 HAS ISSUED. Its first use is mid-step, and the
* join an architecture puts in front of it -- rad_lane_join(0, 1), then rad_lane(1) -- found no
* lane 1 to order and returned without doing anything. Unordered, the first op on the new
* stream reads lane 0's output before lane 0 has written it: on Qwen-Image's two-rank pass
* the first picture after startup took its first all-reduce of stale rows and came out a
* different picture, every later one the right one. */
RAD_TRY(rad_event_record(lane_ev_[0], stream_));
RAD_TRY(rad_event_wait(lane1_, lane_ev_[0]));
return RAD_OK;
}
@@ -1008,8 +1016,9 @@ int Ctx::set_lane(int lane) {
int Ctx::lane_join(int from, int to) {
if (from == to) return RAD_OK;
if (from < 0 || from > 1 || to < 0 || to > 1) return RAD_E_INVAL;
/* Nothing was ever issued on lane 1, so there is nothing to order against. This is the arm
* every unpipelined step takes at the end of run_step, and it must not build a stream. */
/* Nothing was ever issued on lane 1, so there is nothing to order against -- and a lane 1
* built later starts behind lane 0 (lane_init). This is the arm every unpipelined step takes
* at the end of run_step, and it must not build a stream. */
if (!lane1_) return RAD_OK;
RadStream fs = from ? lane1_ : stream_, ts = to ? lane1_ : stream_;
RAD_TRY(rad_event_record(lane_ev_[from], fs));
@@ -1025,6 +1034,8 @@ uint64_t Ctx::pass_key(const RadBatch* b) const {
/* An encoder pass is shaped by its media, and a pass that carries encoder rows issues the
* scatter that puts them in place only when it has some: neither repeats as a tape would. */
if (b->enc || b->n_mm_rows > 0) return 0;
/* A generator pass is shaped by what RadBatch::gen_b carries, which no key below reads. */
if (b->gen) return 0;
uint64_t h = 0x9e3779b97f4a7c15ull;
auto mix = [&](uint64_t v) {
h ^= v + 0x9e3779b97f4a7c15ull + (h << 6) + (h >> 2);
+8 -3
View File
@@ -429,12 +429,17 @@ json Server::capabilities() const {
caps["chat"] = deps_.chat != nullptr;
caps["tools"] = deps_.chat && deps_.chat->supports_tools();
caps["reasoning"] = deps_.chat && deps_.chat->supports_reasoning();
caps["grammar"] = deps_.grammar != nullptr;
/* An image model reads pictures for its edits and nothing else, and writes no text a grammar
* could constrain -- whatever its conditioning network's processor would take. */
const bool img = opt_.image_model;
caps["grammar"] = !img && deps_.grammar != nullptr;
caps["embedding"] = deps_.embed != nullptr;
caps["image"] = deps_.mm && deps_.mm->accepts(MediaKind::Image);
caps["video"] = deps_.mm && deps_.mm->accepts(MediaKind::Video);
caps["audio"] = deps_.mm && deps_.mm->accepts(MediaKind::Audio);
caps["video"] = !img && deps_.mm && deps_.mm->accepts(MediaKind::Video);
caps["audio"] = !img && deps_.mm && deps_.mm->accepts(MediaKind::Audio);
caps["logprobs"] = opt_.supports_logprobs;
caps["image_generation"] = deps_.images != nullptr;
caps["image_edit"] = deps_.images != nullptr && deps_.images->info().max_refs > 0;
/* THE EFFORTS A CHAT REQUEST MAY SEND, as probed from the template at startup: null when it
* takes any word. "none" and "minimal" are this server's, and turn thinking off. */
if (lim_.reasoning_efforts.empty()) {
+17 -6
View File
@@ -406,11 +406,12 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) {
};
auto bridge = [&router](const httplib::Request& hreq, std::string body,
httplib::Response& hres) {
httplib::Response& hres, std::vector<FormPart> form = {}) {
HttpRequest req;
req.method = hreq.method;
req.path = hreq.path;
req.body = std::move(body);
req.form = std::move(form);
req.peer = hreq.remote_addr + ":" + std::to_string(hreq.remote_port);
req.t_received_ns = std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::steady_clock::now().time_since_epoch()).count();
@@ -459,14 +460,24 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) {
/* A POST BODY IS READ STRAIGHT INTO THE STRING THE HANDLER PARSES. Left to httplib it
* lands in its own Request first, which only hands it out const, so it would be copied
* into ours: a body at the size limit held twice before a byte of it is looked at. A
* multipart body is not read at all -- no endpoint takes one, and httplib discards what a
* handler leaves unread -- so the handler sees an empty body and refuses it. */
* multipart body (an image upload) is read as its parts, each straight into its own
* string, under the same size limit. */
svr.Post(path, [gate, bridge](const httplib::Request& q, httplib::Response& s,
const httplib::ContentReader& read) {
if (!gate(q, s)) return;
std::string body;
if (!q.is_multipart_form_data() &&
!read([&body](const char* p, size_t n) { body.append(p, n); return true; })) {
std::vector<FormPart> form;
const bool ok = q.is_multipart_form_data()
? read([&form](const httplib::FormData& f) {
form.push_back(FormPart{ f.name, f.filename, f.content_type, {} });
return true;
},
[&form](const char* p, size_t n) {
if (!form.empty()) form.back().data.append(p, n);
return true;
})
: read([&body](const char* p, size_t n) { body.append(p, n); return true; });
if (!ok) {
/* httplib has already set 413 for a body over the limit; anything else is a peer
* that stopped sending partway, which has to be answered as something. */
if (s.status < 0) {
@@ -477,7 +488,7 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) {
}
return;
}
bridge(q, std::move(body), s);
bridge(q, std::move(body), s, std::move(form));
});
}
/* THE PREFLIGHT ALLOWS WHATEVER HEADERS IT IS ASKED ABOUT. A browser client sends more than
+7
View File
@@ -24,10 +24,17 @@ struct CiLess {
bool operator()(const std::string& a, const std::string& b) const;
};
/* One part of a multipart/form-data body: a field's value, or an uploaded file's bytes. */
struct FormPart {
std::string name, filename, content_type, data;
};
struct HttpRequest {
std::string method = "GET";
std::string path; /* no query string */
std::string body;
/* A multipart/form-data body arrives as its parts, in order, and `body` is empty. */
std::vector<FormPart> form;
std::map<std::string, std::string, CiLess> headers;
std::map<std::string, std::string> query;
std::map<std::string, std::string> params; /* from a ":name" route segment */
+31
View File
@@ -23,6 +23,8 @@
#include <vector>
namespace rad {
namespace gen { struct Request; }
namespace mm { struct Frame; struct Item; }
namespace server {
/* ordered_json, not json, and the reason is not cosmetic: a tool's parameter schema is rendered
@@ -594,5 +596,34 @@ public:
};
/* THE IMAGE GENERATOR (core/gen), for a model that makes pictures rather than text: what the
* model declared about its prompts and sizes, and the queue a request goes into. The server turns
* an OpenAI images request into a gen::Request -- the prompt rendered and tokenised, the reference
* pictures resized for both of the model's readers -- and reads the pictures back off its ticket. */
struct ImageGenInfo {
std::string name, tmpl_text, tmpl_edit, tmpl_image, tmpl_image_sep, drop_prefix,
tmpl_transparent;
int64_t latent_scale = 16, size_multiple = 32, pixel_channels = 4, max_tokens = 0;
int64_t max_refs = 0, ref_area = 0, default_width = 0, default_height = 0;
int64_t default_steps = 0, max_lanes = 1, max_cond_tokens = 0;
/* The model samples on a schedule of its own and takes no step count (a distilled model). */
bool fixed_schedule = false;
int64_t fixed_steps = 0;
double default_cfg = 1.0;
};
class IImageGen {
public:
virtual ~IImageGen() = default;
virtual const ImageGenInfo& info() const = 0;
/* Queue a request; refused at once, with `why`, when it can never run. */
virtual int submit(std::unique_ptr<gen::Request> r, std::string* why) = 0;
/* A reference picture as the conditioning network's encoder reads it: RGB at the size it was
* resized to, which the processor must not change. */
virtual int picture(const mm::Frame& f, std::shared_ptr<mm::Item>* out, std::string* why) = 0;
virtual int64_t queued() const = 0;
virtual int64_t running() const = 0;
};
} /* namespace server */
} /* namespace rad */
+731
View File
@@ -0,0 +1,731 @@
/* images.cpp -- OpenAI's images API over an image generator (core/gen): /v1/images/generations
* and /v1/images/edits.
*
* WHAT A REQUEST BECOMES. The prompt goes into the model's own template (ImageGenInfo), with the
* fixed system turn the generator drops; a transparent background asks for one in the words the
* model was trained on. An edit's pictures are each resized to the model's reference area at their
* own aspect -- with PIL's premultiplied Lanczos, as diffusers resizes them -- and read twice: as
* RGBA pixels by the generator's encoder, and composited on white by the conditioning network's.
* With a mask, the first picture is repainted: the mask's transparent pixels are where it may
* change, the rest is put back exactly after decoding.
*
* WHAT IS EXTENDED, beside OpenAI's fields, by vLLM-Omni's names: `seed`, `negative_prompt` with
* `true_cfg_scale` (guidance), `num_inference_steps`, and `width` / `height` in place of `size`.
* A model with a fixed schedule (a distilled one) takes no step count but its own.
*
* WHAT IS REFUSED: `response_format: url` -- nothing here stores an image to serve later, so the
* picture comes back in the response (b64_json) or not at all.
*
* STREAMING is OpenAI's: `image_generation.partial_image` (`image_edit.partial_image`) events
* for the `partial_images` previews -- the step's estimate of the finished latent, decoded -- and
* one `.completed` event an image.
*/
#include "server.h"
#include "oai.h"
#include "gen/gen.h"
#include "mm/imaging.h"
#include "mm/media.h"
#include "mm/processor.h"
#include "rad_internal.h"
#include <nlohmann/json.hpp>
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstring>
#include <ctime>
#include <random>
namespace rad {
namespace server {
namespace {
/* The largest picture a request may upload, before any resize. */
constexpr int64_t kMaxSourcePixels = (int64_t)1 << 26;
/* Below this alpha a pixel is transparent: where a mask lets the picture change, and what makes a
* picture one with transparency. A decoder's alpha is not exactly 255 on an opaque picture, so a
* picture this model made and is given back to edit stays opaque. */
constexpr uint8_t kTransparentBelow = 128;
struct ImgReq {
bool edit = false;
std::string prompt, negative;
bool has_neg = false;
double cfg = 1.0;
int32_t w = 0, h = 0, n = 1, steps = 0, previews = 0;
bool seed_given = false;
uint64_t seed = 0;
std::string background = "auto", format = "png", quality = "auto";
int32_t compression = -1;
bool stream = false;
std::vector<mm::FrameRGBA> images;
bool has_mask = false;
mm::FrameRGBA mask;
};
/* A multipart field's text as the JSON value the same field takes in a JSON body. */
json form_value(const std::string& key, const std::string& v) {
static const char* ints[] = { "n", "seed", "num_inference_steps", "partial_images",
"output_compression", "width", "height" };
for (const char* k : ints)
if (key == k) {
char* e = nullptr;
const long long x = std::strtoll(v.c_str(), &e, 10);
if (e && *e == 0 && !v.empty()) return json(x);
return json(v);
}
if (key == "true_cfg_scale") {
char* e = nullptr;
const double x = std::strtod(v.c_str(), &e);
if (e && *e == 0 && !v.empty()) return json(x);
return json(v);
}
if (key == "stream") {
if (v == "true" || v == "1") return json(true);
if (v == "false" || v == "0") return json(false);
}
return json(v);
}
/* diffusers' calculate_dimensions: a target area at an aspect, each side rounded to 32. */
void dims_for(double area, double ratio, int32_t mult, int32_t* w, int32_t* h) {
const double wd = std::sqrt(area * ratio);
const double hd = wd / ratio;
*w = (int32_t)std::lround(wd / mult) * mult;
*h = (int32_t)std::lround(hd / mult) * mult;
if (*w < mult) *w = mult;
if (*h < mult) *h = mult;
}
std::string replace_all(std::string s, const std::string& what, const std::string& with) {
for (size_t p = s.find(what); p != std::string::npos; p = s.find(what, p + with.size()))
s.replace(p, what.size(), with);
return s;
}
uint16_t f32_bf16(float f) {
uint32_t u;
std::memcpy(&u, &f, 4);
u += 0x7FFFu + ((u >> 16) & 1u);
return (uint16_t)(u >> 16);
}
/* A picture as the generator's encoder reads it: each channel u -> 2 * (u / 255) - 1 in f32, then
* bf16 -- VaeImageProcessor's preprocess, cast to the VAE's dtype. */
gen::Pixels to_pixels(const mm::FrameRGBA& f) {
gen::Pixels p;
p.w = f.w;
p.h = f.h;
p.ch = 4;
p.bf16.resize(f.rgba.size());
for (size_t i = 0; i < f.rgba.size(); ++i)
p.bf16[i] = f32_bf16(2.0f * ((float)f.rgba[i] / 255.0f) - 1.0f);
return p;
}
/* The decoded RGBA flattened on white (no alpha), for a jpeg or an opaque background. */
std::vector<uint8_t> on_white(const std::vector<uint8_t>& rgba, int32_t w, int32_t h) {
mm::FrameRGBA f;
f.w = w;
f.h = h;
f.rgba = rgba;
mm::Frame o;
mm::composite_white(f, &o);
return std::move(o.rgb);
}
} /* namespace */
HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
if (!deps_.images || !deps_.tok)
return error_response(err_not_implemented(
"the images API requires an image generation model; this one generates text"),
req.peer);
const ImageGenInfo& info = deps_.images->info();
const char* ep = edit ? "/v1/images/edits" : "/v1/images/generations";
if (edit && info.max_refs <= 0)
return error_response(err_not_implemented("this model makes images from text only"),
req.peer);
/* ---- the body, JSON or (an edit's usual form) multipart, as one JSON object */
json body = json::object();
std::vector<std::vector<uint8_t>> files;
std::vector<uint8_t> mask_bytes;
bool have_mask = false;
if (!req.form.empty()) {
for (const FormPart& p : req.form) {
if (p.name == "image" || p.name == "image[]") {
files.emplace_back(p.data.begin(), p.data.end());
} else if (p.name == "mask") {
mask_bytes.assign(p.data.begin(), p.data.end());
have_mask = true;
} else {
body[p.name] = form_value(p.name, p.data);
}
}
} else {
try {
body = json::parse(req.body);
} catch (const std::exception& e) {
return error_response(err_bad("", std::string("the body is not JSON: ") + e.what()),
req.peer);
}
if (!body.is_object()) return error_response(err_bad("", "the body is not a JSON object"), req.peer);
/* An edit's pictures as JSON: `images: [{image_url: "data:..."}]` and `mask: {image_url}`,
* the newer form of the API, or `image` as one data URL or a list of them. */
auto url_of = [](const json& v, std::string* u) {
if (v.is_string()) { *u = v.get<std::string>(); return true; }
if (v.is_object() && v.contains("image_url") && v["image_url"].is_string()) {
*u = v["image_url"].get<std::string>();
return true;
}
if (v.is_object() && v.contains("image_url") && v["image_url"].is_object() &&
v["image_url"].contains("url") && v["image_url"]["url"].is_string()) {
*u = v["image_url"]["url"].get<std::string>();
return true;
}
return false;
};
for (const char* key : { "images", "image" }) {
if (!body.contains(key)) continue;
const json v = body[key];
body.erase(key);
std::vector<json> list;
if (v.is_array()) list.assign(v.begin(), v.end());
else list.push_back(v);
for (const json& e : list) {
std::string u;
if (!url_of(e, &u))
return error_response(err_bad(key, "a picture is a data: URL, or an object "
"with an image_url"), req.peer);
std::vector<uint8_t> bytes;
ApiError err;
if (decode_media_url(u, key, &bytes, &err) < 0) return error_response(err, req.peer);
files.push_back(std::move(bytes));
}
}
if (body.contains("mask")) {
std::string u;
if (!url_of(body["mask"], &u))
return error_response(err_bad("mask", "the mask is a data: URL, or an object with "
"an image_url"), req.peer);
body.erase("mask");
ApiError err;
if (decode_media_url(u, "mask", &mask_bytes, &err) < 0)
return error_response(err, req.peer);
have_mask = true;
}
}
/* ---- the fields */
ImgReq r;
r.edit = edit;
static const char* kKnown[] = {
"prompt", "model", "n", "size", "quality", "background", "output_format",
"output_compression", "response_format", "stream", "partial_images", "moderation",
"style", "user", "input_fidelity", "seed", "negative_prompt", "true_cfg_scale",
"num_inference_steps", "width", "height",
};
for (auto it = body.begin(); it != body.end(); ++it) {
bool known = false;
for (const char* k : kKnown) known = known || it.key() == k;
if (!known)
return error_response(err_bad(it.key(), "'" + it.key() + "' is not a field of " +
std::string(ep)), req.peer);
}
auto str = [&](const char* k, std::string* out) -> int {
if (!body.contains(k) || body[k].is_null()) return 0;
if (!body[k].is_string()) return -1;
*out = body[k].get<std::string>();
return 1;
};
auto num = [&](const char* k, int64_t lo, int64_t hi, int64_t* out) -> int {
if (!body.contains(k) || body[k].is_null()) return 0;
if (!body[k].is_number_integer()) return -1;
const int64_t v = body[k].get<int64_t>();
if (v < lo || v > hi) return -1;
*out = v;
return 1;
};
if (str("prompt", &r.prompt) < 0)
return error_response(err_bad("prompt", "a string"), req.peer);
if (!body.contains("prompt"))
return error_response(err_bad("prompt", "the prompt is required"), req.peer);
if (r.prompt.empty()) r.prompt = " ";
std::string rf;
if (str("response_format", &rf) < 0 || (!rf.empty() && rf != "b64_json" && rf != "url"))
return error_response(err_bad("response_format", "b64_json"), req.peer);
if (rf == "url") {
ApiError e = err_unsupported("response_format",
"url is not served: this server keeps no image to serve "
"later; ask for b64_json");
e.supported = { "b64_json" };
return error_response(e, req.peer);
}
int64_t v = 0;
if (num("n", 1, info.max_lanes, &v) < 0)
return error_response(err_bad("n", "1.." + std::to_string(info.max_lanes)), req.peer);
r.n = body.contains("n") && !body["n"].is_null() ? (int32_t)v : 1;
if (str("background", &r.background) < 0 ||
(r.background != "auto" && r.background != "transparent" && r.background != "opaque")) {
ApiError e = err_bad("background", "auto, transparent or opaque");
e.supported = { "auto", "transparent", "opaque" };
return error_response(e, req.peer);
}
if (str("output_format", &r.format) < 0 ||
(r.format != "png" && r.format != "jpeg" && r.format != "webp")) {
ApiError e = err_bad("output_format", "png, jpeg or webp");
e.supported = { "png", "jpeg", "webp" };
return error_response(e, req.peer);
}
if (r.background == "transparent" && r.format == "jpeg")
return error_response(err_bad("background", "jpeg has no transparency; ask for png or "
"webp"), req.peer);
if (num("output_compression", 0, 100, &v) < 0)
return error_response(err_bad("output_compression", "0..100"), req.peer);
if (body.contains("output_compression")) r.compression = (int32_t)v;
if (body.contains("stream") && !body["stream"].is_null()) {
if (!body["stream"].is_boolean()) return error_response(err_bad("stream", "a boolean"), req.peer);
r.stream = body["stream"].get<bool>();
}
if (num("partial_images", 0, 3, &v) < 0)
return error_response(err_bad("partial_images", "0..3"), req.peer);
if (body.contains("partial_images")) r.previews = (int32_t)v;
if (r.previews > 0 && !r.stream)
return error_response(err_bad("partial_images", "partial images are sent on a stream; "
"set stream"), req.peer);
if (str("quality", &r.quality) < 0 ||
(r.quality != "auto" && r.quality != "low" && r.quality != "medium" &&
r.quality != "high" && r.quality != "standard" && r.quality != "hd")) {
ApiError e = err_bad("quality", "auto, low, medium, high (standard, hd)");
e.supported = { "auto", "low", "medium", "high", "standard", "hd" };
return error_response(e, req.peer);
}
/* The step count: the request's, or what its quality asks for, or the model's. */
int64_t steps = 0;
if (num("num_inference_steps", 1, 200, &steps) < 0)
return error_response(err_bad("num_inference_steps", "1..200"), req.peer);
if (info.fixed_schedule) {
if (steps != 0 && steps != info.fixed_steps)
return error_response(err_unsupported("num_inference_steps",
"this model samples on its own " +
std::to_string(info.fixed_steps) +
"-step schedule and takes no other"),
req.peer);
steps = 0;
} else if (steps == 0) {
if (r.quality == "low") steps = std::max<int64_t>(1, info.default_steps / 2);
else if (r.quality == "medium") steps = std::max<int64_t>(1, info.default_steps * 3 / 4);
}
r.steps = (int32_t)steps;
if (body.contains("seed") && !body["seed"].is_null()) {
if (!body["seed"].is_number_integer())
return error_response(err_bad("seed", "an integer"), req.peer);
r.seed = (uint64_t)body["seed"].get<int64_t>();
r.seed_given = true;
}
if (str("negative_prompt", &r.negative) < 0)
return error_response(err_bad("negative_prompt", "a string"), req.peer);
if (body.contains("true_cfg_scale") && !body["true_cfg_scale"].is_null()) {
if (!body["true_cfg_scale"].is_number())
return error_response(err_bad("true_cfg_scale", "a number"), req.peer);
r.cfg = body["true_cfg_scale"].get<double>();
if (!(r.cfg >= 1.0 && r.cfg <= 30.0))
return error_response(err_bad("true_cfg_scale", "1..30"), req.peer);
}
/* Guidance needs both halves, as the reference pipeline does: a scale above one and a
* negative prompt (an empty one is " "). */
r.has_neg = r.cfg > 1.0 && body.contains("negative_prompt");
if (r.has_neg && r.negative.empty()) r.negative = " ";
if (r.cfg > 1.0 && !r.has_neg)
return error_response(err_bad("true_cfg_scale", "guidance needs a negative_prompt"),
req.peer);
/* ---- the pictures */
if (edit) {
if (files.empty())
return error_response(err_bad("image", "an edit needs at least one picture"), req.peer);
if ((int64_t)files.size() > info.max_refs)
return error_response(err_bad("image", "at most " + std::to_string(info.max_refs) +
" pictures"), req.peer);
for (size_t i = 0; i < files.size(); ++i) {
mm::FrameRGBA f;
std::string why;
if (mm::decode_image_rgba(files[i].data(), files[i].size(), kMaxSourcePixels, &f,
&why) < 0)
return error_response(err_bad("image", "picture " + std::to_string(i + 1) +
": " + why), req.peer);
r.images.push_back(std::move(f));
}
if (have_mask) {
std::string why;
if (mm::decode_image_rgba(mask_bytes.data(), mask_bytes.size(), kMaxSourcePixels,
&r.mask, &why) < 0)
return error_response(err_bad("mask", why), req.peer);
if (r.mask.w != r.images[0].w || r.mask.h != r.images[0].h)
return error_response(err_bad("mask", "the mask must be the first picture's "
"size"), req.peer);
r.has_mask = true;
}
} else if (!files.empty() || have_mask) {
return error_response(err_bad("image", "pictures go to /v1/images/edits"), req.peer);
}
/* `auto` is decided by what was sent: an edit of a picture with transparency keeps it, and
* anything else is opaque -- a picture made without asking for transparency carries only the
* decoder's noise in its alpha. */
if (r.background == "auto") {
bool alpha = false;
if (r.format != "jpeg")
for (const mm::FrameRGBA& f : r.images)
for (size_t i = 3; i < f.rgba.size() && !alpha; i += 4)
alpha = f.rgba[i] < kTransparentBelow;
r.background = alpha ? "transparent" : "opaque";
}
/* ---- the size: `width`/`height`, or `size` "WxH", or auto -- the native size, at the last
* picture's aspect for an edit. Sides are rounded down to the model's multiple. */
const int32_t mult = (int32_t)info.size_multiple;
std::string size = "auto";
if (str("size", &size) < 0) return error_response(err_bad("size", "\"WxH\" or \"auto\""), req.peer);
int64_t bw = 0, bh = 0;
if (num("width", 1, 16384, &bw) < 0 || num("height", 1, 16384, &bh) < 0)
return error_response(err_bad("width", "1..16384"), req.peer);
if ((bw > 0) != (bh > 0))
return error_response(err_bad(bw ? "height" : "width", "width and height go together"),
req.peer);
if (bw > 0) {
r.w = (int32_t)bw;
r.h = (int32_t)bh;
} else if (size != "auto") {
int a = 0, b = 0;
char x = 0;
if (std::sscanf(size.c_str(), "%d%c%d", &a, &x, &b) != 3 || x != 'x' || a <= 0 || b <= 0)
return error_response(err_bad("size", "\"WxH\" or \"auto\""), req.peer);
r.w = a;
r.h = b;
} else if (edit) {
const mm::FrameRGBA& last = r.images.back();
dims_for((double)info.default_width * info.default_height,
(double)last.w / (double)last.h, mult, &r.w, &r.h);
} else {
r.w = (int32_t)info.default_width;
r.h = (int32_t)info.default_height;
}
r.w = r.w / mult * mult;
r.h = r.h / mult * mult;
if (r.w <= 0 || r.h <= 0)
return error_response(err_bad("size", "each side at least " + std::to_string(mult) +
" pixels"), req.peer);
const int64_t ls = info.latent_scale;
if ((r.w / ls) * (r.h / ls) > info.max_tokens)
return error_response(err_bad("size", std::to_string(r.w) + "x" + std::to_string(r.h) +
" is larger than this model makes (" +
std::to_string(info.max_tokens * ls * ls) +
" pixels)"), req.peer);
if (!r.seed_given) {
/* 53 bits: the seed goes back in the response to be sent again, and a JavaScript client
* reads a JSON number as a double -- a 64-bit seed would come back as another picture. */
std::random_device rd;
r.seed = (((uint64_t)rd() << 32) ^ rd()) & (((uint64_t)1 << 53) - 1);
}
/* ---- the request: prompts rendered and tokenised, pictures resized */
auto g = std::make_unique<gen::Request>();
g->width = r.w;
g->height = r.h;
g->n = r.n;
g->steps = r.steps;
g->seed = r.seed;
g->previews = r.previews;
g->cfg = (float)r.cfg;
g->has_neg = r.has_neg;
g->ticket = std::make_shared<gen::Ticket>();
std::vector<std::shared_ptr<mm::Item>> items;
for (const mm::FrameRGBA& f : r.images) {
int32_t rw = 0, rh = 0;
dims_for((double)info.ref_area, (double)f.w / (double)f.h, mult, &rw, &rh);
mm::FrameRGBA rs;
mm::resize_lanczos_rgba(f, rw, rh, &rs);
g->refs.push_back(to_pixels(rs));
mm::Frame rgb;
mm::composite_white(rs, &rgb);
std::shared_ptr<mm::Item> it;
std::string why;
if (deps_.images->picture(rgb, &it, &why) < 0 || !it)
return error_response(err_bad("image", "the picture could not be used: " + why),
req.peer);
items.push_back(std::move(it));
}
/* Repainting: the first picture at the size being made, and per latent token the share of
* its 16 x 16 pixels the mask leaves transparent -- those are repainted, the rest kept. */
std::vector<uint8_t> keep_px, src_px;
if (r.has_mask) {
mm::FrameRGBA src, msk;
mm::resize_lanczos_rgba(r.images[0], r.w, r.h, &src);
mm::resize_lanczos_rgba(r.mask, r.w, r.h, &msk);
g->inpaint = true;
g->inp_src = to_pixels(src);
const int32_t lw = r.w / (int32_t)ls, lh = r.h / (int32_t)ls;
g->inp_mask.assign((size_t)lw * lh, 0.0f);
keep_px.assign((size_t)r.w * r.h, 0);
for (int32_t y = 0; y < r.h; ++y)
for (int32_t x = 0; x < r.w; ++x) {
const bool edit_px = msk.rgba[((size_t)y * r.w + x) * 4 + 3] < kTransparentBelow;
keep_px[(size_t)y * r.w + x] = edit_px ? 0 : 1;
if (edit_px) g->inp_mask[(size_t)(y / ls) * lw + x / ls] += 1.0f;
}
for (float& m : g->inp_mask) m /= (float)(ls * ls);
src_px = std::move(src.rgba);
}
auto render = [&](const std::string& prompt, gen::Branch* out, ApiError* err) -> int {
std::string text = r.background == "transparent" && !info.tmpl_transparent.empty()
? replace_all(info.tmpl_transparent, "{prompt}", prompt)
: prompt;
std::string tmpl = edit ? info.tmpl_edit : info.tmpl_text;
if (edit) {
std::string imgs;
for (size_t i = 0; i < items.size(); ++i) {
if (i) imgs += info.tmpl_image_sep;
imgs += replace_all(replace_all(info.tmpl_image, "{n}", std::to_string(i + 1)),
"{image}", RAD_MEDIA_MARKER);
}
tmpl = replace_all(tmpl, "{images}", imgs);
}
const std::string rendered = replace_all(tmpl, "{prompt}", text);
/* Tokenised piece by piece around the markers, each marker replaced by its picture's
* token run -- the chat path's tokenize_with_media, with pictures already processed. */
auto pm = std::make_shared<mm::PromptMedia>();
size_t pos = 0, mi = 0;
for (;;) {
const size_t at = rendered.find(RAD_MEDIA_MARKER, pos);
const std::string seg = rendered.substr(pos, at == std::string::npos ? std::string::npos
: at - pos);
if (!seg.empty()) {
auto ids = deps_.tok->encode(seg, false, /*parse_special=*/true);
out->tokens.insert(out->tokens.end(), ids.begin(), ids.end());
}
if (at == std::string::npos) break;
mm::Placed pl;
pl.item = items[mi++];
pl.tok = (int32_t)out->tokens.size();
out->tokens.insert(out->tokens.end(), pl.item->expand.begin(), pl.item->expand.end());
pm->items.push_back(std::move(pl));
pos = at + std::strlen(RAD_MEDIA_MARKER);
}
if (!pm->items.empty()) {
pm->layout();
out->media = std::move(pm);
}
/* The fixed turn the generator does not see, which must be where the prompt starts. */
const auto drop = deps_.tok->encode(info.drop_prefix, false, true);
if (drop.size() > out->tokens.size() ||
!std::equal(drop.begin(), drop.end(), out->tokens.begin())) {
*err = err_bad("prompt", "the prompt does not start with the model's fixed turn");
err->status = 500;
return RAD_E_STATE;
}
out->n_drop = (int32_t)drop.size();
if ((int64_t)out->tokens.size() > info.max_cond_tokens) {
*err = err_bad("prompt", "the prompt is " + std::to_string(out->tokens.size()) +
" tokens with its pictures; this deployment conditions on "
"at most " + std::to_string(info.max_cond_tokens));
return RAD_E_INVAL;
}
return RAD_OK;
};
{
ApiError err;
if (render(r.prompt, &g->pos, &err) < 0) return error_response(err, req.peer);
if (r.has_neg && render(r.negative, &g->neg, &err) < 0)
return error_response(err, req.peer);
}
/* ---- admitted and queued */
sweep_abandoned();
if (!admit(1)) {
metrics_.observe_rejected();
return error_response(err_overloaded("the admission queue is full; retry after " +
std::to_string(opt_.retry_after_s) + "s"), req.peer);
}
std::shared_ptr<gen::Ticket> ticket = g->ticket;
{
std::string why;
const int s = deps_.images->submit(std::move(g), &why);
if (s < 0) {
release(1);
ApiError e = err_bad("", why.empty() ? std::string(rad_strerror(s)) : why);
if (s != RAD_E_INVAL) { e.status = 503; e.type = "server_error"; }
return error_response(e, req.peer);
}
}
RAD_INFO("images: %s %dx%d n=%d steps=%d seed=%llu%s%s%s", edit ? "edit" : "generation", r.w,
r.h, r.n, r.steps, (unsigned long long)r.seed, r.has_neg ? " guided" : "",
r.has_mask ? " masked" : "", r.stream ? " streamed" : "");
/* ---- one finished picture to a file */
const std::string size_s = std::to_string(r.w) + "x" + std::to_string(r.h);
const bool flatten = r.format == "jpeg" || r.background == "opaque";
const std::string fmt = r.format;
const int32_t comp = r.compression;
auto encode = [fmt, comp, keep_px, src_px, flatten](gen::Image& im, std::string* b64,
std::string* why) -> int {
std::vector<uint8_t>& px = im.px;
if (!keep_px.empty() && !im.preview)
for (size_t i = 0; i < keep_px.size(); ++i)
if (keep_px[i]) std::memcpy(&px[i * 4], &src_px[i * 4], 4);
std::vector<uint8_t> file;
int s;
if (flatten) {
const std::vector<uint8_t> rgb = on_white(px, im.w, im.h);
s = mm::encode_image(rgb.data(), im.w, im.h, 3, fmt, comp, &file, why);
} else {
s = mm::encode_image(px.data(), im.w, im.h, 4, fmt, comp, &file, why);
}
if (s < 0) return s;
*b64 = base64_encode(file.data(), file.size());
return RAD_OK;
};
const std::string bg_out = flatten ? "opaque" : "transparent";
/* The pictures' share of the input: their token runs, in every branch that carries them. */
int64_t image_tok = 0;
for (const auto& it : items) image_tok += (int64_t)it->expand.size();
if (r.has_neg) image_tok *= 2;
auto usage = [ticket, image_tok]() {
json u;
const int64_t in = ticket->in_tokens, out = ticket->out_tokens;
u["total_tokens"] = in + out;
u["input_tokens"] = in;
u["output_tokens"] = out;
u["input_tokens_details"] = json{ { "text_tokens", in - image_tok },
{ "image_tokens", image_tok } };
return u;
};
const int64_t created = (int64_t)std::time(nullptr);
if (!r.stream) {
std::vector<gen::Image> done;
for (;;) {
gen::Image im;
bool to = false;
if (ticket->next(&im, 200, &to)) {
if (!im.preview) done.push_back(std::move(im));
continue;
}
if (!to) break;
if (req.peer_gone()) {
ticket->cancel.store(true);
release(1);
metrics_.observe_http(499);
return HttpResponse::text(499, "client closed request\n");
}
if (stopping_.load()) {
ticket->cancel.store(true);
release(1);
return error_response(err_overloaded("the server is shutting down"), req.peer);
}
}
release(1);
if (ticket->status() < 0 || (int32_t)done.size() != r.n) {
/* RAD_E_INVAL is the driver's refusal at admission -- a request this deployment can
* never serve, such as a conditioning longer than the cache -- and the client's to
* change; anything else failed while it ran. */
ApiError e;
const bool client = ticket->status() == RAD_E_INVAL;
e.status = client ? 400 : 500;
e.type = client ? "invalid_request_error" : "server_error";
e.message = ticket->why().empty() ? "the image generator failed" : ticket->why();
return error_response(e, req.peer);
}
std::sort(done.begin(), done.end(),
[](const gen::Image& a, const gen::Image& b) { return a.index < b.index; });
json out;
out["created"] = created;
json data = json::array();
for (gen::Image& im : done) {
std::string b64, why;
if (encode(im, &b64, &why) < 0) {
ApiError e;
e.status = 500;
e.type = "server_error";
e.message = "the picture could not be encoded: " + why;
return error_response(e, req.peer);
}
data.push_back(json{ { "b64_json", std::move(b64) }, { "revised_prompt", r.prompt },
{ "seed", im.seed } });
}
out["data"] = std::move(data);
out["background"] = bg_out;
out["output_format"] = r.format;
out["quality"] = r.quality;
out["size"] = size_s;
out["usage"] = usage();
metrics_.observe_http(200);
return HttpResponse::json_body(200, json_dump(out));
}
/* ---- streamed: partial images as the previews arrive, a completed event an image */
HttpResponse res;
res.status = 200;
res.content_type = "text/event-stream";
res.set_header("Cache-Control", "no-cache");
const std::string kind = edit ? "image_edit" : "image_generation";
auto finished = std::make_shared<bool>(false);
auto released = std::make_shared<bool>(false);
const std::string quality = r.quality;
res.next = [this, ticket, kind, encode, created, size_s, bg_out, fmt, quality, usage, finished,
released](std::string& chunk) mutable -> bool {
if (*finished) return false;
gen::Image im;
bool to = false;
if (ticket->next(&im, 100, &to)) {
std::string b64, why;
json ev;
if (encode(im, &b64, &why) < 0) {
ev["type"] = "error";
ev["error"] = json{ { "message", "the picture could not be encoded: " + why } };
} else {
ev["type"] = kind + (im.preview ? ".partial_image" : ".completed");
ev["b64_json"] = std::move(b64);
ev["created_at"] = created;
ev["size"] = size_s;
ev["quality"] = quality;
ev["background"] = bg_out;
ev["output_format"] = fmt;
ev["index"] = im.index;
if (im.preview) ev["partial_image_index"] = im.preview_no;
else { ev["usage"] = usage(); ev["seed"] = im.seed; }
}
chunk = "event: " + ev["type"].get<std::string>() + "\ndata: " + json_dump(ev) + "\n\n";
return true;
}
if (to) { chunk.clear(); return !stopping_.load(); }
*finished = true;
if (!*released) { *released = true; release(1); }
if (ticket->status() < 0) {
json ev;
ev["type"] = "error";
ev["error"] = json{ { "message", ticket->why() },
{ "type", ticket->status() == RAD_E_INVAL ? "invalid_request_error"
: "server_error" } };
chunk = "event: error\ndata: " + json_dump(ev) + "\n\n";
return true;
}
chunk.clear();
return false;
};
res.on_close = [this, ticket, released](bool ok) {
if (!ok) ticket->cancel.store(true);
if (!*released) { *released = true; release(1); }
};
metrics_.observe_http(200);
return res;
}
} /* namespace server */
} /* namespace rad */
+32 -1
View File
@@ -137,6 +137,8 @@ void Server::register_routes() {
router_.post("/v1/chat/completions", [this](const HttpRequest& q) { return handle_chat(q); });
router_.post("/v1/completions", [this](const HttpRequest& q) { return handle_completion(q); });
router_.post("/v1/embeddings", [this](const HttpRequest& q) { return handle_embeddings(q); });
router_.post("/v1/images/generations", [this](const HttpRequest& q) { return handle_images(q, false); });
router_.post("/v1/images/edits", [this](const HttpRequest& q) { return handle_images(q, true); });
router_.post("/v1/systemone", [this](const HttpRequest& q) { return handle_systemone(q); });
router_.get ("/v1/models", [this](const HttpRequest& q) { return handle_models(q); });
router_.get ("/v1/models/:id", [this](const HttpRequest& q) { return handle_models(q); });
@@ -149,6 +151,8 @@ void Server::register_routes() {
router_.post("/completions", [this](const HttpRequest& q) { return handle_native_completion(q); });
router_.post("/infill", [this](const HttpRequest& q) { return handle_infill(q); });
router_.post("/embeddings", [this](const HttpRequest& q) { return handle_embeddings(q); });
router_.post("/images/generations", [this](const HttpRequest& q) { return handle_images(q, false); });
router_.post("/images/edits", [this](const HttpRequest& q) { return handle_images(q, true); });
router_.get ("/models", [this](const HttpRequest& q) { return handle_models(q); });
/* llama-server's: the prompt a chat request renders to, and how many tokens it is. */
router_.post("/apply-template", [this](const HttpRequest& q) { return handle_apply_template(q); });
@@ -1268,6 +1272,11 @@ HttpResponse Server::handle_chat(const HttpRequest& req) {
return error_response(err_not_implemented("this is an embedding model: it serves "
"/v1/embeddings and generates no text"),
req.peer);
if (opt_.image_model)
return error_response(err_not_implemented("this is an image model: it serves "
"/v1/images/generations and /v1/images/edits "
"and generates no text"),
req.peer);
OaiRequest r;
ApiError err;
@@ -1329,6 +1338,11 @@ HttpResponse Server::handle_messages(const HttpRequest& req) {
return error_response(err_not_implemented("this is an embedding model: it serves "
"/v1/embeddings and generates no text"),
req.peer, ApiShape::Anthropic);
if (opt_.image_model)
return error_response(err_not_implemented("this is an image model: it serves "
"/v1/images/generations and /v1/images/edits "
"and generates no text"),
req.peer, ApiShape::Anthropic);
std::string chat, label;
ApiError err;
OaiRequest r;
@@ -1363,6 +1377,11 @@ HttpResponse Server::handle_native_completion(const HttpRequest& req) {
return error_response(err_not_implemented("this is an embedding model: it serves "
"/v1/embeddings and generates no text"),
req.peer);
if (opt_.image_model)
return error_response(err_not_implemented("this is an image model: it serves "
"/v1/images/generations and /v1/images/edits "
"and generates no text"),
req.peer);
OaiRequest r;
ApiError err;
if (parse_completion_request(req.body, odeps_, lim_, &r, &err, /*native=*/true) < 0)
@@ -1525,6 +1544,11 @@ HttpResponse Server::handle_responses(const HttpRequest& req) {
return error_response(err_not_implemented("this is an embedding model: it serves "
"/v1/embeddings and generates no text"),
req.peer);
if (opt_.image_model)
return error_response(err_not_implemented("this is an image model: it serves "
"/v1/images/generations and /v1/images/edits "
"and generates no text"),
req.peer);
std::string chat, echo;
ApiError err;
OaiRequest r;
@@ -1578,6 +1602,11 @@ HttpResponse Server::handle_completion(const HttpRequest& req) {
return error_response(err_not_implemented("this is an embedding model: it serves "
"/v1/embeddings and generates no text"),
req.peer);
if (opt_.image_model)
return error_response(err_not_implemented("this is an image model: it serves "
"/v1/images/generations and /v1/images/edits "
"and generates no text"),
req.peer);
OaiRequest r;
ApiError err;
@@ -1602,7 +1631,9 @@ HttpResponse Server::handle_embeddings(const HttpRequest& req) {
req.peer);
if (!deps_.embed)
return error_response(err_not_implemented(
"/v1/embeddings requires an embedding model; this one generates text"), req.peer);
opt_.image_model ? "/v1/embeddings requires an embedding model; this one makes images"
: "/v1/embeddings requires an embedding model; this one generates "
"text"), req.peer);
OaiRequest r;
ApiError err;
+6
View File
@@ -40,6 +40,7 @@ struct Deps {
IGrammarCompiler* grammar = nullptr; /* absent -> response_format is 501 */
IEmbedder* embed = nullptr; /* absent -> /v1/embeddings is 501 */
IMultimodal* mm = nullptr; /* absent -> image and audio parts are 501 */
IImageGen* images = nullptr; /* absent -> the images endpoints are 501 */
/* WHAT ONLY THE ENGINE CAN SEE: per-card VRAM, the expert plane. The server holds interfaces
* and no device handle, so this dependency is a function rather than an object -- there is
@@ -57,6 +58,9 @@ struct ServerOptions {
* /v1/completions answer 501 naming /v1/embeddings, rather than queueing a request the engine
* would finish after one step with no text. */
bool embedding_model = false;
/* AN IMAGE GENERATOR (rad_declare_generator) GENERATES NO TEXT either: the text endpoints
* answer 501 naming /v1/images/generations and /v1/images/edits. */
bool image_model = false;
/* WHICH DECISION PROTOCOL THE MODEL WAS TRAINED ON, from the container's `decision.type`:
* "d1" serves /v1/systemone (systemone.h); empty answers it 501. Never inferred from a name. */
std::string decision_type;
@@ -197,6 +201,8 @@ private:
HttpResponse handle_chat(const HttpRequest& req);
HttpResponse handle_completion(const HttpRequest& req);
HttpResponse handle_embeddings(const HttpRequest& req);
/* ------------------------------------------------------------------ images.cpp */
HttpResponse handle_images(const HttpRequest& req, bool edit);
HttpResponse handle_systemone(const HttpRequest& req);
HttpResponse handle_models(const HttpRequest& req);
HttpResponse handle_metrics(const HttpRequest& req);