radiance 1.16.0

New models:
- Hunyuan3D-2 (hunyuan3d2): an untextured 3-D mesh from one picture of an object. DINOv2-giant
  over the picture, a FLUX-shaped flow-matching DiT (16 double-stream and 32 single-stream blocks
  of 1024) over 3072 latents with both guidance branches in one step, and the shape VAE's
  geometry decoder. Converted from tencent/Hunyuan3D-2's hunyuan3d-dit-v2-0 folder with
  data/recipes/hunyuan3d-2-bf16.recipe (fp16 cast to bf16, 4.4 GiB, one card). The licence
  (Tencent Hunyuan 3D 2.0 Community License) does not cover the EU, the UK or South Korea
- Served on Hunyuan3D-2's own API server routes, so its Blender add-on and scripts work
  unchanged: POST /generate answers with the mesh, POST /send runs it in the background and
  GET /status/{uid} reports steps_done and then the file. GLB, OBJ, PLY or STL; the field is
  sampled coarse to fine as FlashVDM's hierarchical decoding does, or densely with
  "volume_decoding": "dense"; seed, steps, guidance and octree_resolution as the reference.
  Texturing (Hunyuan3D-Paint) is refused for now (docs/GUIDE.md §5.17)

Merged:
- libr3d rewritten for RDNA3's wave matrix (@RikshaDriver): bf16, f16, int8-activation and vocab
  GEMMs retiled to 16x128 blocks with a double-buffered k-walk; fp8, mxfp4a8, w2a8, w4a16, w5a16
  and w8a8 quantised GEMMs and the gated form; grouped MoE GEMMs (bf16, fp8a8f32, mxfp4a8); the
  norms and quantisers, the QSA state ops and the MoE router, scatter and gather. Brought onto the
  op contract before release (13 schemas, the MoE GEMMs on weight tables with a_order and bf16
  output, moe_gather's gate pitch, moe_scatter above 1024 slots, the mxfp4 m16 dispatch) and its
  gated-delta-net kernels replaced by libhalo's; every op it serves now passes rad-kbench against
  libref on a gfx1151, and r3d_selftest checks its MoE GEMMs by value
- Gemma 4 31B: asymmetric int5 linears (w5a8i8 above 64 rows, w5a16 up to 64, a scale per 128),
  the norm, GELU and two-rank all-reduce junctions at quant_act_i8g's grid (rmsnorm_quant_i8g,
  gelu_mul_quant_i8g, ar_rmsnorm_quant_i8g) so the prefill overlap runs on the i8a8, a4 and w5
  trunks, and compose files for the 31B i8g, heretic-ara-i8g and w5 on two cards (@keptn42)
- The norms' lane sum reads eight at a time: TranslateGemma 27B decode is back from 225 to 239
  tok/s a stream at four streams, bit for bit the same output (@mici81)
- The head-256 prefill softmax rescales each row by its own maximum, not by a vote of the wave, so
  a row's rounding no longer depends on which rows share its launch (@gostar)

Anthropic Messages API:
- /v1/messages takes min_p, presence_penalty, frequency_penalty, repetition_penalty and
  repeat_last_n as top-level fields with the chat path's names, ranges and meaning, so clients that
  speak only the Anthropic format (Claude Code) can set a model card's sampling, such as Qwen's
  presence_penalty 1.5. The penalties count the last repeat_last_n tokens of prompt and reply (64
  by default, --repeat-last-n), as llama.cpp does

Plugin ABI 33:
- Shape generators: rad_declare_shape_generator, RadShapeGenBatch (RadBatch::sgen_b) and
  RadArchProbe::gen_shape, with the SCOND, SSTEP, SLATENT and SQUERY passes. The layout
  fingerprint table is regenerated; out-of-tree plugins rebuild against 33
- New op point_fourier ([x | sin(x 2^j) | cos(x 2^j)], times pi on request) in libref, libavx,
  libr4d and libhalo
- A checkpoint for a model that reads no text gets a one-token vocabulary

More cards from the one image:
- stilldeadcode/radiance now carries libr3d (RDNA3: gfx11-generic, every gfx11 chip) and libhalo
  (Strix Halo: gfx1151, preferred there over libr3d) beside libr4d (gfx1201). docker/build.sh and
  the Dockerfile default to gfx1201;gfx11-generic;gfx1151
- libr3d loads only where the KFD topology lists a gfx11 card and libhalo only where it lists a
  gfx1151; a process without /dev/kfd sees neither. On an RDNA4 card, or with no card at all,
  the image therefore behaves exactly as before, and rad-convert lays weights out as before
- libhalo and libr3d now declare gemm_nt_q's w_rb, and libhalo gram_accum's upper, as libr4d
  does. Before, any build carrying them refused both at load ("9 parameters vs 8"), so a build
  for Strix Halo or RDNA3 had no device kernel library
- libhalo does not yet have every op libr4d added after it was ported (the IQR rows, Pixtral and
  Ministral rope, the tree-attention and DFlash-tree rows, among others); halo_parity lists them
  and is left out of the image's test stage until they are ported

Fixed -- container and checkpoint parsing:
- A .rad expert-1 entry inside or before expert 0 is refused; a vocab section whose count names
  an array at offset 0 is refused rather than read from the file header; offset checks no longer
  wrap; header tables must sit on their element alignment
- An imatrix array of arrays (unbounded recursion) and a safetensors header naming a tensor twice
  are refused; a failed RadWriter undo says the container is damaged; a tune cache measured on
  another machine is refused, as its format contract says

Fixed -- plugins:
- Two plugins declaring one op with different parameter roles are refused; before, the core
  applied the first one's chunk/capacity roles to the other's rows
- Null tables behind nonzero counts, unknown roles, keyless parameters or constraints and more
  operands than an issue carries are refused by name at load; on the host backend device rows are
  dropped even when no fat binary was registered; rad-schemas checks the ABI layout fingerprint as
  the engine does

Fixed -- device:
- Stream slots are recycled under a new generation: before, 1024 stream create/destroy cycles
  (LoRA loads, lanes, uplinks) made every later rad_stream_create fail
- A stream whose drain fails keeps its queue and kernarg ring instead of freeing them under the
  card; the kernarg ring no longer leaks when its access grant fails; a block over 1024 work-items
  is refused
- rad_dev_free takes the allocation off the ledger the pin-cap check reads; the host backend
  charges pages to the card the range was reserved for

Fixed -- engine and server:
- Two NDEBUG-only asserts (runtime-window totals, ring blocks per group) are refusals; a
  plugin-declared lcm past int64 saturates so the quantum check refuses it; every share view rect
  and part span is bounded by its entry
- Video: the timestep regions hold the refine rungs a schedule appends, a zero-frame encode is
  refused, /v1/videos bounds each side before the area product, and a realtime session needs a
  clip length to cut a turn at

Fixed -- kernels and quantisation:
- A trellis run shorter than a state's codes (tcq_rows=1, or N % tcq_rows == 1) read its seam
  out of bounds; the encoder now refuses it as the decoder does, and tcq_rows below one state is
  refused at parse
- qsa_tail_store bounds its slot index by the state plane (libr4d and libhalo); paged attention
  refuses kv_heads <= 0; libavx row_amax skips a NaN as libref does

Fixed -- tools:
- pad_tp.py no longer runs cp through a shell with shard names from the checkpoint's index
  (quote injection, path traversal): names must be bare file names
- ops_doc_check.sh runs under mawk (Ubuntu's awk); rad-kbench --max-cases/--max-bytes are checked
  integers; oot_plugins fails unless the installed replay passed a case and failed none

Thanks to @RikshaDriver, @keptn42, @mici81 and @gostar.
This commit is contained in:
Deadcode committed 2026-11-02 18:35:02 +01:00
1 parent cfa6a668f6
commit 769b4c64a6
122 files changed
+10092 -2203

No files matched your search

+1
View File
@@ -137,6 +137,7 @@ public:
int declare_generator(const RadGeneratorDecl* d);
int declare_audio_generator(const RadAudioGenDecl* d);
int declare_video_generator(const RadVideoGenDecl* d);
int declare_shape_generator(const RadShapeGenDecl* d);
void note_v (const char* f, va_list ap);
/* An op's buffer operands (rad_op_reads/rad_op_writes in rad_builder.h), which give the
+132 -12
View File
@@ -1201,6 +1201,11 @@ int Builder::declare_logits(rad_buf b) {
prog_.vgen_str.name.c_str());
return RAD_E_STATE;
}
if (prog_.is_shape_generator()) {
err(RAD_E_STATE, "declare_logits: this program already declared the shape generator '%s'",
prog_.sgen_name.c_str());
return RAD_E_STATE;
}
prog_.logits_buf = b;
return RAD_OK;
}
@@ -1241,6 +1246,11 @@ int Builder::declare_pooled(rad_buf b) {
prog_.vgen_str.name.c_str());
return RAD_E_STATE;
}
if (prog_.is_shape_generator()) {
err(RAD_E_STATE, "declare_pooled: this program already declared the shape generator '%s'",
prog_.sgen_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) {
@@ -1348,12 +1358,13 @@ int Builder::declare_generator(const RadGeneratorDecl* d) {
return RAD_E_STATE;
}
if (prog_.logits_buf != RAD_NULL_HANDLE || prog_.pooled_buf != RAD_NULL_HANDLE ||
prog_.is_audio_generator() || prog_.is_video_generator()) {
prog_.is_audio_generator() || prog_.is_video_generator() || prog_.is_shape_generator()) {
err(RAD_E_STATE, "declare_generator '%s': this program already declared %s; a program "
"generates text, embeds, makes images, audio or video -- one of the five",
nm, prog_.logits_buf != RAD_NULL_HANDLE ? "logits"
"generates text, embeds, makes images, audio, video or shapes -- one of "
"the six", nm, prog_.logits_buf != RAD_NULL_HANDLE ? "logits"
: prog_.pooled_buf != RAD_NULL_HANDLE ? "a pooled output"
: prog_.is_audio_generator() ? "an audio generator" : "a video generator");
: prog_.is_audio_generator() ? "an audio generator"
: prog_.is_video_generator() ? "a video generator" : "a shape generator");
return RAD_E_STATE;
}
if (d->layout != RAD_GEN_LAYOUT_JOINT_GRID && d->layout != RAD_GEN_LAYOUT_JOINT_STEP) {
@@ -1505,13 +1516,14 @@ int Builder::declare_audio_generator(const RadAudioGenDecl* d) {
return RAD_E_STATE;
}
if (prog_.logits_buf != RAD_NULL_HANDLE || prog_.pooled_buf != RAD_NULL_HANDLE ||
prog_.generator.layout != 0 || prog_.is_video_generator()) {
prog_.generator.layout != 0 || prog_.is_video_generator() || prog_.is_shape_generator()) {
err(RAD_E_STATE, "declare_audio_generator '%s': this program already declared %s; a "
"program generates text, embeds, makes images, audio or video -- one of "
"the five", nm,
"program generates text, embeds, makes images, audio, video or shapes -- "
"one of the six", nm,
prog_.logits_buf != RAD_NULL_HANDLE ? "logits"
: prog_.pooled_buf != RAD_NULL_HANDLE ? "a pooled output"
: prog_.generator.layout != 0 ? "an image generator" : "a video generator");
: prog_.generator.layout != 0 ? "an image generator"
: prog_.is_video_generator() ? "a video generator" : "a shape generator");
return RAD_E_STATE;
}
if (!d->tmpl && !d->tmpl_plain) {
@@ -1682,13 +1694,14 @@ int Builder::declare_video_generator(const RadVideoGenDecl* d) {
return RAD_E_STATE;
}
if (prog_.logits_buf != RAD_NULL_HANDLE || prog_.pooled_buf != RAD_NULL_HANDLE ||
prog_.generator.layout != 0 || prog_.is_audio_generator()) {
prog_.generator.layout != 0 || prog_.is_audio_generator() || prog_.is_shape_generator()) {
err(RAD_E_STATE, "declare_video_generator '%s': this program already declared %s; a "
"program generates text, embeds, makes images, audio or video -- one of "
"the five", nm,
"program generates text, embeds, makes images, audio, video or shapes -- "
"one of the six", nm,
prog_.logits_buf != RAD_NULL_HANDLE ? "logits"
: prog_.pooled_buf != RAD_NULL_HANDLE ? "a pooled output"
: prog_.generator.layout != 0 ? "an image generator" : "an audio generator");
: prog_.generator.layout != 0 ? "an image generator"
: prog_.is_audio_generator() ? "an audio generator" : "a shape generator");
return RAD_E_STATE;
}
if (!d->tmpl || !std::strstr(d->tmpl, "{prompt}") || d->max_text <= 0) {
@@ -1903,6 +1916,108 @@ int Builder::declare_video_generator(const RadVideoGenDecl* d) {
return RAD_OK;
}
/* The shape generator (rad_declare_shape_generator). Checked here rather than at the first request:
* the picture's geometry, the sampler, the grid and the field's buffer, which the core reads back
* after every query pass. */
int Builder::declare_shape_generator(const RadShapeGenDecl* d) {
if (finished_) {
err(RAD_E_STATE, "declare_shape_generator after declare finished");
return RAD_E_STATE;
}
if (!d) { err(RAD_E_INVAL, "declare_shape_generator: null declaration"); return RAD_E_INVAL; }
const char* nm = d->name && *d->name ? d->name : "(unnamed)";
if (prog_.is_shape_generator()) {
err(RAD_E_STATE, "declare_shape_generator: '%s' was already declared; '%s' is a second one",
prog_.sgen_name.c_str(), nm);
return RAD_E_STATE;
}
if (prog_.logits_buf != RAD_NULL_HANDLE || prog_.pooled_buf != RAD_NULL_HANDLE ||
prog_.generator.layout != 0 || prog_.is_audio_generator() || prog_.is_video_generator()) {
err(RAD_E_STATE, "declare_shape_generator '%s': this program already declared %s; a "
"program generates text, embeds, makes images, audio, video or shapes -- "
"one of the six", nm,
prog_.logits_buf != RAD_NULL_HANDLE ? "logits"
: prog_.pooled_buf != RAD_NULL_HANDLE ? "a pooled output"
: prog_.generator.layout != 0 ? "an image generator"
: prog_.is_audio_generator() ? "an audio generator" : "a video generator");
return RAD_E_STATE;
}
if (d->canvas < 1 || d->canvas > 4096 || !(d->border_ratio >= 0.0 && d->border_ratio < 1.0) ||
d->enc_patch < 1 || d->enc_size < d->enc_patch || d->enc_size > 4096 ||
d->enc_size % d->enc_patch != 0) {
err(RAD_E_INVAL, "declare_shape_generator '%s': the picture is out of range (canvas %lld, "
"border %g, encoder %lld in patches of %lld): the canvas 1..4096, the "
"border in [0, 1), the encoder's side 1..4096 and a whole number of "
"patches", nm, (long long)d->canvas, d->border_ratio,
(long long)d->enc_size, (long long)d->enc_patch);
return RAD_E_INVAL;
}
for (int c = 0; c < 3; ++c)
if (!std::isfinite(d->pix_mean[c]) || !(d->pix_std[c] > 0.0) ||
!std::isfinite(d->pix_std[c])) {
err(RAD_E_INVAL, "declare_shape_generator '%s': channel %d's mean %g and deviation %g "
"must be finite and the deviation positive", nm, c, d->pix_mean[c],
d->pix_std[c]);
return RAD_E_INVAL;
}
if (d->latent_rows < 1 || d->latent_channels < 1 || d->step_rows < 2 * d->latent_rows) {
err(RAD_E_INVAL, "declare_shape_generator '%s': a latent of %lld rows of %lld channels "
"and a step of %lld rows; a step holds both branches' latents", nm,
(long long)d->latent_rows, (long long)d->latent_channels, (long long)d->step_rows);
return RAD_E_INVAL;
}
if (d->default_steps < 2 || d->max_steps < d->default_steps || d->max_steps > 1000 ||
!(d->default_guidance >= 0.0) || !std::isfinite(d->default_guidance)) {
err(RAD_E_INVAL, "declare_shape_generator '%s': the sampler is out of range (%lld steps "
"by default, %lld at most, guidance %g): at least 2 grid points, at most "
"1000, the guidance finite and not negative", nm,
(long long)d->default_steps, (long long)d->max_steps, d->default_guidance);
return RAD_E_INVAL;
}
if (!(d->bounds > 0.0) || !std::isfinite(d->bounds) || !std::isfinite(d->level) ||
d->min_resolution < 2 || d->default_resolution < d->min_resolution ||
d->max_resolution < d->default_resolution || d->max_resolution > 2048) {
err(RAD_E_INVAL, "declare_shape_generator '%s': the field is out of range (bounds %g, "
"level %g, resolution %lld in %lld..%lld): the bounds positive, the level "
"finite, the resolutions in order from 2 to 2048", nm, d->bounds,
d->level, (long long)d->default_resolution, (long long)d->min_resolution,
(long long)d->max_resolution);
return RAD_E_INVAL;
}
if (d->max_lanes < 1 || d->max_query < 1) {
err(RAD_E_INVAL, "declare_shape_generator '%s': %lld lanes and %lld points a query pass; "
"both at least 1", nm, (long long)d->max_lanes, (long long)d->max_query);
return RAD_E_INVAL;
}
const int64_t n_patch = (d->enc_size / d->enc_patch) * (d->enc_size / d->enc_patch);
const int64_t rows = std::max({ d->step_rows, d->max_query, n_patch, d->latent_rows });
if (prog_.ctx.max_tok < rows) {
err(RAD_E_INVAL, "declare_shape_generator '%s': a pass carries %lld rows and this one's "
"largest is %lld", nm, (long long)prog_.ctx.max_tok, (long long)rows);
return RAD_E_INVAL;
}
const rad_buf h = d->field_out;
if (h == RAD_NULL_HANDLE || (size_t)h >= prog_.buffers.size()) {
err(RAD_E_INVAL, "declare_shape_generator '%s': field_out %u is not a declared buffer", nm,
(unsigned)h);
return RAD_E_INVAL;
}
const RadBufDecl& ob = prog_.buffers[h].decl;
if (ob.dtype != RAD_F32 || ob.domain != RAD_DOMAIN_DEVICE ||
decl_numel(ob.rank, ob.shape) < d->max_query) {
err(RAD_E_INVAL, "declare_shape_generator '%s': field_out '%s' must be a device f32 "
"buffer of at least %lld elements", nm, prog_.buffers[h].name.c_str(),
(long long)d->max_query);
return RAD_E_INVAL;
}
prog_.sgen_name = nm;
prog_.shape_gen = *d;
/* As for the other generators: the Program is moved after declare; the name lives in
* sgen_name. */
prog_.shape_gen.name = nullptr;
return RAD_OK;
}
/* Validates the draft head at declare rather than at the first draft pass, where a bad decl would
* only show as zero acceptance. `depth` must equal RadBuildCtx::max_spec, which the plugin sized
* its buffers with. */
@@ -2745,6 +2860,11 @@ int rad_declare_video_generator(RadBuilder* b, const RadVideoGenDecl* d) {
return B(b)->declare_video_generator(d);
}
int rad_declare_shape_generator(RadBuilder* b, const RadShapeGenDecl* d) {
if (!b) return RAD_E_INVAL;
return B(b)->declare_shape_generator(d);
}
void rad_note(RadBuilder* b, const char* f, ...) {
if (!b) return;
va_list ap;
+53 -13
View File
@@ -589,7 +589,7 @@ KernelRec* kernel_for(const void* stub, int ord, std::string* why) {
struct Stream {
uint64_t magic = kStreamMagic;
int ord = 0;
uint32_t id = 0; /* index into g_queue_by_id, never reused */
uint32_t id = 0; /* queue_of's key, never reused (see there) */
hsa_agent_t agent{};
hsa_queue_t* q = nullptr;
uint64_t mask = 0;
@@ -623,12 +623,27 @@ struct Stream {
void unlock() { busy.store(false, std::memory_order_release); }
};
/* Every queue this process has made, by an id that is never reused, so "packet i of queue n"
* stays meaningful after the queue is destroyed. A destroyed queue's entry is null; everything
* it held has been consumed. */
/* Every live queue, by an id that is never reused, so "packet i of queue n" stays meaningful after
* the queue is destroyed: queue_of answers null for a destroyed queue's id, and everything it held
* has been consumed. At most kMaxQueues are live at once; a destroyed queue's slot is taken again
* under a new generation, id = generation * kMaxQueues + slot, so a stale id never names the
* slot's next queue. */
constexpr uint32_t kMaxQueues = 1024;
std::atomic<hsa_queue_t*> g_queue_by_id[kMaxQueues];
std::atomic<uint32_t> g_next_queue_id{0};
std::atomic<uint32_t> g_queue_id_at[kMaxQueues]; /* the id holding each slot now */
std::mutex g_queue_slot_mu;
std::vector<uint32_t> g_queue_free; /* destroyed queues' slots */
uint32_t g_queue_next_slot = 0;
uint32_t g_queue_gen[kMaxQueues];
/* The queue an id names, or null once it is destroyed. The slot's id is stored before its queue
* (release), so a queue read here that belongs to a later generation is seen with that
* generation's id and refused. */
inline hsa_queue_t* queue_of(uint32_t id) {
const uint32_t slot = id % kMaxQueues;
hsa_queue_t* q = g_queue_by_id[slot].load(std::memory_order_acquire);
return g_queue_id_at[slot].load(std::memory_order_acquire) == id ? q : nullptr;
}
inline Stream* ours(const void* s) {
if ((uintptr_t)s < 4096) return nullptr;
@@ -1127,6 +1142,9 @@ int dispatch(Stream* s, const KernelRec* k, dim3 g, dim3 b, void** args, size_t
if (!gx || !gy || !gz) return RAD_OK;
if (gx > UINT32_MAX || gy > UINT32_MAX || gz > UINT32_MAX) return RAD_E_INVAL;
if ((uint64_t)k->group_size + shm > 65536) return RAD_E_INVAL;
/* The packet's fields are 16 bits wide and the card runs at most 1024 work-items a group;
* HIP refuses a larger block, and so does this. */
if ((uint64_t)b.x * b.y * b.z > 1024) return RAD_E_INVAL;
alignas(64) unsigned char ka[kKargMax];
const uint32_t n = (k->kernarg_size + 15u) & ~15u;
@@ -1562,6 +1580,7 @@ int a_stream_create(RadStream* out, int high_priority) {
if (hsa_amd_memory_pool_allocate(kpool, (size_t)(s->mask + 2) * kKargSlot, 0, &ka) !=
HSA_STATUS_SUCCESS ||
hsa_amd_agents_allow_access(1, &kpeer, nullptr, ka) != HSA_STATUS_SUCCESS) {
if (ka) hsa_amd_memory_pool_free(ka); /* allocated, then refused access */
hsa_queue_destroy(s->q);
device_set_error("rad_stream_create: the kernel argument ring could not be placed in %s",
d.host_kargs ? "pinned host memory" : "VRAM the host can write");
@@ -1582,17 +1601,28 @@ int a_stream_create(RadStream* out, int high_priority) {
s->bounce = static_cast<char*>(bb);
note_alloc(ka, (int64_t)(s->mask + 2) * kKargSlot, -1);
note_alloc(bb, kBounceBytes, -1);
s->id = g_next_queue_id.fetch_add(1, std::memory_order_relaxed);
if (s->id >= kMaxQueues) {
uint32_t slot = kMaxQueues;
{
std::lock_guard<std::mutex> lk(g_queue_slot_mu);
if (!g_queue_free.empty()) {
slot = g_queue_free.back();
g_queue_free.pop_back();
} else if (g_queue_next_slot < kMaxQueues) {
slot = g_queue_next_slot++;
}
if (slot < kMaxQueues) s->id = g_queue_gen[slot]++ * kMaxQueues + slot;
}
if (slot >= kMaxQueues) {
note_free(bb);
note_free(ka);
hsa_amd_memory_pool_free(bb);
hsa_amd_memory_pool_free(ka);
hsa_queue_destroy(s->q);
device_set_error("rad_stream_create: more than %u streams in one process", kMaxQueues);
device_set_error("rad_stream_create: more than %u streams live at once", kMaxQueues);
return RAD_E_NOMEM;
}
g_queue_by_id[s->id].store(s->q, std::memory_order_release);
g_queue_id_at[slot].store(s->id, std::memory_order_release);
g_queue_by_id[slot].store(s->q, std::memory_order_release);
{
std::lock_guard<std::mutex> lk(G().streams_mu);
G().streams.push_back(s.get());
@@ -1604,14 +1634,24 @@ int a_stream_create(RadStream* out, int high_priority) {
void a_stream_destroy(RadStream rs) {
Stream* s = ours(rs);
if (!s) return;
(void)stream_drain(s);
/* Undrained (a closed gate, a fault), the queue may still be read by the card, and so may its
* kernel argument ring: both are left allocated rather than freed under it. */
if (const int rc = stream_drain(s); rc < 0) {
RAD_WARN("device: a stream was destroyed with work it could not drain (%s); its queue and "
"argument ring stay allocated", rad_strerror(rc));
return;
}
{
std::lock_guard<std::mutex> lk(G().streams_mu);
auto& v = G().streams;
for (size_t i = 0; i < v.size(); ++i) if (v[i] == s) { v.erase(v.begin() + (long)i); break; }
}
g_queue_by_id[s->id].store(nullptr, std::memory_order_release);
g_queue_by_id[s->id % kMaxQueues].store(nullptr, std::memory_order_release);
hsa_queue_destroy(s->q);
{
std::lock_guard<std::mutex> lk(g_queue_slot_mu);
g_queue_free.push_back(s->id % kMaxQueues);
}
note_free(s->karg);
note_free(s->bounce);
hsa_amd_memory_pool_free(s->karg);
@@ -1676,7 +1716,7 @@ bool xp_list_finished(int ord, uint32_t k);
bool reusable(const Sig* g) {
if (g->stamped || hsa_signal_load_relaxed(g->h) != 0) return false;
for (const auto& w : g->waiters) {
hsa_queue_t* q = g_queue_by_id[w.first].load(std::memory_order_acquire);
hsa_queue_t* q = queue_of(w.first);
if (q && hsa_queue_load_read_index_relaxed(q) <= w.second) return false;
}
const int32_t xd = g->xp_dev.load(std::memory_order_acquire);
@@ -1902,7 +1942,7 @@ std::vector<Tape*> g_tape_retired;
* kReserveMargin past it has launched, which proves it as in reserve(). */
bool tape_idle(const Tape* t) {
for (const auto& l : t->last) {
hsa_queue_t* q = g_queue_by_id[l.first].load(std::memory_order_acquire);
hsa_queue_t* q = queue_of(l.first);
if (q && hsa_queue_load_read_index_scacquire(q) < l.second + kReserveMargin) return false;
}
return true;
+2 -1
View File
@@ -406,7 +406,8 @@ int64_t dev_stuck_ms();
constexpr int kTapeOverlapRun = 6;
/* ------------------------------------------------------------------ the allocation ledger
* What rad_dev_alloc has handed out since process start, by RAD_MEM_* kind. It does not see a
* By RAD_MEM_* kind: the bytes rad_dev_alloc has handed out and rad_dev_free has not taken back,
* and the number of allocations since process start. It does not see a
* kernel plugin that calls hipMalloc directly; see the ledger in dispatch.cpp. */
void rad_dev_alloc_totals(int kind, int64_t* bytes, int64_t* count);
+24 -4
View File
@@ -18,6 +18,7 @@
#include <iterator>
#include <map>
#include <mutex>
#include <unordered_map>
#include <string>
#include <utility>
#include <cstdint>
@@ -143,6 +144,26 @@ struct Ledger {
std::atomic<int64_t> count{0};
};
Ledger g_ledger[4]; /* indexed by RAD_MEM_*; rad_dev_alloc bounds the kind */
/* Each live allocation's size, so rad_dev_free (which has none) takes it back off the ledger's
* bytes: pinned ranges are freed and taken again during bring-up, and the pin-cap check reads the
* ledger as what the process holds. Allocations are rare, never per step. */
struct LiveAlloc { int64_t bytes; int kind; };
std::mutex g_ledger_mu;
std::unordered_map<void*, LiveAlloc> g_ledger_live;
void ledger_add(void* p, int64_t bytes, int kind) {
g_ledger[kind].bytes.fetch_add(bytes, std::memory_order_relaxed);
std::lock_guard<std::mutex> lk(g_ledger_mu);
g_ledger_live[p] = LiveAlloc{ bytes, kind };
}
void ledger_drop(void* p) {
if (!p) return;
std::lock_guard<std::mutex> lk(g_ledger_mu);
const auto it = g_ledger_live.find(p);
if (it == g_ledger_live.end()) return;
g_ledger[it->second.kind].bytes.fetch_sub(it->second.bytes, std::memory_order_relaxed);
g_ledger_live.erase(it);
}
/* Live event handles, counted here so the number is backend-independent; the only place an
* event leaked at teardown shows. */
@@ -421,7 +442,7 @@ void* rad_dev_alloc(int64_t bytes, int kind) {
thread_local int64_t t_device_ordinal = 0;
void* p = dev()->alloc(bytes, kind);
if (p && kind >= 0 && kind < (int)std::size(rad::g_ledger)) {
rad::g_ledger[kind].bytes.fetch_add(bytes, std::memory_order_relaxed);
rad::ledger_add(p, bytes, kind);
const int64_t total = rad::g_ledger[kind].count.fetch_add(1, std::memory_order_relaxed) + 1;
const int64_t ordinal = kind == RAD_MEM_DEVICE ? ++t_device_ordinal : total;
const int64_t floor_ = rad::trace_floor();
@@ -447,8 +468,7 @@ void* rad_dev_alloc(int64_t bytes, int kind) {
return p;
}
void rad_dev_free(void* p, int kind) {
/* The ledger counts allocations, not live bytes: rad_dev_free has no size. The engine frees
* only at teardown, so the two agree while running. */
rad::ledger_drop(p);
dev()->free(p, kind);
}
void* rad_dev_host_ptr(void* p) { return dev()->host_ptr(p); }
@@ -665,7 +685,7 @@ void* rad_dev_map_file(int fd, int64_t foff, int64_t bytes) {
}
void* p = f(fd, foff, bytes);
if (p) {
rad::g_ledger[RAD_MEM_HOST_MAPPED].bytes.fetch_add(bytes, std::memory_order_relaxed);
rad::ledger_add(p, bytes, RAD_MEM_HOST_MAPPED);
rad::g_ledger[RAD_MEM_HOST_MAPPED].count.fetch_add(1, std::memory_order_relaxed);
}
return p;
+28 -3
View File
@@ -20,6 +20,7 @@
#include <condition_variable>
#include <cstdlib>
#include <cstring>
#include <map>
#include <mutex>
#include <thread>
#include <unordered_map>
@@ -723,6 +724,21 @@ constexpr int64_t kVmemGranule = RAD_ALIGN_POOL;
int64_t h_vmem_granularity(void) { return kVmemGranule; }
/* Each reservation's card, recorded at reserve: the thread that later commits into a pool, or
* releases it at teardown, may have selected another card, and the pages count against the card
* the range was reserved for (as the AQL backend's VRes does). Keyed by base. */
struct VRange { char* end; int device; };
std::mutex g_vres_mu;
std::map<const char*, VRange> g_vres;
int vmem_device_of(const void* addr) {
std::lock_guard<std::mutex> lk(g_vres_mu);
auto it = g_vres.upper_bound((const char*)addr);
if (it == g_vres.begin()) return t_device;
--it;
return (const char*)addr < it->second.end ? it->second.device : t_device;
}
void* h_vmem_reserve(int64_t bytes, int64_t align) {
if (bytes <= 0) return nullptr;
if (align < kVmemGranule) align = kVmemGranule;
@@ -740,11 +756,20 @@ void* h_vmem_reserve(int64_t bytes, int64_t align) {
if (head) ::munmap(raw, head);
const size_t tail = raw_len - head - (size_t)bytes;
if (tail) ::munmap(base + bytes, tail);
{
std::lock_guard<std::mutex> lk(g_vres_mu);
g_vres[base] = VRange{ base + bytes, t_device };
}
return base;
}
void h_vmem_release(void* base, int64_t bytes) {
if (base && bytes > 0) ::munmap(base, (size_t)bytes);
if (!base || bytes <= 0) return;
{
std::lock_guard<std::mutex> lk(g_vres_mu);
g_vres.erase((const char*)base);
}
::munmap(base, (size_t)bytes);
}
int h_vmem_commit(void* addr, int64_t bytes) {
@@ -755,7 +780,7 @@ int h_vmem_commit(void* addr, int64_t bytes) {
device_set_error("vmem_commit(%p, %lld): mmap failed", addr, (long long)bytes);
return RAD_E_NOMEM;
}
g_used[t_device].fetch_add(bytes, std::memory_order_relaxed);
g_used[vmem_device_of(addr)].fetch_add(bytes, std::memory_order_relaxed);
return RAD_OK;
}
@@ -769,7 +794,7 @@ int h_vmem_decommit(void* addr, int64_t bytes) {
device_set_error("vmem_decommit(%p, %lld): mmap failed", addr, (long long)bytes);
return RAD_E_INVAL;
}
g_used[t_device].fetch_sub(bytes, std::memory_order_relaxed);
g_used[vmem_device_of(addr)].fetch_sub(bytes, std::memory_order_relaxed);
return RAD_OK;
}
+46 -3
View File
@@ -6,6 +6,7 @@
#include "gen/driver.h"
#include "gen/audio_driver.h"
#include "gen/video_driver.h"
#include "gen/shape_driver.h"
#include "kld.h"
#include "mm/processor.h"
#include "mm/media.h"
@@ -1809,17 +1810,20 @@ int Engine::serve(std::unique_ptr<StallWatch> watch) {
embedding_ = ranks_[0]->program.pooled_buf != RAD_NULL_HANDLE;
const bool audio_gen = ranks_[0]->program.is_audio_generator();
const bool video_gen = ranks_[0]->program.is_video_generator();
const bool shape_gen = ranks_[0]->program.is_shape_generator();
const bool generator = ranks_[0]->program.is_pass_driven();
if (ranks_[0]->program.logits_buf == RAD_NULL_HANDLE && !embedding_ && !generator) {
RAD_ERR("the '%s' plugin declared no logits buffer (rad_declare_logits), no pooled output "
"(rad_declare_pooled) and no generator (rad_declare_generator, "
"rad_declare_audio_generator, rad_declare_video_generator), so a step produces "
"rad_declare_audio_generator, rad_declare_video_generator, "
"rad_declare_shape_generator), so a step produces "
"nothing anyone can read. An encoder-only plugin cannot serve.",
plugins_.arch_plugin.c_str());
return RAD_E_UNSUPPORTED;
}
if (generator) {
const char* const what = audio_gen ? "audio" : video_gen ? "video" : "images";
const char* const what = audio_gen ? "audio" : video_gen ? "video"
: shape_gen ? "shapes" : "images";
if (cfg_.kld() || cfg_.n_spec > 0) {
RAD_ERR("the '%s' plugin makes %s: --kld and speculative decoding have no tokens to "
"work on", plugins_.arch_plugin.c_str(), what);
@@ -1828,6 +1832,7 @@ int Engine::serve(std::unique_ptr<StallWatch> watch) {
for (size_t i = 1; i < ranks_.size(); ++i)
if (ranks_[i]->program.is_audio_generator() != audio_gen ||
ranks_[i]->program.is_video_generator() != video_gen ||
ranks_[i]->program.is_shape_generator() != shape_gen ||
!ranks_[i]->program.is_pass_driven()) {
RAD_ERR("rank %zu declared a different generator from rank 0's", i);
return RAD_E_STATE;
@@ -1838,6 +1843,8 @@ int Engine::serve(std::unique_ptr<StallWatch> watch) {
"after them"
: video_gen
? "a video generator: a prompt is read by its own request's steps and keeps no KV"
: shape_gen
? "a shape generator: a picture is read by its own request's steps and keeps no KV"
: "an image generator: a conditioning is read by its own request's images and by "
"nothing after them";
decide("--no-prefix-cache", "prefix caching off", prefix_off_why_);
@@ -1994,7 +2001,16 @@ int Engine::serve(std::unique_ptr<StallWatch> watch) {
rio.push_back({ rk->device, rk->ctx.stream(), &rk->program, rk->pools.kv().base(),
rank_stream_views_[r].data() });
}
if (video_gen) {
if (shape_gen) {
/* As for the image generator below. */
std::vector<gen::ShapeDriver::RankIO> gio;
for (auto& rk : ranks_) gio.push_back({ rk->device, rk->ctx.stream() });
auto d = std::make_unique<gen::ShapeDriver>();
RAD_TRY(d->init(ranks_[0]->program, gio));
shp_gen_ = d.get();
gen_ = std::move(d);
RAD_TRY(rad_dev_set(ranks_[0]->device));
} else if (video_gen) {
/* As for the image generator below; the plugin lays out each request's rows. */
std::vector<gen::VideoDriver::RankIO> gio;
for (auto& rk : ranks_) gio.push_back({ rk->device, rk->ctx.stream() });
@@ -2596,6 +2612,7 @@ int Engine::run_server() {
o.image_model = img_gen_ != nullptr;
o.audio_model = aud_gen_ != nullptr;
o.video_model = vid_gen_ != nullptr;
o.shape_model = shp_gen_ != nullptr;
o.decision_type = rad_meta_gets(&meta_, "decision.type", "");
/* clef's learned scalars, which the server applies to what the head returns (server/clef.h);
* rad-convert writes them beside decision.type. */
@@ -3159,6 +3176,29 @@ int Engine::run_server() {
/* A video generator's endpoints: the driver's queue and the declared prompt, sizes and
* lengths. */
struct ShapeBridge final : server::IShapeGen {
gen::ShapeDriver* drv = nullptr;
const gen::ShapeGenInfo& info() const override { return drv->info(); }
int submit(std::unique_ptr<gen::ShapeRequest> r, std::string* why) override {
return drv->submit(std::move(r), why);
}
int64_t queued() const override { return drv->queued(); }
int64_t running() const override { return drv->running(); }
} shape_bridge;
if (shp_gen_) {
shape_bridge.drv = shp_gen_;
d.shapes = &shape_bridge;
const gen::ShapeGenInfo& in = shp_gen_->info();
if (cfg_.served_model_name.empty() && !in.name.empty()) {
o.model_id = in.name;
decide("--served-model-name", o.model_id, "a shape generator: its own name");
}
RAD_INFO("shape: '%s', a %lldx%lld picture to a field sampled at %lld cells a side by "
"default (%lld..%lld), %lld steps by default at guidance %g",
in.name.c_str(), (long long)in.canvas, (long long)in.canvas,
(long long)in.default_resolution, (long long)in.min_resolution,
(long long)in.max_resolution, (long long)in.default_steps, in.default_guidance);
}
struct VideoBridge final : server::IVideoGen {
gen::VideoDriver* drv = nullptr;
server::VideoGenInfo inf;
@@ -3308,6 +3348,9 @@ int Engine::run_server() {
else if (vid_gen_)
RAD_INFO("serving on http://%s:%d (/v1/videos; completions and chat are 501%s)",
o.host.c_str(), o.port, keyed);
else if (shp_gen_)
RAD_INFO("serving on http://%s:%d (/generate, /send and /status/{uid}; completions and "
"chat are 501%s)", o.host.c_str(), o.port, keyed);
else if (gen_)
RAD_INFO("serving on http://%s:%d (/v1/images/generations%s; completions and chat are "
"501%s)", o.host.c_str(), o.port,
+7 -5
View File
@@ -50,7 +50,7 @@ namespace rad {
class Kld;
class StallWatch;
namespace gen { class Driver; class AudioDriver; class VideoDriver; struct IPassDriver; }
namespace gen { class Driver; class AudioDriver; class VideoDriver; class ShapeDriver; struct IPassDriver; }
namespace server { class Sink; }
struct TierPump;
struct TierJob;
@@ -431,14 +431,16 @@ private:
int collect_pooled_issue(const RadBatch* b, StepOut& so);
int collect_pooled(const RadBatch* b, StepOut& so);
/* A generator (rad_declare_generator, rad_declare_audio_generator,
* rad_declare_video_generator): the driver that turns requests into passes and the loop that
* runs them, replacing the scheduler and step loop (engine_gen.cpp). Null for every other
* program. `img_gen_`, `aud_gen_` and `vid_gen_` are the same driver by its kind, for the
* endpoints; one of them is set when `gen_` is. */
* rad_declare_video_generator, rad_declare_shape_generator): the driver that turns requests
* into passes and the loop that runs them, replacing the scheduler and step loop
* (engine_gen.cpp). Null for every other program. `img_gen_`, `aud_gen_`, `vid_gen_` and
* `shp_gen_` are the same driver by its kind, for the endpoints; one of them is set when
* `gen_` is. */
std::unique_ptr<gen::IPassDriver> gen_;
gen::Driver* img_gen_ = nullptr;
gen::AudioDriver* aud_gen_ = nullptr;
gen::VideoDriver* vid_gen_ = nullptr;
gen::ShapeDriver* shp_gen_ = nullptr;
int gen_loop();
/* Zeroes the state slots the KV manager granted since the last step, on every rank's stream,
* before the step or pass that first reads them. */
+23
View File
@@ -11,6 +11,7 @@
#include "gen/driver.h"
#include "gen/audio_driver.h"
#include "gen/video_driver.h"
#include "gen/shape_driver.h"
#include "build/startup.h"
#include "build/rad_build.h"
@@ -1110,6 +1111,25 @@ int Engine::declare() {
if (cfg_.mm_max_patches < 0) cfg_.mm_max_patches = 0;
if (cfg_.n_spec < 0) cfg_.n_spec = 0;
cfg_.prefix_cache = false;
} else if (pb.gen_rows > 0 && pb.gen_shape) {
if (!cfg_.given.count("--max-num-batched-tokens")) {
cfg_.max_tok = pb.gen_rows;
decide("--max-num-batched-tokens", std::to_string(cfg_.max_tok),
"a shape generator: a denoising step's two branches or a query pass's "
"points, whichever is more");
}
if (!cfg_.given.count("--max-num-seqs")) {
cfg_.max_seqs = 1;
decide("--max-num-seqs", "1", "a shape generator: a pass is one request's");
}
if (!cfg_.given.count("--max-model-len") && cfg_.max_ctx == 0) {
cfg_.max_ctx = pb.gen_rows;
decide("--max-model-len", std::to_string(cfg_.max_ctx),
"a shape generator: a pass's rows");
}
if (cfg_.mm_max_patches < 0) cfg_.mm_max_patches = 0;
if (cfg_.n_spec < 0) cfg_.n_spec = 0;
cfg_.prefix_cache = false;
} else if (pb.gen_rows > 0 && pb.gen_video) {
if (!cfg_.given.count("--max-num-batched-tokens")) {
cfg_.max_tok = pb.gen_rows;
@@ -1809,6 +1829,7 @@ int Engine::plan() {
f.staging = r->program.is_generator() ? gen::Driver::device_bytes(r->program)
: r->program.is_audio_generator() ? gen::AudioDriver::device_bytes(r->program)
: r->program.is_video_generator() ? gen::VideoDriver::device_bytes(r->program)
: r->program.is_shape_generator() ? gen::ShapeDriver::device_bytes(r->program)
: BatchBuilder::device_bytes(r->program, cfg_, kg);
if (f.staging < 0) return RAD_E_INVAL;
late_step_bytes_ = std::max(late_step_bytes_, f.staging);
@@ -4185,6 +4206,8 @@ int Engine::load_vocab() {
return RAD_E_FORMAT;
}
RAD_TRY(vocab_deserialize(file_->base(), (uint64_t)file_->size(), vs.h, vb));
} else if (meta_textless(rad_meta_gets(&meta_, "radiance.text", nullptr))) {
vocab_textless(vb);
} else if (ckpt_->is_gguf()) {
/* GGUF names its pre-tokeniser; the chain is reconstructed from the name or refused (a
* container converted with --tokenizer bakes in the declared one). */
+8 -2
View File
@@ -1,6 +1,6 @@
/* engine_gen.cpp -- a generator's loop: the driver's passes (core/gen/pass.h; driver.h for
* images, audio_driver.h for audio, video_driver.h for video) run on the ranks like token steps, one at a time, each drained
* before the next.
* images, audio_driver.h for audio, video_driver.h for video, shape_driver.h for shapes) run on the
* ranks like token steps, one at a time, each drained before the next.
*
* Draining is cheap: a pass is tens to thousands of milliseconds of device work, and the next
* pass depends only on the driver's host bookkeeping, so the wait costs the microseconds of
@@ -29,6 +29,12 @@ static const char* pass_name(int gen) {
case RAD_GEN_PASS_ADECODE: return "adecode";
case RAD_GEN_PASS_VDECODE: return "vdecode";
case RAD_GEN_PASS_VUPSCALE: return "vupscale";
case RAD_GEN_PASS_VENCODE: return "vencode";
case RAD_GEN_PASS_AENCODE: return "aencode";
case RAD_GEN_PASS_SCOND: return "scond";
case RAD_GEN_PASS_SSTEP: return "sstep";
case RAD_GEN_PASS_SLATENT: return "slatent";
case RAD_GEN_PASS_SQUERY: return "squery";
default: return "";
}
}
+129
View File
@@ -13,6 +13,7 @@
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <sstream>
#include <map>
namespace rad {
@@ -688,6 +689,124 @@ int Checkpoint::open_diffusers() {
return RAD_OK;
}
/* config.yaml's maps of scalars as dotted keys, a list's items space-separated, booleans as 1 and
* 0 and a trailing comment dropped: the subset Hunyuan3D-2's configs are written in. Anything else
* (a multi-line value, a list of maps) is refused, not guessed at. */
static int meta_from_yaml(const std::string& path, MetaOwn* out) {
std::ifstream f(path);
if (!f) {
RAD_ERR("%s: cannot read", path.c_str());
return RAD_E_IO;
}
std::vector<std::pair<size_t, std::string>> stack; /* indentation, key */
std::string line;
int ln = 0;
auto trim = [](std::string s) {
const size_t a = s.find_first_not_of(" \t\r"), b = s.find_last_not_of(" \t\r");
return a == std::string::npos ? std::string() : s.substr(a, b - a + 1);
};
while (std::getline(f, line)) {
++ln;
if (const size_t h = line.find(" #"); h != std::string::npos) line.resize(h);
const std::string body = trim(line);
if (body.empty() || body[0] == '#') continue;
const size_t ind = line.find_first_not_of(' ');
const size_t colon = body.find(':');
if (colon == std::string::npos || body[0] == '-') {
RAD_ERR("%s:%d: not a `key: value` line of the YAML this importer reads", path.c_str(), ln);
return RAD_E_FORMAT;
}
while (!stack.empty() && stack.back().first >= ind) stack.pop_back();
const std::string key = trim(body.substr(0, colon));
std::string val = trim(body.substr(colon + 1));
std::string full;
for (const auto& s : stack) full += s.second + ".";
full += key;
if (val.empty()) {
stack.emplace_back(ind, key);
continue;
}
if (val.front() == '[') {
if (val.back() != ']') {
RAD_ERR("%s:%d: a list must close on its line", path.c_str(), ln);
return RAD_E_FORMAT;
}
std::string items;
for (char& ch : val) if (ch == '[' || ch == ']' || ch == ',') ch = ' ';
std::istringstream is(val);
for (std::string it; is >> it;) items += (items.empty() ? "" : " ") + it;
val = items;
} else if (val == "True" || val == "true") {
val = "1";
} else if (val == "False" || val == "false") {
val = "0";
} else if (val.size() >= 2 && (val.front() == '"' || val.front() == '\'') &&
val.back() == val.front()) {
val = val.substr(1, val.size() - 2);
}
out->set(full, val);
}
return RAD_OK;
}
/* A Hunyuan3D-2 shape model (tencent/Hunyuan3D-2's hunyuan3d-dit-v2-0 and its kin): a folder of
* config.yaml and one safetensors holding three networks under `model.` (the DiT),
* `conditioner.` (DINOv2's image encoder) and `vae.` (the shape VAE), the names kept. config.yaml's
* keys go into the metadata by dotted path (model.params.hidden_size, vae.params.scale_factor,
* conditioner.params.main_image_encoder.kwargs.config.num_hidden_layers, ...). The architecture
* is `hunyuan3d2`, and the model reads no text (`radiance.text` none). */
int Checkpoint::open_hy3d(const std::string& weights) {
kind_ = SafeT;
RAD_TRY(add_shard(weights));
RAD_TRY(meta_from_yaml(dir_ + "/config.yaml", &meta_));
meta_.arch = "hunyuan3d2";
meta_.set("radiance.text", "none");
/* The typed dimensions are the denoiser's: its blocks, width and heads, read off its tensors;
* the vocabulary is the one token of a model that reads no text, and the context a step's
* rows (both branches of the 1370 conditioning rows and the latent). */
{
RadModelMeta& m = meta_.m;
const SrcTensor* lat = find("model.latent_in.weight");
const SrcTensor* mlp = find("model.double_blocks.0.img_mlp.0.weight");
const SrcTensor* qn = find("model.double_blocks.0.img_attn.norm.query_norm.scale");
const SrcTensor* vae = find("vae.post_kl.weight");
int64_t layers = 0;
while (find("model.double_blocks." + std::to_string(layers) + ".img_mod.lin.weight"))
++layers;
for (int64_t s = 0; find("model.single_blocks." + std::to_string(s) + ".linear1.weight"); ++s)
++layers;
if (!lat || lat->shape.size() != 2 || !mlp || mlp->shape.size() != 2 || !qn ||
qn->shape.size() != 1 || qn->shape[0] <= 0 || !vae || !layers) {
RAD_ERR("%s: Hunyuan3D-2's DiT or shape VAE is incomplete", weights.c_str());
return RAD_E_FORMAT;
}
m.n_layers = layers;
m.n_embd = lat->shape[0];
m.head_dim = qn->shape[0];
m.n_head = m.n_head_kv = m.n_embd / m.head_dim;
m.n_ff = mlp->shape[0];
m.n_vocab = 1;
m.n_ctx_train = 2 * (1370 + 3072);
m.rms_eps = 1e-6f;
m.rope_theta = 10000.0f;
m.rope_scale = 1.0f;
}
meta_.finish();
return RAD_OK;
}
/* Whether `file` is a Hunyuan3D-2 shape checkpoint: its DiT and image encoder by name. */
static bool hy3d_weights(const std::string& file) {
SafeTensorsFile probe;
if (probe.open(file) != RAD_OK) return false;
bool dit = false, enc = false;
for (const auto& t : probe.tensors()) {
dit = dit || t.name == "model.latent_in.weight";
enc = enc || t.name.rfind("conditioner.main_image_encoder.", 0) == 0;
}
return dit && enc;
}
/* A single-file Stable Diffusion XL checkpoint in Stability's (sgm) layout, the form SDXL and its
* finetunes (Illustrious, NoobAI, Pony and the rest) are published in: one safetensors holding
*
@@ -887,6 +1006,16 @@ int Checkpoint::open_safetensors(const std::string& path) {
((path_exists(dir_ + "/model_index.json") && !path_exists(dir_ + "/config.json")) ||
path_exists(dir_ + "/modular_model_index.json")))
return open_diffusers();
/* A Hunyuan3D-2 shape model: config.yaml beside its one safetensors (the fp16 one when the
* folder holds both). */
if (!is_index && path_exists(dir_ + "/config.yaml")) {
std::string w = path;
if (!is_file)
for (const char* f : { "/model.fp16.safetensors", "/model.safetensors" })
if (path_exists(dir_ + f)) { w = dir_ + f; break; }
if (w != path || is_file)
if (hy3d_weights(w)) return open_hy3d(w);
}
if (is_file) {
shards.push_back(path);
/* A single-file Stable Diffusion XL checkpoint, as Stability and every SDXL finetune
+1
View File
@@ -209,6 +209,7 @@ private:
int open_safetensors(const std::string& path);
int open_diffusers();
int open_sgm();
int open_hy3d(const std::string& weights);
int add_companions();
int add_torch_files();
int open_gguf(const std::string& path);
+3
View File
@@ -56,6 +56,9 @@ struct Cursor {
case GT_ARR: {
uint32_t et = 0; uint64_t n = 0;
if (!get(&et) || !get(&n)) return false;
/* An array of arrays is refused, as the GGUF reader refuses it: each level costs a
* file 12 bytes and this walker a stack frame. */
if (et == GT_ARR) { ok = false; return false; }
for (uint64_t i = 0; i < n && ok; ++i) if (!skip_value(et)) return false;
return ok;
}
+55 -16
View File
@@ -48,7 +48,7 @@ void RadFile::close() {
int RadFile::read_at(void* dst, int64_t bytes, int64_t off) const {
if (fd_ < 0) { RAD_ERR("read_at on a closed container"); return RAD_E_STATE; }
if (off < 0 || bytes < 0 || off + bytes > size_) {
if (off < 0 || bytes < 0 || off > size_ || bytes > size_ - off) {
RAD_ERR("read_at [%lld, %lld) is outside the %lld-byte container",
(long long)off, (long long)(off + bytes), (long long)size_);
return RAD_E_FORMAT;
@@ -210,6 +210,21 @@ int RadFile::validate() {
return RAD_E_FORMAT;
}
/* The tables are read in place through typed pointers, so each must sit on its element's
* alignment (the writer places every one 8-aligned), as the vocab section's arrays must. */
auto aligned = [&](uint64_t off, uint64_t count, size_t align, const char* what) {
if (count == 0 || off % align == 0) return true;
RAD_ERR("%s: %s starts at %llu, which is not %zu-aligned", path_.c_str(), what,
(unsigned long long)off, align);
return false;
};
if (!aligned(hdr_->meta_off, hdr_->meta_count, alignof(RadFileKV), "the metadata table") ||
!aligned(hdr_->dir_off, hdr_->dir_count, alignof(RadFileEntry), "the weight directory") ||
!aligned(hdr_->plane_off, hdr_->plane_count, alignof(RadFilePlane), "the plane table") ||
!aligned(hdr_->enc_off, hdr_->enc_count, alignof(RadEncoding), "the encoding table") ||
!aligned(hdr_->prof_off, hdr_->prof_count, alignof(RadFileProfile), "the expert profile"))
return RAD_E_FORMAT;
meta_ = (const RadFileKV*)(base_ + hdr_->meta_off);
dir_ = (const RadFileEntry*)(base_ + hdr_->dir_off);
planes_ = (const RadFilePlane*)(base_ + hdr_->plane_off);
@@ -335,18 +350,21 @@ int RadFile::validate() {
}
const RadVocabHeader* v = (const RadVocabHeader*)(base_ + voff);
/* Offset 0 means an optional array is absent (scores are unigram-only; types default to
* normal). Nothing real lives at file offset 0. */
auto arr_ok = [&](uint64_t off, uint64_t bytes, size_t align) {
return bytes == 0 || off == 0 ||
(off >= voff && off - voff <= vbytes && bytes <= vbytes - (off - voff) &&
off % align == 0);
* normal). Nothing real lives at file offset 0. Token texts, merges and steps are not
* optional: the writer places each one its count says exists, and a reader handed a
* count with no array would read the file header in its place. */
auto arr_ok = [&](uint64_t off, uint64_t bytes, size_t align, bool optional) {
if (bytes == 0) return true;
if (off == 0) return optional;
return off >= voff && off - voff <= vbytes && bytes <= vbytes - (off - voff) &&
off % align == 0;
};
const uint64_t nt = v->n_tokens, nm = v->n_merges, ns = v->n_steps;
if (!arr_ok(v->tok_text_off, nt * sizeof(rad_stroff), alignof(rad_stroff)) ||
!arr_ok(v->tok_score_off, nt * sizeof(float), alignof(float)) ||
!arr_ok(v->tok_type_off, nt, 1) ||
!arr_ok(v->merge_off, nm * 2 * sizeof(uint32_t), alignof(uint32_t)) ||
!arr_ok(v->step_off, ns * sizeof(RadVocabStep), alignof(RadVocabStep))) {
if (!arr_ok(v->tok_text_off, nt * sizeof(rad_stroff), alignof(rad_stroff), false) ||
!arr_ok(v->tok_score_off, nt * sizeof(float), alignof(float), true) ||
!arr_ok(v->tok_type_off, nt, 1, true) ||
!arr_ok(v->merge_off, nm * 2 * sizeof(uint32_t), alignof(uint32_t), false) ||
!arr_ok(v->step_off, ns * sizeof(RadVocabStep), alignof(RadVocabStep), false)) {
RAD_ERR("%s: the %s section's arrays do not fit inside it, or one is not aligned to its "
"element",
path_.c_str(), what);
@@ -458,7 +476,17 @@ int RadFile::index_experts() {
return RAD_E_FORMAT;
}
const uint64_t ebase = dir_[j].offset;
if (e_id == 1) g.stride = ebase - g.base;
if (e_id == 1) {
/* Expert 1 defines the stride, so the arithmetic test below cannot check it: it
* must step forward by at least one whole unit, or experts overlap (or wrap). */
if (ebase < g.base || ebase - g.base < g.unit_bytes) {
RAD_ERR("%s: layer %d expert 1 starts at %llu, inside or before expert 0's "
"%llu bytes at %llu", path_.c_str(), layer, (unsigned long long)ebase,
(unsigned long long)g.unit_bytes, (unsigned long long)g.base);
return RAD_E_FORMAT;
}
g.stride = ebase - g.base;
}
if (ebase != g.base + (uint64_t)e_id * g.stride) {
RAD_ERR("%s: layer %d expert %d starts at %llu, but base + %d*%llu is %llu -- the "
"layer has no fixed stride and cannot be addressed by arithmetic",
@@ -565,8 +593,16 @@ void RadWriter::abort() {
/* The file is the caller's container: restore its header (a no-op unless finish_append()
* failed in that write) and truncate the tail. */
if (fd_out_ >= 0) {
(void)!::pwrite(fd_out_, &old_hdr_, sizeof old_hdr_, 0);
(void)!::ftruncate(fd_out_, (off_t)old_size_);
/* A failed restore leaves a file that is neither the old container nor the new one,
* and the caller has only been told that the write failed. */
const bool hdr_ok = ::pwrite(fd_out_, &old_hdr_, sizeof old_hdr_, 0) ==
(ssize_t)sizeof old_hdr_;
const bool cut_ok = ::ftruncate(fd_out_, (off_t)old_size_) == 0;
if (!hdr_ok || !cut_ok)
RAD_ERR("%s: the append was undone only in part (%s) -- the container is damaged; "
"restore it from a copy", path_.c_str(),
!hdr_ok ? "its header could not be rewritten"
: "its tail could not be cut back");
::close(fd_out_);
}
if (fd_spill_ >= 0) ::close(fd_spill_);
@@ -1009,8 +1045,11 @@ int RadWriter::set_vocab_section(const void* blob, int64_t bytes) {
!fits(h->tok_score_off, h->tok_score_off ? (uint64_t)h->n_tokens * sizeof(float) : 0) ||
!fits(h->tok_type_off, h->tok_type_off ? h->n_tokens : 0) ||
!fits(h->merge_off, (uint64_t)h->n_merges * 2 * sizeof(uint32_t)) ||
!fits(h->step_off, (uint64_t)h->n_steps * sizeof(RadVocabStep))) {
RAD_ERR("the vocab section's arrays do not fit inside its %lld bytes. Its offsets must be "
!fits(h->step_off, (uint64_t)h->n_steps * sizeof(RadVocabStep)) ||
(h->n_tokens && !h->tok_text_off) || (h->n_merges && !h->merge_off) ||
(h->n_steps && !h->step_off)) {
RAD_ERR("the vocab section's arrays do not fit inside its %lld bytes, or one its count "
"names is absent. Its offsets must be "
"SECTION-RELATIVE -- serialise with a section_file_off of 0 and let finish() "
"rebase them.", (long long)bytes);
return RAD_E_INVAL;
+7 -1
View File
@@ -295,7 +295,13 @@ int SafeTensorsFile::open(const std::string& path) {
return RAD_E_FORMAT;
}
index_.emplace(t.name, tensors_.size());
/* A JSON object's keys are unique; a header naming one tensor twice has two answers to
* find() and is refused rather than resolved to the first. */
if (!index_.emplace(t.name, tensors_.size()).second) {
RAD_ERR("%s: the header names '%s' twice", path.c_str(), name.c_str());
close();
return RAD_E_FORMAT;
}
tensors_.push_back(std::move(t));
if (!sc.eat(',')) break;
+14
View File
@@ -155,6 +155,20 @@ int weight_share(const WeightInfo& w, const RadEncoding& enc, uint32_t rank, con
}
}
/* The view's rectangles come from plugin-stated spans and parts, sum-checked only. A single
* selected plane takes them as its own rectangles below, with no enc_plane_rect to bound
* them, so every one is held to the entry here. */
for (int g = 0; !whole && g < w.n_part_spans; ++g)
if (w.part_lo[g] < 0 || w.part_lo[g] > w.part_hi[g] || w.part_hi[g] > w.part_total[g])
return refuse(fmt("part %d's span [%lld, %lld) is outside its %lld", g,
(long long)w.part_lo[g], (long long)w.part_hi[g],
(long long)w.part_total[g]));
for (const VRect& q : view)
if (q.r0 < 0 || q.r0 > q.r1 || q.r1 > VR || q.c0 < 0 || q.c0 > q.c1 || q.c1 > VC)
return refuse(fmt("the slice [%lld, %lld) x [%lld, %lld) is outside the entry's "
"%lld x %lld", (long long)q.r0, (long long)q.r1, (long long)q.c0,
(long long)q.c1, (long long)VR, (long long)VC));
for (int k = 0; k < w.n_sel; ++k) {
const RadEncPlane& p = enc.plane[w.sel[k]];
PlaneShare& s = out[k];
+9 -4
View File
@@ -175,10 +175,15 @@ int TuneCache::load(const std::string& home, const std::string& machine) {
continue;
}
if (tok[0] == "machine") {
if (tok.size() >= 2 && std::string(tok[1]) != machine)
RAD_WARN("%s: measured on '%.*s' but this machine is '%s' -- the rows may not "
"describe this card", path.c_str(), (int)tok[1].size(), tok[1].data(),
machine.c_str());
/* A cache from another card is wrong, not just slow (tunecache.h): a file renamed or
* copied to this machine's name is refused, as another format version is. */
if (tok.size() >= 2 && std::string(tok[1]) != machine) {
RAD_WARN("%s: measured on '%.*s' but this machine is '%s' -- ignoring the cache",
path.c_str(), (int)tok[1].size(), tok[1].data(), machine.c_str());
std::free(line);
::fclose(f);
return RAD_E_FORMAT;
}
continue;
}
if (tok.size() < 5) { ++bad; continue; }
+771
View File
@@ -0,0 +1,771 @@
/* shape.cpp -- the shape generator's host geometry (shape.h): the picture, the sampler's grid, the
* field's levels, marching cubes and the mesh's files; and the ticket a caller waits on. */
#include "shape.h"
#include "rad_internal.h"
#include <nlohmann/json.hpp>
#include <algorithm>
#include <array>
#include <chrono>
#include <cmath>
#include <cstring>
namespace rad {
namespace gen {
ShapeGenInfo shape_info(const RadShapeGenDecl& d, const std::string& name) {
ShapeGenInfo g;
g.name = name;
g.canvas = d.canvas;
g.enc_size = d.enc_size;
g.enc_patch = d.enc_patch;
g.border_ratio = d.border_ratio;
for (int c = 0; c < 3; ++c) { g.pix_mean[c] = d.pix_mean[c]; g.pix_std[c] = d.pix_std[c]; }
g.default_steps = d.default_steps;
g.max_steps = d.max_steps;
g.default_guidance = d.default_guidance;
g.bounds = d.bounds;
g.level = d.level;
g.default_resolution = d.default_resolution;
g.min_resolution = d.min_resolution;
g.max_resolution = d.max_resolution;
g.max_lanes = d.max_lanes;
return g;
}
/* ================================================================== the picture */
namespace {
/* An 8-bit image, `ch` channels interleaved. */
struct Img {
int32_t w = 0, h = 0, ch = 0;
std::vector<uint8_t> px;
uint8_t* at(int32_t y, int32_t x) { return px.data() + ((size_t)y * w + x) * ch; }
const uint8_t* at(int32_t y, int32_t x) const { return px.data() + ((size_t)y * w + x) * ch; }
};
/* OpenCV's saturate_cast<uchar> of a float: round half to even, clipped. */
inline uint8_t sat_u8(float v) {
const float r = std::nearbyint(v);
return (uint8_t)(r < 0.0f ? 0.0f : r > 255.0f ? 255.0f : r);
}
/* cv::resize's INTER_AREA when it shrinks both sides: computeResizeAreaTab's weights, a row's
* horizontal sums, then the weighted rows, in float. */
struct AreaTap { int32_t di, si; float alpha; };
std::vector<AreaTap> area_tab(int32_t ssize, int32_t dsize, double scale) {
std::vector<AreaTap> tab;
for (int32_t dx = 0; dx < dsize; ++dx) {
const double fsx1 = dx * scale, fsx2 = fsx1 + scale;
const double cell = std::min(scale, ssize - fsx1);
int32_t sx1 = (int32_t)std::ceil(fsx1), sx2 = (int32_t)std::floor(fsx2);
sx2 = std::min(sx2, ssize - 1);
sx1 = std::min(sx1, sx2);
if (sx1 - fsx1 > 1e-3) tab.push_back({ dx, sx1 - 1, (float)((sx1 - fsx1) / cell) });
for (int32_t sx = sx1; sx < sx2; ++sx) tab.push_back({ dx, sx, (float)(1.0 / cell) });
if (fsx2 - sx2 > 1e-3)
tab.push_back({ dx, sx2, (float)(std::min(std::min(fsx2 - sx2, 1.0), cell) / cell) });
}
return tab;
}
void resize_area_down(const Img& s, int32_t dw, int32_t dh, Img* d) {
const double sx = (double)s.w / dw, sy = (double)s.h / dh;
const std::vector<AreaTap> xt = area_tab(s.w, dw, sx), yt = area_tab(s.h, dh, sy);
const int32_t ch = s.ch;
std::vector<float> row((size_t)dw * ch), acc((size_t)dw * ch);
d->w = dw; d->h = dh; d->ch = ch;
d->px.assign((size_t)dw * dh * ch, 0);
size_t k = 0;
for (int32_t dy = 0; dy < dh; ++dy) {
std::fill(acc.begin(), acc.end(), 0.0f);
for (; k < yt.size() && yt[k].di == dy; ++k) {
std::fill(row.begin(), row.end(), 0.0f);
const uint8_t* src = s.at(yt[k].si, 0);
for (const AreaTap& t : xt)
for (int32_t c = 0; c < ch; ++c)
row[(size_t)t.di * ch + c] += src[(size_t)t.si * ch + c] * t.alpha;
for (size_t i = 0; i < acc.size(); ++i) acc[i] += row[i] * yt[k].alpha;
}
uint8_t* dst = d->at(dy, 0);
for (size_t i = 0; i < acc.size(); ++i) dst[i] = sat_u8(acc[i]);
}
}
/* cv::resize's fixed-point separable filter for 8-bit images: each tap's float coefficient
* rounded to 11 bits, the horizontal sums in int, the vertical sum shifted back by 22 with
* rounding. `taps` coefficients a destination pixel, first at source index ofs[d] (indices
* clamped to the image, OpenCV's BORDER_REPLICATE). */
struct Taps {
int32_t ksize = 0;
std::vector<int32_t> ofs;
std::vector<int16_t> c;
};
Taps taps_linear_area(int32_t ssize, int32_t dsize) {
/* INTER_AREA when it does not shrink both sides: linear taps in OpenCV's area mode. */
const double scale = (double)ssize / dsize, inv = (double)dsize / ssize;
Taps t;
t.ksize = 2;
for (int32_t dx = 0; dx < dsize; ++dx) {
const int32_t sx = (int32_t)std::floor(dx * scale);
float fx = (float)((dx + 1) - (sx + 1) * inv);
fx = fx <= 0 ? 0.0f : fx - std::floor(fx);
t.ofs.push_back(sx);
t.c.push_back((int16_t)std::nearbyint((1.0f - fx) * 2048.0f));
t.c.push_back((int16_t)std::nearbyint(fx * 2048.0f));
}
return t;
}
Taps taps_cubic(int32_t ssize, int32_t dsize) {
const double scale = (double)ssize / dsize;
const float A = -0.75f;
Taps t;
t.ksize = 4;
for (int32_t dx = 0; dx < dsize; ++dx) {
float fx = (float)((dx + 0.5) * scale - 0.5);
const int32_t sx = (int32_t)std::floor(fx);
fx -= sx;
float w[4];
w[0] = ((A * (fx + 1) - 5 * A) * (fx + 1) + 8 * A) * (fx + 1) - 4 * A;
w[1] = ((A + 2) * fx - (A + 3)) * fx * fx + 1;
w[2] = ((A + 2) * (1 - fx) - (A + 3)) * (1 - fx) * (1 - fx) + 1;
w[3] = 1.0f - w[0] - w[1] - w[2];
t.ofs.push_back(sx - 1);
for (float v : w) t.c.push_back((int16_t)std::nearbyint(v * 2048.0f));
}
return t;
}
void resize_fixed(const Img& s, const Taps& tx, const Taps& ty, int32_t dw, int32_t dh, Img* d) {
const int32_t ch = s.ch;
/* Every source row through the horizontal taps, then each destination row from its rows. */
std::vector<int32_t> hrow((size_t)s.h * dw * ch);
for (int32_t y = 0; y < s.h; ++y)
for (int32_t dx = 0; dx < dw; ++dx)
for (int32_t c = 0; c < ch; ++c) {
int32_t sum = 0;
for (int32_t k = 0; k < tx.ksize; ++k) {
const int32_t sx = std::clamp(tx.ofs[(size_t)dx] + k, 0, s.w - 1);
sum += s.at(y, sx)[c] * tx.c[(size_t)dx * tx.ksize + k];
}
hrow[((size_t)y * dw + dx) * ch + c] = sum;
}
d->w = dw; d->h = dh; d->ch = ch;
d->px.assign((size_t)dw * dh * ch, 0);
for (int32_t dy = 0; dy < dh; ++dy)
for (int32_t i = 0; i < dw * ch; ++i) {
int64_t v = 0;
for (int32_t k = 0; k < ty.ksize; ++k) {
const int32_t sy = std::clamp(ty.ofs[(size_t)dy] + k, 0, s.h - 1);
v += (int64_t)hrow[(size_t)sy * dw * ch + i] * ty.c[(size_t)dy * ty.ksize + k];
}
const int64_t r = (v + (1 << 21)) >> 22;
d->px[(size_t)dy * dw * ch + i] = (uint8_t)std::clamp<int64_t>(r, 0, 255);
}
}
/* cv2.resize(src, (dw, dh), INTER_AREA). */
void resize_area(const Img& s, int32_t dw, int32_t dh, Img* d) {
if (dw == s.w && dh == s.h) { *d = s; return; }
if (s.w >= dw && s.h >= dh) { resize_area_down(s, dw, dh, d); return; }
resize_fixed(s, taps_linear_area(s.w, dw), taps_linear_area(s.h, dh), dw, dh, d);
}
/* cv2.resize(src, (dw, dh), INTER_CUBIC). */
void resize_cubic(const Img& s, int32_t dw, int32_t dh, Img* d) {
if (dw == s.w && dh == s.h) { *d = s; return; }
resize_fixed(s, taps_cubic(s.w, dw), taps_cubic(s.h, dh), dw, dh, d);
}
/* torchvision's antialiased bilinear resize along one axis (align_corners false): the triangle
* filter around each output's centre, widened by the scale when shrinking, normalised over the
* taps inside the image. */
struct AaTaps { std::vector<int32_t> lo; std::vector<std::vector<float>> w; };
AaTaps aa_taps(int32_t in, int32_t out) {
const double scale = (double)in / out;
const double support = scale >= 1.0 ? scale : 1.0;
const double inv = scale >= 1.0 ? 1.0 / scale : 1.0;
AaTaps t;
for (int32_t i = 0; i < out; ++i) {
const double center = scale * (i + 0.5);
const int32_t lo = std::max((int32_t)(center - support + 0.5), 0);
const int32_t hi = std::min((int32_t)(center + support + 0.5), in);
std::vector<float> w;
double total = 0.0;
for (int32_t j = lo; j < hi; ++j) {
const double x = std::fabs((j - center + 0.5) * inv);
const double v = x < 1.0 ? 1.0 - x : 0.0;
w.push_back((float)v);
total += v;
}
if (total > 0.0) for (float& v : w) v = (float)(v / total);
t.lo.push_back(lo);
t.w.push_back(std::move(w));
}
return t;
}
} /* namespace */
int shape_picture(const ShapeGenInfo& g, const mm::FrameRGBA& rgba, std::vector<float>* patches,
std::string* why) {
auto no = [&](const std::string& w) {
if (why) *why = w;
return RAD_E_INVAL;
};
const int32_t H = rgba.h, W = rgba.w;
if (H < 1 || W < 1 || rgba.rgba.size() != (size_t)H * W * 4) return no("the picture is empty");
/* ---- ImageProcessorV2.recenter: the alpha's bounding box on a square of the longer side */
int32_t y0 = H, y1 = -1, x0 = W, x1 = -1;
for (int32_t y = 0; y < H; ++y)
for (int32_t x = 0; x < W; ++x)
if (rgba.rgba[((size_t)y * W + x) * 4 + 3]) {
y0 = std::min(y0, y); y1 = std::max(y1, y);
x0 = std::min(x0, x); x1 = std::max(x1, x);
}
if (y1 < 0) return no("the picture is fully transparent: nothing to make a shape of");
const int32_t h = y1 - y0, w = x1 - x0;
if (h == 0 || w == 0)
return no("the picture's opaque part is a single row or column: nothing to make a shape "
"of");
const int32_t size = std::max(H, W);
const int32_t desired = (int32_t)(size * (1.0 - g.border_ratio));
const double scale = (double)desired / std::max(h, w);
const int32_t h2 = (int32_t)(h * scale), w2 = (int32_t)(w * scale);
if (h2 < 1 || w2 < 1)
return no("the picture's opaque part is too thin to scale onto the canvas");
Img crop;
crop.w = w; crop.h = h; crop.ch = 4;
crop.px.resize((size_t)w * h * 4);
for (int32_t y = 0; y < h; ++y)
std::memcpy(crop.at(y, 0), rgba.rgba.data() + ((size_t)(y0 + y) * W + x0) * 4,
(size_t)w * 4);
Img fit;
resize_area(crop, w2, h2, &fit);
const int32_t oy = (size - h2) / 2, ox = (size - w2) / 2;
/* Flattened onto white in float, then truncated to 8 bits, as numpy's astype does. */
Img sq;
sq.w = size; sq.h = size; sq.ch = 3;
sq.px.assign((size_t)size * size * 3, 255);
for (int32_t y = 0; y < h2; ++y)
for (int32_t x = 0; x < w2; ++x) {
const uint8_t* p = fit.at(y, x);
const float a = (float)p[3] / 255.0f;
uint8_t* q = sq.at(oy + y, ox + x);
for (int c = 0; c < 3; ++c) {
const float v = (float)p[c] * a + 255.0f * (1.0f - a);
q[c] = (uint8_t)std::clamp(v, 0.0f, 255.0f);
}
}
/* ---- the canvas, INTER_CUBIC */
const int32_t C = (int32_t)g.canvas;
Img can;
resize_cubic(sq, C, C, &can);
/* ---- the encoder's transform: 0..1, bilinear (antialiased) to enc_size, normalised */
const int32_t E = (int32_t)g.enc_size, P = (int32_t)g.enc_patch, G = E / P;
const AaTaps ta = aa_taps(C, E);
std::vector<float> hor((size_t)C * E * 3), img((size_t)E * E * 3);
for (int32_t y = 0; y < C; ++y)
for (int32_t x = 0; x < E; ++x)
for (int c = 0; c < 3; ++c) {
float s = 0.0f;
const std::vector<float>& wt = ta.w[(size_t)x];
for (size_t k = 0; k < wt.size(); ++k)
s += wt[k] * ((float)can.at(y, ta.lo[(size_t)x] + (int32_t)k)[c] / 255.0f);
hor[((size_t)y * E + x) * 3 + c] = s;
}
for (int32_t y = 0; y < E; ++y)
for (int32_t x = 0; x < E; ++x)
for (int c = 0; c < 3; ++c) {
float s = 0.0f;
const std::vector<float>& wt = ta.w[(size_t)y];
for (size_t k = 0; k < wt.size(); ++k)
s += wt[k] * hor[(((size_t)ta.lo[(size_t)y] + k) * E + x) * 3 + c];
img[((size_t)y * E + x) * 3 + c] =
(float)((s - g.pix_mean[c]) / g.pix_std[c]);
}
/* ---- patches, row-major; a patch's values (channel, row, column) */
const int64_t pd = 3 * (int64_t)P * P;
patches->assign((size_t)G * G * pd, 0.0f);
for (int32_t py = 0; py < G; ++py)
for (int32_t px = 0; px < G; ++px) {
float* o = patches->data() + ((size_t)py * G + px) * pd;
for (int c = 0; c < 3; ++c)
for (int32_t i = 0; i < P; ++i)
for (int32_t j = 0; j < P; ++j)
o[((size_t)c * P + i) * P + j] =
img[(((size_t)py * P + i) * E + px * P + j) * 3 + c];
}
return RAD_OK;
}
/* ================================================================== the sampler and the grid */
std::vector<float> shape_sigmas(int32_t steps) {
std::vector<float> s;
if (steps < 2) return s;
const double step = 1.0 / (steps - 1);
for (int32_t i = 0; i < steps; ++i) s.push_back(i == steps - 1 ? 1.0f : (float)(i * step));
return s;
}
std::vector<int32_t> shape_levels(int32_t resolution) {
std::vector<int32_t> r;
if (resolution < 63) r.push_back(resolution);
for (int32_t v = resolution; v >= 63; v /= 2) r.push_back(v);
std::reverse(r.begin(), r.end());
return r;
}
std::vector<float> shape_axis(double bounds, int32_t r) {
std::vector<float> a((size_t)r + 1);
const double step = 2.0 * bounds / r;
for (int32_t i = 0; i <= r; ++i) a[(size_t)i] = (float)(i * step + -bounds);
a[(size_t)r] = (float)bounds;
return a;
}
namespace {
/* A 3 x 3 x 3 dilation of an n^3 mask (zero outside), as separable maxima along each axis. */
void dilate(std::vector<uint8_t>& m, int64_t n) {
std::vector<uint8_t> t(m.size());
auto pass = [&](const std::vector<uint8_t>& src, std::vector<uint8_t>& dst, int64_t stride) {
for (int64_t p = 0; p < (int64_t)src.size(); ++p) {
const int64_t c = (p / stride) % n;
uint8_t v = src[(size_t)p];
if (c > 0) v |= src[(size_t)(p - stride)];
if (c + 1 < n) v |= src[(size_t)(p + stride)];
dst[(size_t)p] = v;
}
};
pass(m, t, 1);
pass(t, m, n);
pass(m, t, n * n);
m.swap(t);
}
} /* namespace */
std::vector<uint32_t> shape_refine(const std::vector<float>& prev, int32_t rp, int32_t r,
double level, bool last) {
const int64_t np = (int64_t)rp + 1, n = (int64_t)r + 1;
std::vector<uint8_t> near((size_t)(np * np * np), 0);
auto sgn = [](float v) { return (v > 0.0f) - (v < 0.0f); };
const float lv = (float)level;
for (int64_t i = 0; i < np; ++i)
for (int64_t j = 0; j < np; ++j)
for (int64_t k = 0; k < np; ++k) {
const int64_t p = (i * np + j) * np + k;
const float raw = prev[(size_t)p];
if (std::isnan(raw)) continue;
const float v = raw - lv;
const int s = sgn(v);
bool cross = std::fabs(v) < 0.95f;
const int64_t nb[6][3] = { { i - 1, j, k }, { i + 1, j, k }, { i, j - 1, k },
{ i, j + 1, k }, { i, j, k - 1 }, { i, j, k + 1 } };
for (int q = 0; q < 6 && !cross; ++q) {
const int64_t a = nb[q][0], b = nb[q][1], c = nb[q][2];
/* Outside the grid the reference replicates the border, and a neighbour not
* sampled stands in as the point itself: neither crosses. */
if (a < 0 || a >= np || b < 0 || b >= np || c < 0 || c >= np) continue;
const float u = prev[(size_t)((a * np + b) * np + c)];
if (std::isnan(u)) continue;
cross = sgn(u - lv) != s;
}
near[(size_t)p] = cross;
}
if (!last) dilate(near, np);
std::vector<uint8_t> mark((size_t)(n * n * n), 0);
auto up = [&](int64_t c) { return (c * r + rp / 2) / rp; };
for (int64_t i = 0; i < np; ++i)
for (int64_t j = 0; j < np; ++j)
for (int64_t k = 0; k < np; ++k)
if (near[(size_t)((i * np + j) * np + k)])
mark[(size_t)((up(i) * n + up(j)) * n + up(k))] = 1;
dilate(mark, n);
if (last) dilate(mark, n);
std::vector<uint32_t> pts;
for (int64_t p = 0; p < (int64_t)mark.size(); ++p)
if (mark[(size_t)p]) pts.push_back((uint32_t)p);
return pts;
}
/* ================================================================== marching cubes */
namespace {
/* Corner c of a cube is at (c & 1, c >> 1 & 1, c >> 2 & 1) along the grid's (i, j, k). Edge e is
* along axis e / 4 from corner kEdge[e][0] to kEdge[e][1]. */
struct McTables {
int32_t edge[12][2];
/* Each case's triangles as edge triples, -1 ended. */
int8_t tri[256][31];
};
McTables build_tables() {
McTables T{};
int ne = 0;
for (int a = 0; a < 3; ++a)
for (int c = 0; c < 8; ++c)
if (!(c >> a & 1)) { T.edge[ne][0] = c; T.edge[ne][1] = c | (1 << a); ++ne; }
auto edge_of = [&](int c0, int c1) {
for (int e = 0; e < 12; ++e)
if ((T.edge[e][0] == c0 && T.edge[e][1] == c1) ||
(T.edge[e][0] == c1 && T.edge[e][1] == c0))
return e;
return -1;
};
auto pos = [](int c, double* p) { p[0] = c & 1; p[1] = c >> 1 & 1; p[2] = c >> 2 & 1; };
for (int m = 0; m < 256; ++m) {
for (int i = 0; i < 31; ++i) T.tri[m][i] = -1;
if (m == 0 || m == 255) continue;
auto in = [&](int c) { return (m >> c & 1) != 0; };
/* Each face's segments between its crossing edges. A face with all four edges crossing
* (its inside corners diagonal) separates the inside corners, the rule both cubes that
* share the face apply, so the surface has no cracks. */
std::vector<std::array<int, 2>> seg;
for (int a = 0; a < 3; ++a)
for (int s = 0; s < 2; ++s) {
const int u = (a + 1) % 3, v = (a + 2) % 3;
const int base = s << a;
const int cyc[4] = { base, base | (1 << u), base | (1 << u) | (1 << v),
base | (1 << v) };
int fe[4];
bool cr[4];
int ncr = 0;
for (int q = 0; q < 4; ++q) {
fe[q] = edge_of(cyc[q], cyc[(q + 1) % 4]);
cr[q] = in(cyc[q]) != in(cyc[(q + 1) % 4]);
ncr += cr[q];
}
if (ncr == 2) {
int a0 = -1, a1 = -1;
for (int q = 0; q < 4; ++q) {
if (!cr[q]) continue;
if (a0 < 0) a0 = fe[q]; else a1 = fe[q];
}
seg.push_back({ a0, a1 });
} else if (ncr == 4) {
for (int q = 0; q < 4; ++q)
if (in(cyc[q])) seg.push_back({ fe[(q + 3) % 4], fe[q] });
}
}
/* The segments close into loops; each crossing edge is in exactly two. */
std::vector<bool> used(seg.size(), false);
int nt = 0;
for (size_t s0 = 0; s0 < seg.size(); ++s0) {
if (used[s0]) continue;
std::vector<int> loop = { seg[s0][0], seg[s0][1] };
used[s0] = true;
for (bool grew = true; grew;) {
grew = false;
for (size_t q = 0; q < seg.size(); ++q) {
if (used[q]) continue;
const int tail = loop.back();
int nx = -1;
if (seg[q][0] == tail) nx = seg[q][1];
else if (seg[q][1] == tail) nx = seg[q][0];
if (nx < 0) continue;
used[q] = true;
grew = true;
if (nx != loop.front()) loop.push_back(nx);
}
}
/* Orientation: the loop's normal (Newell's, over the edges' midpoints) points from the
* inside corners to the outside ones. */
double nrm[3] = { 0, 0, 0 }, out[3] = { 0, 0, 0 };
std::vector<std::array<double, 3>> mid;
for (int e : loop) {
double p0[3], p1[3];
pos(T.edge[e][0], p0);
pos(T.edge[e][1], p1);
mid.push_back({ (p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2, (p0[2] + p1[2]) / 2 });
const double sg = in(T.edge[e][0]) ? 1.0 : -1.0;
for (int d = 0; d < 3; ++d) out[d] += sg * (p1[d] - p0[d]);
}
for (size_t q = 0; q < mid.size(); ++q) {
const auto& c = mid[q];
const auto& d = mid[(q + 1) % mid.size()];
nrm[0] += (c[1] - d[1]) * (c[2] + d[2]);
nrm[1] += (c[2] - d[2]) * (c[0] + d[0]);
nrm[2] += (c[0] - d[0]) * (c[1] + d[1]);
}
if (nrm[0] * out[0] + nrm[1] * out[1] + nrm[2] * out[2] < 0)
std::reverse(loop.begin(), loop.end());
for (size_t q = 1; q + 1 < loop.size() && nt < 10; ++q) {
T.tri[m][3 * nt] = (int8_t)loop[0];
T.tri[m][3 * nt + 1] = (int8_t)loop[q];
T.tri[m][3 * nt + 2] = (int8_t)loop[q + 1];
++nt;
}
}
}
return T;
}
const McTables& tables() {
static const McTables t = build_tables();
return t;
}
} /* namespace */
void shape_mesh(const std::vector<float>& field, int32_t r, double bounds, double level,
ShapeMesh* out) {
out->v.clear();
out->f.clear();
const McTables& T = tables();
const int64_t n = (int64_t)r + 1, nn = n * n;
const float lv = (float)level;
const double sc = 2.0 * bounds / (double)n;
/* An edge's vertex by its first grid point: the x edges between planes i and i + 1, and the
* y and z edges of planes i and i + 1. */
std::vector<int32_t> ex((size_t)nn), ey[2], ez[2];
for (int p = 0; p < 2; ++p) { ey[p].assign((size_t)nn, -1); ez[p].assign((size_t)nn, -1); }
auto value = [&](int64_t i, int64_t j, int64_t k) {
return field[(size_t)((i * n + j) * n + k)];
};
for (int64_t i = 0; i + 1 < n; ++i) {
std::fill(ex.begin(), ex.end(), -1);
if (i > 0) {
std::swap(ey[0], ey[1]);
std::swap(ez[0], ez[1]);
std::fill(ey[1].begin(), ey[1].end(), -1);
std::fill(ez[1].begin(), ez[1].end(), -1);
}
for (int64_t j = 0; j + 1 < n; ++j)
for (int64_t k = 0; k + 1 < n; ++k) {
float v[8];
bool skip = false;
int m = 0;
for (int c = 0; c < 8 && !skip; ++c) {
v[c] = value(i + (c & 1), j + (c >> 1 & 1), k + (c >> 2 & 1));
if (std::isnan(v[c])) skip = true;
else if (v[c] > lv) m |= 1 << c;
}
if (skip || m == 0 || m == 255) continue;
for (int t = 0; t < 30 && T.tri[m][t] >= 0; ++t) {
const int e = T.tri[m][t];
const int c0 = T.edge[e][0], c1 = T.edge[e][1], a = e / 4;
const int64_t bi = c0 & 1, bj = c0 >> 1 & 1, bk = c0 >> 2 & 1;
int32_t* slot = a == 0 ? &ex[(size_t)((j + bj) * n + k + bk)]
: a == 1 ? &ey[bi][(size_t)(j * n + k + bk)]
: &ez[bi][(size_t)((j + bj) * n + k)];
if (*slot < 0) {
const float t0 = v[c0], t1 = v[c1];
const float f = t1 != t0 ? (lv - t0) / (t1 - t0) : 0.5f;
float g[3] = { (float)(i + bi), (float)(j + bj), (float)(k + bk) };
g[a] += f;
*slot = (int32_t)(out->v.size() / 3);
for (int d = 0; d < 3; ++d) out->v.push_back((float)(g[d] * sc - bounds));
}
out->f.push_back((uint32_t)*slot);
}
}
}
}
/* ================================================================== files */
namespace {
void put(std::string& s, const void* p, size_t n) { s.append((const char*)p, n); }
template <class T> void put_v(std::string& s, T v) { put(s, &v, sizeof v); }
/* Area-weighted vertex normals, unit length (zero for a vertex of only degenerate faces). */
std::vector<float> vertex_normals(const ShapeMesh& m) {
std::vector<float> nrm(m.v.size(), 0.0f);
for (size_t t = 0; t + 2 < m.f.size(); t += 3) {
const float* a = &m.v[(size_t)m.f[t] * 3];
const float* b = &m.v[(size_t)m.f[t + 1] * 3];
const float* c = &m.v[(size_t)m.f[t + 2] * 3];
const float u[3] = { b[0] - a[0], b[1] - a[1], b[2] - a[2] };
const float w[3] = { c[0] - a[0], c[1] - a[1], c[2] - a[2] };
const float x[3] = { u[1] * w[2] - u[2] * w[1], u[2] * w[0] - u[0] * w[2],
u[0] * w[1] - u[1] * w[0] };
for (int q = 0; q < 3; ++q)
for (int d = 0; d < 3; ++d) nrm[(size_t)m.f[t + q] * 3 + d] += x[d];
}
for (size_t i = 0; i + 2 < nrm.size(); i += 3) {
const float l =
std::sqrt(nrm[i] * nrm[i] + nrm[i + 1] * nrm[i + 1] + nrm[i + 2] * nrm[i + 2]);
if (l > 0.0f) for (int d = 0; d < 3; ++d) nrm[i + d] /= l;
}
return nrm;
}
std::string glb(const ShapeMesh& m) {
const size_t nv = m.v.size() / 3, ni = m.f.size();
const std::vector<float> nrm = vertex_normals(m);
float lo[3] = { INFINITY, INFINITY, INFINITY }, hi[3] = { -INFINITY, -INFINITY, -INFINITY };
for (size_t i = 0; i < nv; ++i)
for (int d = 0; d < 3; ++d) {
lo[d] = std::min(lo[d], m.v[i * 3 + d]);
hi[d] = std::max(hi[d], m.v[i * 3 + d]);
}
const size_t vb = nv * 12, ib = ni * 4;
std::string bin;
put(bin, m.v.data(), vb);
put(bin, nrm.data(), vb);
put(bin, m.f.data(), ib);
while (bin.size() % 4) bin.push_back('\0');
using nlohmann::json;
json j;
j["asset"] = { { "version", "2.0" }, { "generator", "radiance" } };
j["scene"] = 0;
j["scenes"] = json::array({ { { "nodes", json::array({ 0 }) } } });
j["nodes"] = json::array({ { { "mesh", 0 } } });
const json prim = { { "attributes", { { "POSITION", 0 }, { "NORMAL", 1 } } },
{ "indices", 2 }, { "mode", 4 } };
j["meshes"] = json::array({ { { "primitives", json::array({ prim }) } } });
j["buffers"] = json::array({ { { "byteLength", bin.size() } } });
j["bufferViews"] = json::array({
{ { "buffer", 0 }, { "byteOffset", 0 }, { "byteLength", vb }, { "target", 34962 } },
{ { "buffer", 0 }, { "byteOffset", vb }, { "byteLength", vb }, { "target", 34962 } },
{ { "buffer", 0 }, { "byteOffset", 2 * vb }, { "byteLength", ib }, { "target", 34963 } } });
j["accessors"] = json::array({
{ { "bufferView", 0 }, { "componentType", 5126 }, { "count", nv }, { "type", "VEC3" },
{ "min", { lo[0], lo[1], lo[2] } }, { "max", { hi[0], hi[1], hi[2] } } },
{ { "bufferView", 1 }, { "componentType", 5126 }, { "count", nv }, { "type", "VEC3" } },
{ { "bufferView", 2 }, { "componentType", 5125 }, { "count", ni },
{ "type", "SCALAR" } } });
std::string js = j.dump();
while (js.size() % 4) js.push_back(' ');
std::string out;
put_v<uint32_t>(out, 0x46546C67u); /* "glTF" */
put_v<uint32_t>(out, 2);
put_v<uint32_t>(out, (uint32_t)(12 + 8 + js.size() + 8 + bin.size()));
put_v<uint32_t>(out, (uint32_t)js.size());
put_v<uint32_t>(out, 0x4E4F534Au); /* "JSON" */
out += js;
put_v<uint32_t>(out, (uint32_t)bin.size());
put_v<uint32_t>(out, 0x004E4942u); /* "BIN\0" */
out += bin;
return out;
}
std::string obj(const ShapeMesh& m) {
std::string s;
char line[128];
for (size_t i = 0; i + 2 < m.v.size(); i += 3) {
const int n = std::snprintf(line, sizeof line, "v %.9g %.9g %.9g\n", (double)m.v[i],
(double)m.v[i + 1], (double)m.v[i + 2]);
s.append(line, (size_t)n);
}
for (size_t t = 0; t + 2 < m.f.size(); t += 3) {
const int n = std::snprintf(line, sizeof line, "f %u %u %u\n", m.f[t] + 1, m.f[t + 1] + 1,
m.f[t + 2] + 1);
s.append(line, (size_t)n);
}
return s;
}
std::string ply(const ShapeMesh& m) {
const size_t nv = m.v.size() / 3, nf = m.f.size() / 3;
std::string s = "ply\nformat binary_little_endian 1.0\nelement vertex " + std::to_string(nv) +
"\nproperty float x\nproperty float y\nproperty float z\nelement face " +
std::to_string(nf) + "\nproperty list uchar int vertex_indices\nend_header\n";
put(s, m.v.data(), m.v.size() * 4);
for (size_t t = 0; t < nf; ++t) {
put_v<uint8_t>(s, 3);
for (int q = 0; q < 3; ++q) put_v<int32_t>(s, (int32_t)m.f[t * 3 + q]);
}
return s;
}
std::string stl(const ShapeMesh& m) {
std::string s(80, '\0');
std::memcpy(&s[0], "radiance", 8);
const size_t nf = m.f.size() / 3;
put_v<uint32_t>(s, (uint32_t)nf);
for (size_t t = 0; t < nf; ++t) {
const float* a = &m.v[(size_t)m.f[t * 3] * 3];
const float* b = &m.v[(size_t)m.f[t * 3 + 1] * 3];
const float* c = &m.v[(size_t)m.f[t * 3 + 2] * 3];
const float u[3] = { b[0] - a[0], b[1] - a[1], b[2] - a[2] };
const float w[3] = { c[0] - a[0], c[1] - a[1], c[2] - a[2] };
float x[3] = { u[1] * w[2] - u[2] * w[1], u[2] * w[0] - u[0] * w[2],
u[0] * w[1] - u[1] * w[0] };
const float l = std::sqrt(x[0] * x[0] + x[1] * x[1] + x[2] * x[2]);
if (l > 0.0f) for (float& q : x) q /= l;
put(s, x, 12);
put(s, a, 12);
put(s, b, 12);
put(s, c, 12);
put_v<uint16_t>(s, 0);
}
return s;
}
} /* namespace */
int shape_export(const ShapeMesh& m, const std::string& format, std::string* bytes,
std::string* mime, std::string* why) {
if (format == "glb") { *bytes = glb(m); *mime = "model/gltf-binary"; return RAD_OK; }
if (format == "obj") { *bytes = obj(m); *mime = "model/obj"; return RAD_OK; }
if (format == "ply") { *bytes = ply(m); *mime = "application/x-ply"; return RAD_OK; }
if (format == "stl") { *bytes = stl(m); *mime = "model/stl"; return RAD_OK; }
if (why) *why = "type '" + format + "' is not one this server writes: glb, obj, ply or stl";
return RAD_E_INVAL;
}
/* ================================================================== the ticket */
void ShapeTicket::progress(int32_t steps_done, int32_t points_done) {
std::lock_guard<std::mutex> lk(mu_);
steps_done_ = steps_done;
points_done_ = points_done;
}
void ShapeTicket::set_field(std::vector<float>&& field, int32_t r) {
std::lock_guard<std::mutex> lk(mu_);
field_ = std::move(field);
r_ = r;
}
void ShapeTicket::finish(int status, const std::string& why) {
{
std::lock_guard<std::mutex> lk(mu_);
if (done_) return;
done_ = true;
status_ = status;
why_ = why;
}
cv_.notify_all();
}
bool ShapeTicket::wait(int ms) {
std::unique_lock<std::mutex> lk(mu_);
cv_.wait_for(lk, std::chrono::milliseconds(ms), [this] { return done_; });
return done_;
}
bool ShapeTicket::finished() const {
std::lock_guard<std::mutex> lk(mu_);
return done_;
}
int ShapeTicket::status() const {
std::lock_guard<std::mutex> lk(mu_);
return status_;
}
std::string ShapeTicket::why() const {
std::lock_guard<std::mutex> lk(mu_);
return why_;
}
std::vector<float> ShapeTicket::take_field(int32_t* r) {
std::lock_guard<std::mutex> lk(mu_);
if (r) *r = r_;
return std::move(field_);
}
void ShapeTicket::progress_of(int32_t* steps_done, int32_t* points_done) const {
std::lock_guard<std::mutex> lk(mu_);
if (steps_done) *steps_done = steps_done_;
if (points_done) *points_done = points_done_;
}
} /* namespace gen */
} /* namespace rad */
+137
View File
@@ -0,0 +1,137 @@
/* shape.h -- shape generation: the request, the channel its field comes back on, and the host
* geometry around the model's passes.
*
* A shape generator (abi/rad_builder.h, rad_declare_shape_generator) makes a 3-D shape from one
* picture: it denoises a latent, then decodes it into an occupancy field that is sampled on a
* grid. core/gen/shape_driver.h turns a request into those passes; this is what a caller hands it
* (the picture already prepared, shape_picture), what it hands back (progress as the steps and
* the grid's levels run, then the finest grid), and the geometry both sides share: the sampler's
* sigmas, the grid's levels and the points each level queries, and the mesh made of the grid
* (shape_mesh) with its file formats.
*/
#pragma once
#include "rad_core.h"
#include "mm/media.h"
#include <atomic>
#include <cmath>
#include <condition_variable>
#include <cstdint>
#include <memory>
#include <mutex>
#include <string>
#include <vector>
namespace rad {
namespace gen {
/* What the driver knows of the declaration, for the server and the geometry below. */
struct ShapeGenInfo {
std::string name;
int64_t canvas = 0, enc_size = 0, enc_patch = 0;
double border_ratio = 0.0;
double pix_mean[3] = {}, pix_std[3] = {};
int64_t default_steps = 0, max_steps = 0;
double default_guidance = 0.0;
double bounds = 1.0, level = 0.0;
int64_t default_resolution = 0, min_resolution = 0, max_resolution = 0;
int64_t max_lanes = 1;
};
ShapeGenInfo shape_info(const RadShapeGenDecl& d, const std::string& name);
/* The picture as an SCOND pass carries it (RadShapeGenDecl, "The picture"): `rgba` decoded with
* its alpha, out as f32 [(enc_size / enc_patch)^2, 3 enc_patch^2]. Refuses a picture whose alpha
* leaves nothing, or a bounding box of one row or column, as the reference does. */
int shape_picture(const ShapeGenInfo& g, const mm::FrameRGBA& rgba, std::vector<float>* patches,
std::string* why);
/* The sampler's grid points: numpy's linspace(0, 1, steps) taken to f32. An evaluation at each
* but the last steps to the next. */
std::vector<float> shape_sigmas(int32_t steps);
/* The grid's levels, coarsest first: `resolution` halved while it stays at least 63, then
* reversed (one level when it is below 63). */
std::vector<int32_t> shape_levels(int32_t resolution);
/* One axis of a level's grid: numpy's linspace(-bounds, bounds, r + 1) in f32. */
std::vector<float> shape_axis(double bounds, int32_t r);
/* The grid points of level `r` (index (i, j, k) at (i (r+1) + j) (r+1) + k) to query, given the
* coarser level's field `prev` at resolution `rp` (NaN where it was not sampled): the coarse
* points whose sign against `level` differs from a neighbour's, or whose value is within 0.95 of
* zero, dilated once unless this is the last level, put at their places on this grid and dilated
* twice there (once when the coarse set was). As FlashVDM's hierarchical decoding. */
std::vector<uint32_t> shape_refine(const std::vector<float>& prev, int32_t rp, int32_t r,
double level, bool last);
/* A triangle mesh: positions xyz, and faces as three vertex indices, counter-clockwise seen from
* outside the shape. */
struct ShapeMesh {
std::vector<float> v;
std::vector<uint32_t> f;
};
/* Marching cubes over `field` ((r+1)^3 values, the layout above) at `level`, inside above it. A
* cube with a corner not sampled (NaN) makes nothing. Vertices sit on the grid's edges where the
* linear interpolation of their ends crosses the level, one vertex an edge, and grid index g goes
* to g 2 bounds / (r + 1) - bounds (RadShapeGenDecl, "The field"). */
void shape_mesh(const std::vector<float>& field, int32_t r, double bounds, double level,
ShapeMesh* out);
/* The mesh as a file: "glb" (positions, smooth normals and indices), "obj", "ply" (binary) or
* "stl" (binary). The content type goes to `mime`. Refuses another format by name. */
int shape_export(const ShapeMesh& m, const std::string& format, std::string* bytes,
std::string* mime, std::string* why);
/* ================================================================== the request */
class ShapeTicket {
public:
/* driver side */
void progress(int32_t steps_done, int32_t points_done);
/* The finest grid, at resolution `r`, and the end. */
void finish(int status, const std::string& why = std::string());
void set_field(std::vector<float>&& field, int32_t r);
/* caller side: waits at most `ms` milliseconds for the end; true once it came. */
bool wait(int ms);
bool finished() const;
int status() const;
std::string why() const;
/* The field, once finished with RAD_OK; moved out. */
std::vector<float> take_field(int32_t* r);
void progress_of(int32_t* steps_done, int32_t* points_done) const;
std::atomic<bool> cancel{false};
/* Written by the driver at submit: the evaluations, the resolution and the guidance. */
int32_t steps = 0, resolution = 0;
double guidance = 0.0;
/* Usage, written by the driver before finish(): the points the decoder was queried at, and
* per-phase times. */
int64_t points = 0;
int64_t t_submit_ns = 0, t_cond_ns = 0, t_denoised_ns = 0, t_done_ns = 0;
private:
mutable std::mutex mu_;
std::condition_variable cv_;
bool done_ = false;
int status_ = RAD_OK;
std::string why_;
int32_t steps_done_ = 0, points_done_ = 0;
std::vector<float> field_;
int32_t r_ = 0;
};
struct ShapeRequest {
/* The picture, prepared (shape_picture). */
std::vector<float> patches;
int32_t steps = 0; /* sigma grid points; 0: the model's default */
double guidance = NAN; /* NaN: the model's default */
int32_t resolution = 0; /* the finest grid's cells a side; 0: the model's default */
bool dense = false; /* sample every point of the finest grid, no coarser levels */
uint64_t seed = 0;
std::shared_ptr<ShapeTicket> ticket;
};
} /* namespace gen */
} /* namespace rad */
+436
View File
@@ -0,0 +1,436 @@
/* shape_driver.cpp -- the shape generator's pass driver (shape_driver.h). */
#include "shape_driver.h"
#include "rad_internal.h"
#include <algorithm>
#include <cmath>
#include <cstring>
namespace rad {
namespace gen {
namespace {
constexpr int64_t kAlign = 256;
/* Region offsets and sizes, in the enum's order (shape_driver.h), and the total; shared by the
* allocation and the VRAM budget. */
int64_t carve(const RadShapeGenDecl& d, int64_t (*bytes)[2], int n) {
const int64_t side = d.enc_size / d.enc_patch;
const int64_t want[] = {
side * side * 3 * d.enc_patch * d.enc_patch * 4, /* R_PATCH: f32 */
2 * 4, /* R_SIGMA */
2 * 4, /* R_SNEXT */
2 * 4, /* R_CFG */
2 * 4, /* R_PAIR */
2 * 4, /* R_LANES */
2 * 4, /* R_FLAGS */
2 * 2 * 4, /* R_SEED */
3 * 4, /* R_LATCU */
d.max_query * 3 * 4, /* R_QUERY: f32 */
2 * 4, /* R_QCU */
};
int64_t off = 0;
for (int r = 0; r < n; ++r) {
bytes[r][0] = off;
bytes[r][1] = want[r];
off = align_up(off + want[r], kAlign);
}
return off;
}
} /* namespace */
int64_t ShapeDriver::device_bytes(const Program& prog) {
if (!prog.is_shape_generator()) return 0;
int64_t b[R_N][2];
return carve(prog.shape_gen, b, R_N);
}
int ShapeDriver::init(const Program& prog, const std::vector<RankIO>& ranks) {
fini();
if (!prog.is_shape_generator()) return RAD_E_STATE;
decl_ = prog.shape_gen;
info_ = shape_info(decl_, prog.sgen_name);
ranks_ = ranks;
n_patch_ = (decl_.enc_size / decl_.enc_patch) * (decl_.enc_size / decl_.enc_patch);
patch_dim_ = 3 * decl_.enc_patch * decl_.enc_patch;
int64_t b[R_N][2];
bytes_ = carve(decl_, 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));
field_host_ = static_cast<float*>(rad_dev_alloc(decl_.max_query * 4, RAD_MEM_HOST_PINNED));
if (!host_ || !field_host_) {
RAD_ERR("shape generator: no pinned host memory for the pass staging and the field "
"(%lld + %lld bytes)", (long long)bytes_, (long long)(decl_.max_query * 4));
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("shape 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{});
sout_.assign(ranks_.size(), RadShapeGenBatch{});
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 ShapeDriver::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 (field_host_) rad_dev_free(field_host_, RAD_MEM_HOST_PINNED);
host_ = nullptr;
field_host_ = nullptr;
}
/* ================================================================== requests */
int ShapeDriver::submit(std::unique_ptr<ShapeRequest> r, std::string* why) {
if (!r || !r->ticket) return RAD_E_INVAL;
const RadShapeGenDecl& d = decl_;
auto no = [&](const std::string& w) {
if (why) *why = w;
return RAD_E_INVAL;
};
if ((int64_t)r->patches.size() != n_patch_ * patch_dim_)
return no("the picture is not prepared for this model's image encoder");
const int32_t steps = r->steps > 0 ? r->steps : (int32_t)d.default_steps;
if (steps < 2 || steps > d.max_steps)
return no("num_inference_steps must be 2.." + std::to_string(d.max_steps) +
" (sigma grid points, the last one the clean shape)");
const double cfg = std::isnan(r->guidance) ? d.default_guidance : r->guidance;
if (!(cfg >= 0.0) || !std::isfinite(cfg))
return no("guidance_scale must be finite and not negative");
const int32_t res = r->resolution > 0 ? r->resolution : (int32_t)d.default_resolution;
if (res < d.min_resolution || res > d.max_resolution)
return no("octree_resolution must be " + std::to_string(d.min_resolution) + ".." +
std::to_string(d.max_resolution));
auto j = std::make_unique<Job>();
j->sigmas = shape_sigmas(steps);
j->evals = steps - 1;
j->cfg = (float)cfg;
j->levels = r->dense ? std::vector<int32_t>{ res } : shape_levels(res);
ShapeTicket& t = *r->ticket;
t.steps = j->evals;
t.resolution = res;
t.guidance = cfg;
t.t_submit_ns = (int64_t)rad_mono_ns();
std::lock_guard<std::mutex> lk(mu_);
if (closed_) {
if (why) *why = closed_why_;
return closed_status_;
}
j->id = next_id_++;
j->req = std::move(r);
jobs_.push_back(std::move(j));
return RAD_OK;
}
void ShapeDriver::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 ShapeDriver::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 ShapeDriver::running() const {
std::lock_guard<std::mutex> lk(mu_);
int64_t n = 0;
for (const auto& j : jobs_) if (j->admitted) ++n;
return n;
}
ShapeDriver::Job* ShapeDriver::job_locked(uint64_t id) {
for (auto& j : jobs_) if (j->id == id) return j.get();
return nullptr;
}
void ShapeDriver::release_locked(Job& j) {
if (j.lane >= 0) {
free_lanes_.push_back(j.lane);
j.lane = -1;
}
}
void ShapeDriver::fail_locked(Job& j, int status, const std::string& why) {
j.failed = true;
j.req->ticket->finish(status, why);
}
/* In arrival order: a request needs only a lane. */
void ShapeDriver::admit_locked() {
for (auto& jp : jobs_) {
Job& j = *jp;
if (j.admitted || j.failed) continue;
if (free_lanes_.empty()) break;
j.lane = free_lanes_.back();
free_lanes_.pop_back();
j.admitted = true;
}
}
/* A level of the grid begins: its field unsampled, its points `pts` (every point when `all`). */
void ShapeDriver::start_level(Job& j, size_t level, std::vector<uint32_t>&& pts, bool all) {
const int32_t r = j.levels[level];
const int64_t n = (int64_t)r + 1;
j.level = level;
j.field.assign((size_t)(n * n * n), NAN);
j.axis = shape_axis(decl_.bounds, r);
j.all = all;
j.pts = std::move(pts);
j.n_pts = all ? n * n * n : (int64_t)j.pts.size();
j.next = 0;
}
/* ================================================================== staging */
int ShapeDriver::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 ShapeDriver::stage_common(const Job& j) {
const int32_t lanes[2] = { j.lane, j.lane };
const int32_t cu[3] = { 0, (int32_t)decl_.latent_rows, (int32_t)(2 * decl_.latent_rows) };
std::memcpy(hptr<int32_t>(R_LANES), lanes, sizeof lanes);
std::memcpy(hptr<int32_t>(R_LATCU), cu, sizeof cu);
reg_[R_LANES].used = sizeof lanes;
reg_[R_LATCU].used = sizeof cu;
}
void ShapeDriver::base_batches(const Job& j, int64_t n_tok, int kind, int step) {
for (size_t r = 0; r < ranks_.size(); ++r) {
RadBatch& B = out_[r];
RadShapeGenBatch& S = sout_[r];
const int ri = (int)r;
B = RadBatch{};
B.step = step;
B.phase = RAD_PHASE_PREFILL;
B.n_tok = n_tok;
B.n_seq = 1;
B.max_q_len = (int32_t)n_tok;
B.max_q_len_prefill = (int32_t)n_tok;
B.gen = kind;
S = RadShapeGenBatch{};
S.lane = j.lane;
S.patches = dptr<float>(ri, R_PATCH);
S.step = j.step;
S.n_steps = j.evals;
S.sigma = dptr<float>(ri, R_SIGMA);
S.sigma_next = dptr<float>(ri, R_SNEXT);
S.cfg = dptr<float>(ri, R_CFG);
S.pair = dptr<int32_t>(ri, R_PAIR);
S.lanes = dptr<int32_t>(ri, R_LANES);
S.flags = dptr<int32_t>(ri, R_FLAGS);
S.seed = dptr<uint32_t>(ri, R_SEED);
S.lat_cu = dptr<int32_t>(ri, R_LATCU);
S.query = dptr<float>(ri, R_QUERY);
S.query_cu = dptr<int32_t>(ri, R_QCU);
B.sgen_b = &S;
}
pass_.kind = kind;
pass_.job = j.id;
}
/* ================================================================== the passes */
const RadBatch* ShapeDriver::next(int step) {
std::lock_guard<std::mutex> lk(mu_);
pass_ = Pass{};
rb_.clear();
if (closed_) return nullptr;
/* Retire finished, failed and cancelled jobs, returning their lanes before admitting. Safe
* because next() runs between passes, with nothing in flight. */
for (auto it = jobs_.begin(); it != jobs_.end();) {
Job& j = **it;
const bool cancelled = j.req->ticket->cancel.load(std::memory_order_acquire);
if (!(j.failed || cancelled || j.finished)) { ++it; continue; }
if (cancelled && !j.failed && !j.finished)
j.req->ticket->finish(RAD_E_CANCELLED, "the request was cancelled");
release_locked(j);
it = jobs_.erase(it);
}
admit_locked();
/* 1. The decoding of a denoised lane: its latent, then its grid. */
for (auto& jp : jobs_) {
Job& j = *jp;
if (!j.admitted || j.failed || !j.cond_done || j.step < j.evals) continue;
return j.latent_done ? build_query(j, step) : build_latent(j, step);
}
/* 2. A picture. */
for (auto& jp : jobs_) {
Job& j = *jp;
if (j.admitted && !j.failed && !j.cond_done) return build_cond(j, step);
}
/* 3. The oldest lane's next step. */
for (auto& jp : jobs_) {
Job& j = *jp;
if (j.admitted && !j.failed && j.cond_done && j.step < j.evals) return build_step(j, step);
}
return nullptr;
}
const RadBatch* ShapeDriver::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* ShapeDriver::build_cond(Job& j, int step) {
for (int g = 0; g < R_N; ++g) reg_[g].used = 0;
std::memcpy(hptr<float>(R_PATCH), j.req->patches.data(), j.req->patches.size() * 4);
reg_[R_PATCH].used = (int64_t)j.req->patches.size() * 4;
stage_common(j);
if (upload() < 0) return nullptr;
base_batches(j, n_patch_, RAD_GEN_PASS_SCOND, step);
return &out_[0];
}
/* The two entries of the step: the picture's latent guided against the unconditioned one, which
* reads the same lane and moves nothing. */
const RadBatch* ShapeDriver::build_step(Job& j, int step) {
for (int g = 0; g < R_N; ++g) reg_[g].used = 0;
const float s = j.sigmas[(size_t)j.step], sn = j.sigmas[(size_t)j.step + 1];
const float sig[2] = { s, s }, nxt[2] = { sn, sn }, cfg[2] = { j.cfg, 1.0f };
const int32_t pair[2] = { 1, -2 };
const int32_t flags[2] = { j.step == 0 ? (int32_t)RAD_GEN_F_FIRST : 0, 0 };
const uint32_t lo = (uint32_t)j.req->seed, hi = (uint32_t)(j.req->seed >> 32);
const uint32_t seed[4] = { lo, hi, lo, hi };
auto stage = [&](int r, const void* p, int64_t n) {
std::memcpy(host_ + reg_[r].off, p, (size_t)n);
reg_[r].used = n;
};
stage(R_SIGMA, sig, sizeof sig);
stage(R_SNEXT, nxt, sizeof nxt);
stage(R_CFG, cfg, sizeof cfg);
stage(R_PAIR, pair, sizeof pair);
stage(R_FLAGS, flags, sizeof flags);
stage(R_SEED, seed, sizeof seed);
stage_common(j);
if (upload() < 0) return nullptr;
base_batches(j, decl_.step_rows, RAD_GEN_PASS_SSTEP, step);
return &out_[0];
}
const RadBatch* ShapeDriver::build_latent(Job& j, int step) {
for (int g = 0; g < R_N; ++g) reg_[g].used = 0;
stage_common(j);
if (upload() < 0) return nullptr;
base_batches(j, decl_.latent_rows, RAD_GEN_PASS_SLATENT, step);
return &out_[0];
}
/* The level's next run of points, at most max_query, as x, y, z. */
const RadBatch* ShapeDriver::build_query(Job& j, int step) {
for (int g = 0; g < R_N; ++g) reg_[g].used = 0;
const int64_t n = std::min<int64_t>(decl_.max_query, j.n_pts - j.next);
const int64_t side = (int64_t)j.levels[j.level] + 1;
float* q = hptr<float>(R_QUERY);
for (int64_t i = 0; i < n; ++i) {
const int64_t p = j.all ? j.next + i : (int64_t)j.pts[(size_t)(j.next + i)];
q[3 * i] = j.axis[(size_t)(p / (side * side))];
q[3 * i + 1] = j.axis[(size_t)(p / side % side)];
q[3 * i + 2] = j.axis[(size_t)(p % side)];
}
reg_[R_QUERY].used = n * 3 * 4;
const int32_t qcu[2] = { 0, (int32_t)n };
std::memcpy(hptr<int32_t>(R_QCU), qcu, sizeof qcu);
reg_[R_QCU].used = sizeof qcu;
stage_common(j);
if (upload() < 0) return nullptr;
base_batches(j, n, RAD_GEN_PASS_SQUERY, step);
for (auto& S : sout_) S.n_query = n;
pass_.n_query = n;
rb_.assign(1, Readback{ decl_.field_out, n * 4, field_host_ });
return &out_[0];
}
int ShapeDriver::done() {
std::lock_guard<std::mutex> lk(mu_);
const int64_t now = (int64_t)rad_mono_ns();
Job* j = job_locked(pass_.job);
switch (j ? pass_.kind : 0) {
case RAD_GEN_PASS_SCOND:
j->cond_done = true;
j->req->ticket->t_cond_ns = now;
/* The patches are on the card for good; the request keeps no copy. */
std::vector<float>().swap(j->req->patches);
break;
case RAD_GEN_PASS_SSTEP:
++j->step;
j->req->ticket->progress(j->step, 0);
if (j->step >= j->evals) j->req->ticket->t_denoised_ns = now;
break;
case RAD_GEN_PASS_SLATENT:
j->latent_done = true;
start_level(*j, 0, {}, true);
break;
case RAD_GEN_PASS_SQUERY: {
const int64_t n = pass_.n_query;
for (int64_t i = 0; i < n; ++i) {
const int64_t p = j->all ? j->next + i : (int64_t)j->pts[(size_t)(j->next + i)];
j->field[(size_t)p] = field_host_[i];
}
j->next += n;
j->points += n;
j->req->ticket->progress(j->step, (int32_t)std::min<int64_t>(j->points, INT32_MAX));
if (j->next < j->n_pts) break;
/* The level is complete: the next one's points, or the end (also when no point of this
* level is near the surface, which leaves the finer levels nothing to sample). */
if (j->level + 1 < j->levels.size()) {
const int32_t rp = j->levels[j->level], r = j->levels[j->level + 1];
const bool last = j->level + 2 == j->levels.size();
std::vector<uint32_t> pts = shape_refine(j->field, rp, r, decl_.level, last);
if (!pts.empty()) {
start_level(*j, j->level + 1, std::move(pts), false);
break;
}
}
ShapeTicket& t = *j->req->ticket;
t.points = j->points;
t.t_done_ns = now;
t.set_field(std::move(j->field), j->levels[j->level]);
j->finished = true;
t.finish(RAD_OK);
break;
}
default:
break;
}
pass_ = Pass{};
rb_.clear();
return RAD_OK;
}
} /* namespace gen */
} /* namespace rad */
+141
View File
@@ -0,0 +1,141 @@
/* shape_driver.h -- the shape generator's pass driver (shape.h; abi/rad_builder.h's
* RadShapeGenDecl describes the passes).
*
* Driven by the engine thread like the other drivers (pass.h): `next()` picks and stages a pass,
* `done()` folds its result back once every rank has run it. Requests arrive from HTTP threads
* through `submit()` and leave through their ShapeTicket.
*
* A request holds a lane from admission to its last query. Its picture is prepared and its
* schedule fixed at submit; between passes the driver only stages, except when a level of the
* grid is complete, when it works out the points of the next (shape_refine).
*
* Pass priority, one pass at a time:
*
* 1. SLATENT, then the SQUERY passes level by level, of a lane whose denoising is done: they
* finish a request and free its lane.
* 2. SCOND of an admitted request, so its steps can follow the current request's without a gap.
* 3. SSTEP of the oldest lane with steps left. Requests are denoised one after another, not in
* turns: a pass is one request's, so taking turns would only delay the first.
*/
#pragma once
#include "shape.h"
#include "pass.h"
#include "device/device.h"
#include <deque>
#include <mutex>
namespace rad {
namespace gen {
class ShapeDriver final : public IPassDriver {
public:
struct RankIO {
int device = 0;
RadStream stream = nullptr;
};
int init(const Program& prog, const std::vector<RankIO>& ranks);
void fini();
~ShapeDriver() override { fini(); }
/* The bytes init() allocates on each rank's card, for the VRAM budget. */
static int64_t device_bytes(const Program& prog);
/* ---------------------------------------------------------- HTTP threads */
/* Queue a request, refused at once with `why` when it can never run. */
int submit(std::unique_ptr<ShapeRequest> r, std::string* why);
const ShapeGenInfo& info() const { return info_; }
void shutdown(const char* why, int status) override;
/* ---------------------------------------------------------- the engine thread */
const RadBatch* next(int step) override;
const RadBatch* batch_for(int rank) const override;
const std::vector<Readback>& readbacks() const override { return rb_; }
int done() override;
int64_t queued() const override;
int64_t running() const override;
private:
struct Job {
uint64_t id = 0;
std::unique_ptr<ShapeRequest> req;
std::vector<float> sigmas; /* the request's grid points */
float cfg = 0.0f;
int32_t evals = 0; /* steps the request takes: grid points less one */
int32_t lane = -1;
bool admitted = false;
bool cond_done = false;
int32_t step = 0; /* steps done */
bool latent_done = false;
/* The grid: its levels, the one being sampled, its field (NaN where not sampled) and
* the points it samples, all of them when `all` (the coarsest level, and dense
* sampling); `next` is the first not yet queried. */
std::vector<int32_t> levels;
size_t level = 0;
std::vector<float> field;
std::vector<float> axis;
std::vector<uint32_t> pts;
bool all = false;
int64_t n_pts = 0, next = 0;
int64_t points = 0; /* every level's, for the usage */
bool failed = false;
bool finished = false;
};
struct Pass {
int kind = 0;
uint64_t job = 0;
int64_t n_query = 0;
};
struct Region { int64_t off = 0, bytes = 0, used = 0; };
enum { R_PATCH, R_SIGMA, R_SNEXT, R_CFG, R_PAIR, R_LANES, R_FLAGS, R_SEED, R_LATCU, R_QUERY,
R_QCU, R_N };
template <class T> T* hptr(int r) const { return reinterpret_cast<T*>(host_ + reg_[r].off); }
template <class T> T* dptr(int rank, int r) const {
return reinterpret_cast<T*>((char*)dev_[(size_t)rank] + reg_[r].off);
}
int upload();
/* What every pass carries: the lane twice (the step's two entries) and the latents' bounds. */
void stage_common(const Job& j);
void base_batches(const Job& j, int64_t n_tok, int kind, int step);
void start_level(Job& j, size_t level, std::vector<uint32_t>&& pts, bool all);
void admit_locked();
void release_locked(Job& j);
void fail_locked(Job& j, int status, const std::string& why);
Job* job_locked(uint64_t id);
const RadBatch* build_cond(Job& j, int step);
const RadBatch* build_step(Job& j, int step);
const RadBatch* build_latent(Job& j, int step);
const RadBatch* build_query(Job& j, int step);
RadShapeGenDecl decl_{};
ShapeGenInfo info_;
int64_t n_patch_ = 0, patch_dim_ = 0;
std::vector<RankIO> ranks_;
char* host_ = nullptr; /* pinned, same layout as each slab */
int64_t bytes_ = 0;
std::vector<void*> dev_;
Region reg_[R_N];
float* field_host_ = nullptr;
std::vector<Readback> rb_;
std::vector<RadBatch> out_; /* one per rank */
std::vector<RadShapeGenBatch> sout_;
Pass pass_;
mutable std::mutex mu_;
std::deque<std::unique_ptr<Job>> jobs_; /* arrival order */
std::vector<int32_t> free_lanes_;
uint64_t next_id_ = 1;
bool closed_ = false;
std::string closed_why_;
int closed_status_ = RAD_E_STATE;
};
} /* namespace gen */
} /* namespace rad */
+11 -3
View File
@@ -198,6 +198,9 @@ int64_t carve(const RadVideoGenDecl& d, int64_t max_tok, int64_t ep, int64_t pd,
int64_t (*bytes)[2], int n) {
/* A guided model's VCOND carries the negative prompt after the positive. */
const int64_t prompts = d.guidance ? 2 : 1;
/* A schedule's steps: a request's, at most max_steps, plus the refinement rungs an upscaling
* request appends after them (video_schedule). */
const int64_t sched_cap = (int64_t)d.max_steps + std::max<int32_t>(d.n_refine_rungs, 0);
const int64_t want[] = {
prompts * d.max_text * 4, /* R_TOK */
prompts * d.max_text * 4, /* R_POS */
@@ -205,8 +208,8 @@ int64_t carve(const RadVideoGenDecl& d, int64_t max_tok, int64_t ep, int64_t pd,
3 * max_tok * 4, /* R_ROPE: a step's positions, or the prompt's M-RoPE */
RAD_VGEOM_N * 4, /* R_GEOM */
16 * 4, /* R_SCHED */
d.max_steps * 4, /* R_TV */
d.max_steps * 4, /* R_TA */
sched_cap * 4, /* R_TV */
sched_cap * 4, /* R_TA */
4 * 4, /* R_SEED */
4, /* R_LANE */
4, /* R_FIRST */
@@ -1008,6 +1011,11 @@ const RadBatch* VideoDriver::build_cond(Job& j, int step) {
px[i] = rad_f32_to_bf16(2.0f * ((float)img[i] / 255.0f) - 1.0f);
reg_[R_IMG].used = (int64_t)img.size() * 2;
}
if ((int64_t)j.sched.steps * 4 > reg_[R_TV].bytes) {
fail_locked(j, RAD_E_STATE, "the schedule's " + std::to_string(j.sched.steps) +
" steps are more than the timestep regions hold");
return nullptr;
}
float* tv = hptr<float>(R_TV);
float* ta = hptr<float>(R_TA);
for (int32_t i = 0; i < j.sched.steps; ++i) {
@@ -1238,7 +1246,7 @@ const RadBatch* VideoDriver::build_encode(Job& j, int step) {
} else {
const int64_t nf = m.enc_frames, area = (int64_t)eh * ew * 3;
stage_frames = ng > 23 ? gd[23] : 0;
if (stage_frames < nf || stage_frames * area * 4 > reg_[R_ENCPX].bytes) {
if (nf < 1 || stage_frames < nf || stage_frames * area * 4 > reg_[R_ENCPX].bytes) {
fail_locked(j, RAD_E_STATE, "'" + m.name + "' does not fit an encode pass");
return nullptr;
}
+10 -6
View File
@@ -381,12 +381,16 @@ int KVManager::declare_runtime_window(int32_t g, int64_t window_tokens) {
fixed_ += align_up(max_seqs_ * q.ring_blocks_max() * q.bytes_per_block, RAD_ALIGN_UNIT);
if (counted) {
const int64_t was = q.window_blocks * q.bytes_per_block;
/* The plan counted this group's snapshot section, so both totals carry `was`.
* Saturating hides an accounting bug; surface it in debug builds. */
assert(window_ck_bytes_ >= was && checkpoint_bytes_ >= was &&
"runtime window: snapshot byte totals below the section being removed");
window_ck_bytes_ = window_ck_bytes_ > was ? window_ck_bytes_ - was : 0;
checkpoint_bytes_ = checkpoint_bytes_ > was ? checkpoint_bytes_ - was : 0;
/* The plan counted this group's snapshot section, so both totals carry `was`; less
* is an accounting bug, and the pool would be sized from a wrong total. */
if (window_ck_bytes_ < was || checkpoint_bytes_ < was) {
RAD_ERR("kv group %d: runtime window: the snapshot byte totals (%lld, %lld) are "
"below the %lld-byte section being removed", (int)g,
(long long)window_ck_bytes_, (long long)checkpoint_bytes_, (long long)was);
return RAD_E_STATE;
}
window_ck_bytes_ -= was;
checkpoint_bytes_ -= was;
}
}
return RAD_OK;
+55 -5
View File
@@ -52,9 +52,10 @@ bool target_covers(const std::string& declared, const char* arch) {
}
/* Two schemas for one op are the same when every positional slot means the same thing: parameter
* keys, types and requiredness (what the selector matches on) and operand count, roles and
* optionality (arguments are positional). Operand names are for diagnostics only (ABI), so "b"
* and "w_gate" in slot 1 agree. */
* keys, types, requiredness (what the selector matches on) and roles (the core reads the first
* registrant's: a chunk or a capacity named by one plugin applies to every plugin's rows), and
* operand count, roles and optionality (arguments are positional). Operand names are for
* diagnostics only (ABI), so "b" and "w_gate" in slot 1 agree. */
bool schema_same(const RadOpSchema& a, const RadOpSchema& b, std::string* diff) {
if (a.n_params != b.n_params) {
*diff = fmt("%d parameters vs %d", a.n_params, b.n_params);
@@ -77,6 +78,10 @@ bool schema_same(const RadOpSchema& a, const RadOpSchema& b, std::string* diff)
x.required ? "required" : "optional", y.required ? "required" : "optional");
return false;
}
if (x.role != y.role) {
*diff = fmt("parameter '%s' has role %d vs %d", or_empty(x.key), x.role, y.role);
return false;
}
}
if (a.n_operands != b.n_operands) {
*diff = fmt("%d operands vs %d", a.n_operands, b.n_operands);
@@ -291,6 +296,27 @@ int Registry::commit_(Staged& s, int order) {
unstage_(s);
return RAD_E_INVAL;
}
/* The counts are the plugin's word; the tables they index are walked at every
* selection and every issue, so a null table or an operand count past what an issue
* can carry (MAX_OPERANDS) is refused here, by name, rather than read there. */
if (sch->n_params < 0 || (sch->n_params && !sch->params) || sch->n_operands < 0 ||
sch->n_operands > MAX_OPERANDS || (sch->n_operands && !sch->operands)) {
err_("kernel plugin '%s': op '%s' declares %d parameters and %d operands, a table "
"missing, or more operands than an issue carries (%d)", p.name.c_str(),
sch->op, sch->n_params, sch->n_operands, MAX_OPERANDS);
unstage_(s);
return RAD_E_INVAL;
}
for (int q = 0; q < sch->n_params; ++q) {
const RadParamSpec& ps = sch->params[q];
if (!ps.key || !ps.key[0] || ps.role < RAD_PROLE_NONE ||
ps.role > RAD_PROLE_CAPACITY) {
err_("kernel plugin '%s': op '%s' parameter %d has no key or an unknown role "
"(%d)", p.name.c_str(), sch->op, q, ps.role);
unstage_(s);
return RAD_E_INVAL;
}
}
std::string diff;
auto it = schemas_.find(sch->op);
if (it != schemas_.end()) {
@@ -338,6 +364,23 @@ int Registry::commit_(Staged& s, int order) {
unstage_(s);
return RAD_E_INVAL;
}
/* The selector reads every constraint of every row at every query, and the tuner every
* tunable, so their tables must exist wherever a count says they do. */
if (k->n_tunables < 0 || (k->n_tunables && !k->tunables) || k->n_constraints < 0 ||
(k->n_constraints && !k->constraints)) {
err_("kernel '%s' in plugin '%s' declares %d tunables and %d constraints with a "
"missing table", k->name, p.name.c_str(), k->n_tunables, k->n_constraints);
unstage_(s);
return RAD_E_INVAL;
}
for (int c = 0; c < k->n_constraints; ++c)
if (!k->constraints[c].key || !k->constraints[c].key[0] ||
(k->constraints[c].op == RAD_C_IN && !k->constraints[c].sval)) {
err_("kernel '%s' in plugin '%s' declares constraint %d with no key, or an IN "
"with no set", k->name, p.name.c_str(), c);
unstage_(s);
return RAD_E_INVAL;
}
/* Every tunable axis must carry a default that is one of its own values. Untuned
* shapes (no cache, an unmeasured shape, another card's cache) run the defaults, with
* no other fallback (spec §15). Checked at load rather than first use so a bad axis
@@ -382,8 +425,15 @@ int Registry::commit_(Staged& s, int order) {
if (no_device_code_)
why = "no card is visible, so this process runs on the host backend and no GPU code "
"object runs here";
if (n_device > 0 && s.code_to > s.code_from &&
(no_device_code_ || rad::dev_code_runs(s.code_from, s.code_to, code_device_, &why) == 0)) {
/* The code range decides only the per-card test: on the host backend the rows go even when
* this dlopen registered no fat binary (no HIP in the build, or the library already
* mapped by another registry). */
const bool no_code_here =
n_device > 0 &&
(no_device_code_ ||
(s.code_to > s.code_from &&
rad::dev_code_runs(s.code_from, s.code_to, code_device_, &why) == 0));
if (no_code_here) {
std::vector<std::pair<const RadKernelInfo*, int>> keep;
for (const auto& r : staged_rows)
if (r.first->domain != RAD_DOMAIN_DEVICE) keep.push_back(r);
+12 -1
View File
@@ -17,6 +17,11 @@
namespace rad {
/* The widest conventional op is gdn_conv_prep at sixteen operands (docs/OPS.md). Thirty-two leaves
* room for an architecture plugin's private ops without a variable-length array on the hot path.
* The plugin loader refuses a schema with more, so no issue carries more. */
constexpr int MAX_OPERANDS = 32;
namespace mm { struct Item; struct PromptMedia; }
class Registry;
@@ -451,9 +456,15 @@ public:
std::vector<int64_t> decoder_max_area;
} vgen_str;
bool is_video_generator() const { return video_gen.max_lanes != 0; }
/* The declared shape generator (rad_declare_shape_generator); `max_lanes` 0 when none. Its
* name points at `sgen_name`. */
RadShapeGenDecl shape_gen{};
std::string sgen_name;
bool is_shape_generator() const { return shape_gen.max_lanes != 0; }
/* Driven by passes, not token steps: any generator. */
bool is_pass_driven() const {
return is_generator() || is_audio_generator() || is_video_generator();
return is_generator() || is_audio_generator() || is_video_generator() ||
is_shape_generator();
}
/* Two arenas, because a host-site activation cannot index device memory. The buffer plan
+5 -5
View File
@@ -942,9 +942,9 @@ int Ctx::lane_join(int from, int to) {
/* The key below reads every RadBatch field a pass's shape or arguments can depend on, by hand. A
* field added to RadBatch changes its size: decide whether the key must read it, then update the
* size here. `agen_b` and `vgen_b` are set only on generator passes, which are never recorded
* (below). */
static_assert(sizeof(void*) != 8 || sizeof(RadBatch) == 408,
* size here. `agen_b`, `vgen_b` and `sgen_b` are set only on generator passes, which are never
* recorded (below). */
static_assert(sizeof(void*) != 8 || sizeof(RadBatch) == 416,
"RadBatch changed: check that Ctx::pass_key reads every new field a pass depends on");
static_assert(sizeof(void*) != 8 || sizeof(RadKVGroupBatch) == 80,
"RadKVGroupBatch changed: check that Ctx::pass_key reads every new field");
@@ -957,8 +957,8 @@ uint64_t Ctx::pass_key(const RadBatch* b) const {
* sequence from their counts), and such a step samples a prompt's first token, which is not
* the repeating decode pass. */
if (b->n_plugin_words > 0) return 0;
/* A generator pass is shaped by what RadBatch::gen_b, agen_b or vgen_b carries, which no key
* below reads. */
/* A generator pass is shaped by what RadBatch::gen_b, agen_b, vgen_b or sgen_b carries, which
* no key below reads. */
if (b->gen) return 0;
uint64_t h = 0x9e3779b97f4a7c15ull;
auto mix = [&](uint64_t v) {
-4
View File
@@ -40,10 +40,6 @@ class Registry;
struct XpState;
struct XpLayer;
/* The widest conventional op is gdn_conv_prep at sixteen operands (docs/OPS.md). Thirty-two leaves
* room for an architecture plugin's private ops without a variable-length array on the hot path. */
constexpr int MAX_OPERANDS = 32;
typedef void (*ArchStepFn)(RadCtx*, const RadBatch*);
/* "[shape]/[stride]" of a tensor's live dimensions, for diagnostics. */
+7 -1
View File
@@ -725,7 +725,13 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set&
first = kv.first_block_pos(e.seq, (int32_t)gi);
has_win = kv.runtime_window(e.seq, (int32_t)gi, &win);
if (has_win) {
assert(!ring_blocks || ring_blocks == (int32_t)win.ring_blocks);
/* The ring size sets the group header's geometry, so every sequence in the
* group must report the same one. */
if (ring_blocks && ring_blocks != (int32_t)win.ring_blocks) {
RAD_ERR("kv group %d: sequences report ring sizes of %d and %d blocks",
(int)gi, (int)ring_blocks, (int)win.ring_blocks);
return RAD_E_STATE;
}
ring_blocks = (int32_t)win.ring_blocks;
}
bt_len = (int64_t)bt.size();
+4 -2
View File
@@ -9,11 +9,13 @@
namespace rad {
/* lcm, with a non-positive side meaning "no constraint yet". */
/* lcm, with a non-positive side meaning "no constraint yet". The sides are plugin-declared; an lcm
* past int64 saturates, so the quantum check refuses it rather than wrapping to a small one. */
static int64_t lcm64(int64_t a, int64_t b) {
if (a <= 0) return b;
if (b <= 0) return a;
return std::lcm(a, b);
const int64_t q = a / std::gcd(a, b);
return q > INT64_MAX / b ? INT64_MAX : q * b;
}
/* The op's sequence-chunk parameter, found by role (RAD_PROLE_SEQ_CHUNK) in its schema. Steps
+3 -1
View File
@@ -390,7 +390,7 @@ json Server::capabilities() const {
caps["reasoning"] = !rerank && deps_.chat && deps_.chat->supports_reasoning();
/* An image model reads pictures only for edits and writes no text a grammar could constrain,
* whatever its conditioning network's processor would take. */
const bool img = opt_.image_model || opt_.video_model;
const bool img = opt_.image_model || opt_.video_model || opt_.shape_model;
caps["grammar"] = !img && !rerank && deps_.grammar != nullptr;
/* Laya runs on the embedding path, but answers /v1/systemone, not /v1/embeddings. */
caps["embedding"] = deps_.embed != nullptr && !rerank && opt_.decision_type != "laya";
@@ -403,11 +403,13 @@ json Server::capabilities() const {
caps["image_edit"] = deps_.images != nullptr && deps_.images->info().max_refs > 0;
caps["audio_generation"] = deps_.audio != nullptr;
caps["video_generation"] = deps_.videos != nullptr;
caps["shape_generation"] = deps_.shapes != nullptr;
/* The decision protocol /v1/systemone serves (ServerOptions::decision_type), so a proxy can
* route to a decision model without trying a generation; null when it serves none. */
caps["decision"] = opt_.decision_type.empty() ? json(nullptr) : json(opt_.decision_type);
/* What a video request may carry. */
if (deps_.videos) video_caps(caps, deps_.videos);
if (deps_.shapes) shape_caps(caps, deps_.shapes);
/* The efforts a chat request may send, probed from the template at startup; null when it
* takes any word. "none" and "minimal" are this server's and turn thinking off. */
if (lim_.reasoning_efforts.empty()) {
+16 -1
View File
@@ -22,7 +22,8 @@
struct RadModelMeta;
namespace rad {
namespace gen { struct Request; struct AudioRequest; class AudioTicket; struct VideoRequest; class VideoTicket; }
namespace gen { struct Request; struct AudioRequest; class AudioTicket; struct VideoRequest; class VideoTicket;
struct ShapeRequest; struct ShapeGenInfo; }
namespace mm { struct Frame; struct Item; }
namespace server {
@@ -816,5 +817,19 @@ public:
virtual int64_t running() const = 0;
};
/* The shape generator (core/gen/shape_driver.h), for a model that makes a 3-D shape from a
* picture: its declared picture, sampler and grid (gen::ShapeGenInfo) and its request queue. The
* server prepares the picture (gen::shape_picture), queues the request, and meshes the field the
* ticket hands back. */
class IShapeGen {
public:
virtual ~IShapeGen() = default;
virtual const gen::ShapeGenInfo& info() const = 0;
/* Queue a request; refused at once, with `why`, when it can never run. */
virtual int submit(std::unique_ptr<gen::ShapeRequest> r, std::string* why) = 0;
virtual int64_t queued() const = 0;
virtual int64_t running() const = 0;
};
} /* namespace server */
} /* namespace rad */
+11 -3
View File
@@ -3379,11 +3379,16 @@ int anthropic_image(const json& block, const std::string& at, json* out, ApiErro
* continuation sends only the tail of the conversation), so a field outside these lists is
* refused by name rather than ignored. The refusal says "Extra inputs are not permitted", as
* Anthropic's does; Claude Code matches those words to retry without a beta field it can
* drop. */
* drop.
*
* The last row is not Anthropic's: the chat path's history penalties and min-p, under the chat
* path's names, ranges and meaning, for clients that speak only this format to a model whose
* card asks for them (Qwen's presence_penalty). */
const char* kAnthropicFields[] = {
"model", "messages", "system", "max_tokens", "temperature", "top_p", "top_k", "stream",
"stop_sequences", "tools", "tool_choice", "thinking", "metadata", "output_config",
"output_format", "context_management", "thread",
"min_p", "presence_penalty", "frequency_penalty", "repetition_penalty", "repeat_last_n",
};
/* Accepted and not acted on: none of them can change the answer here. Capacity and placement
@@ -3917,8 +3922,11 @@ int anthropic_to_chat(const std::string& body, const OaiLimits& lim, std::string
if (one) o["parallel_tool_calls"] = false;
}
/* `model` included, since the reply names it back as Anthropic's does. */
for (const char* k : { "model", "max_tokens", "temperature", "top_p", "top_k", "stream" })
/* `model` included, since the reply names it back as Anthropic's does. The penalties and
* min-p are the chat path's own fields, checked there. */
for (const char* k : { "model", "max_tokens", "temperature", "top_p", "top_k", "stream",
"min_p", "presence_penalty", "frequency_penalty", "repetition_penalty",
"repeat_last_n" })
if (b.contains(k)) o[k] = b.at(k);
if (b.contains("stop_sequences")) o["stop"] = b.at("stop_sequences");
+6
View File
@@ -220,6 +220,12 @@ void Server::handle_realtime(const HttpRequest& req, WsConn& ws) {
"this model does not transcribe: its architecture plugin states no "
"transcription format (rad_arch_audio_format), or it was started without "
"its audio encoder", 1008);
/* An open turn is cut at the encoder's clip length; without one it would grow for as long as
* the client appends audio. */
if (deps_.mm->audio_max_samples() <= 0)
return refuse("invalid_request_error", "model_not_supported",
"this model's audio encoder states no clip length, which a realtime turn "
"is cut at", 1008);
/* A session holds a connection's thread and one of its own for its whole life, and runs one
* pass at a time: more sessions than the engine has sequences would only queue. */
const int64_t cap = std::max<int64_t>(1, opt_.max_seqs);
+8
View File
@@ -134,6 +134,10 @@ void Server::register_routes() {
[this](const HttpRequest& q) { return handle_video_delete(q); });
router_.get ("/v1/videos/:id/content",
[this](const HttpRequest& q) { return handle_video_content(q); });
/* Hunyuan3D-2's API server: a shape from a picture. */
router_.post("/generate", [this](const HttpRequest& q) { return handle_shape_generate(q); });
router_.post("/send", [this](const HttpRequest& q) { return handle_shape_send(q); });
router_.get ("/status/:uid", [this](const HttpRequest& q) { return handle_shape_status(q); });
router_.post("/v1/audio/transcriptions",
[this](const HttpRequest& q) { return handle_transcription(q); });
/* The same, live over a WebSocket (OpenAI's realtime transcription session). A plain GET
@@ -374,6 +378,7 @@ void Server::stop() {
stopping_.store(true);
transport_.stop();
stop_videos();
stop_shapes();
drain_graveyard(2000);
}
@@ -1389,6 +1394,8 @@ std::optional<HttpResponse> Server::refuse_text(const std::string& peer, ApiShap
"generates no text"
: opt_.video_model ? "this is a video model: it serves /v1/videos and generates "
"no text"
: opt_.shape_model ? "this is a 3-D shape model: it serves /generate and generates "
"no text"
: nullptr;
if (!why) return std::nullopt;
return error_response(err_not_implemented(why), peer, shape);
@@ -1675,6 +1682,7 @@ HttpResponse Server::serve_pooled(const HttpRequest& req, bool rerank) {
opt_.image_model ? "/v1/embeddings requires an embedding model; this one makes images"
: opt_.audio_model ? "/v1/embeddings requires an embedding model; this one makes audio"
: opt_.video_model ? "/v1/embeddings requires an embedding model; this one makes video"
: opt_.shape_model ? "/v1/embeddings requires an embedding model; this one makes shapes"
: "/v1/embeddings requires an embedding model; this one generates "
"text"), req.peer);
+20
View File
@@ -43,6 +43,7 @@ struct Deps {
IImageGen* images = nullptr; /* absent -> the images endpoints are 501 */
IAudioGen* audio = nullptr; /* absent -> /v1/audio/speech is 501 */
IVideoGen* videos = nullptr; /* absent -> /v1/videos is 501 */
IShapeGen* shapes = nullptr; /* absent -> /generate is 501 */
const SpeechFormat* speech = nullptr; /* absent -> /v1/audio/transcriptions is 501 */
/* Engine-side state the server cannot see (per-card VRAM, the expert plane), as a snapshot
@@ -88,6 +89,10 @@ struct ServerOptions {
* many finished videos are kept at most (the oldest go first). */
int64_t video_ttl_s = 3600;
int64_t max_videos = 32;
/* A shape generator (rad_declare_shape_generator) generates no text either: the text
* endpoints answer 501 naming /generate. A shape made through /send is kept for /status for
* as long as a video, as many at most. */
bool shape_model = false;
/* The decision protocol from the container's `decision.type`: "d1" serves /v1/systemone
* (systemone.h), "clef" serves it through the head on the card (clef.h), "laya" through the
* Laya plugin's option logits (laya.h), "mica" through Mica's label logits (mica.h); empty
@@ -264,6 +269,7 @@ private:
struct RealtimeSession; /* realtime.cpp */
struct SpeechSession; /* speech_stream.cpp */
struct VideoJob; /* videos.cpp */
struct ShapeJob; /* shapes.cpp */
struct StreamState;
static UsageOut usage_of(const OaiRequest& r, const std::vector<Generation>& gens);
@@ -366,6 +372,17 @@ private:
/* What this deployment can do (chat, tools, reasoning, grammar, media, logprobs, reasoning
* efforts), shared by /server_info's `capabilities` and the model entry so they agree. */
json capabilities() const;
/* ------------------------------------------------------------------ shapes.cpp
* Hunyuan3D-2's own API: a shape from a picture, made at once (/generate) or in the
* background (/send) and collected (/status/{uid}). */
HttpResponse handle_shape_generate(const HttpRequest& req);
HttpResponse handle_shape_send(const HttpRequest& req);
HttpResponse handle_shape_status(const HttpRequest& req);
void shape_work(std::shared_ptr<ShapeJob> j);
void sweep_shapes_locked(int64_t now);
void stop_shapes();
static void shape_caps(json& caps, const IShapeGen* gen);
/* A video model's capabilities (videos.cpp). */
static void video_caps(json& caps, const IVideoGen* gen);
HttpResponse handle_reset_prefix_cache(const HttpRequest& req);
@@ -453,6 +470,9 @@ private:
std::mutex videos_m_;
std::vector<std::shared_ptr<VideoJob>> videos_;
std::vector<std::shared_ptr<VideoJob>> videos_gone_;
/* The background shapes (/send), oldest first, and their threads (shapes.cpp). */
std::mutex shapes_m_;
std::vector<std::shared_ptr<ShapeJob>> shapes_;
};
} /* namespace server */
+334
View File
@@ -0,0 +1,334 @@
/* shapes.cpp -- Hunyuan3D-2's API over a shape generator (core/gen/shape_driver.h): a 3-D shape
* from one picture.
*
* The routes and fields are the reference's own API server's (hy3dgen's api_server.py), so its
* clients (its Blender add-on, scripts written against it) work unchanged:
*
* POST /generate the shape, made while the request waits, as the file itself;
* POST /send the same in the background, answered at once with {"uid"};
* GET /status/{uid} {"status": "processing"}, or "completed" with the file as
* `model_base64`, or "error" with its `message`.
*
* The body is JSON: `image`, the picture as base64 (or a data URL), with an alpha channel for a
* cut-out object -- the reference removes the background of an opaque picture with rembg, which
* this server does not, so an opaque picture is taken whole; `seed` (1234 when absent, as the
* reference), `octree_resolution`, `num_inference_steps` and `guidance_scale` (the model's own
* when absent), and `type`, the file: glb (the default), obj, ply or stl. `volume_decoding`
* "dense" samples every point of the grid instead of refining it coarse to fine. Texturing
* (`texture` true) and the reference's text-to-image and re-texturing inputs (`text`, `mesh`)
* are refused. The reference's knobs that change nothing here are taken and ignored: `face_count`
* (texturing's face budget), `num_chunks` (its decoder's batch) and `mc_algo` "mc"; any other
* field is refused by name. A finished background shape is kept for as long as a video, as many
* as videos.
*/
#include "server.h"
#include "oai.h"
#include "gen/shape.h"
#include "mm/media.h"
#include "rad_internal.h"
#include <nlohmann/json.hpp>
#include <chrono>
#include <cmath>
#include <thread>
namespace rad {
namespace server {
namespace {
/* The largest picture decoded, as the image endpoints bound theirs. */
constexpr int64_t kMaxSourcePixels = (int64_t)1 << 26;
/* A request as the routes read it, and its file's format. */
struct ShapeAsk {
std::unique_ptr<gen::ShapeRequest> req;
std::string type = "glb";
};
int read_ask(const HttpRequest& q, const OaiLimits& lim, const gen::ShapeGenInfo& info,
ShapeAsk* out, ApiError* err) {
json b;
if (parse_request_object(q.body, lim, &b, err) < 0) return RAD_E_INVAL;
auto bad = [&](const std::string& p, const std::string& why) {
*err = err_bad(p, why);
return RAD_E_INVAL;
};
static const char* const kFields[] = { "image", "seed", "octree_resolution",
"num_inference_steps", "guidance_scale", "type",
"volume_decoding", "texture", "text", "mesh",
"face_count", "num_chunks", "mc_algo" };
for (auto it = b.begin(); it != b.end(); ++it) {
bool known = false;
for (const char* k : kFields) known = known || it.key() == k;
if (!known)
return bad(it.key(), "'" + it.key() + "' is not a field of /generate");
}
if (b.contains("mc_algo") && !b["mc_algo"].is_null() &&
!(b["mc_algo"].is_string() && b["mc_algo"].get<std::string>() == "mc")) {
*err = err_unsupported("mc_algo", "the surface is marching cubes ('mc'); differentiable "
"marching cubes ('dmc') is not served");
return RAD_E_INVAL;
}
for (const char* k : { "text", "mesh" })
if (b.contains(k) && !b[k].is_null()) {
*err = err_unsupported(k, std::string("this server makes a shape from a picture; '") +
k + "' (the reference's text-to-image and re-texturing "
"inputs) is not served");
return RAD_E_INVAL;
}
if (b.contains("texture") && b["texture"].is_boolean() && b["texture"].get<bool>()) {
*err = err_unsupported("texture", "texturing (Hunyuan3D-Paint) is not served: this "
"server makes the untextured shape");
return RAD_E_INVAL;
}
if (!b.contains("image") || !b["image"].is_string() || b["image"].get<std::string>().empty())
return bad("image", "'image' must be the picture as base64");
std::string img = b["image"].get<std::string>();
if (img.rfind("data:", 0) == 0) {
const size_t comma = img.find(',');
if (comma == std::string::npos || img.compare(comma - 7, 7, ";base64") != 0)
return bad("image", "a data URL must be base64 ('data:<type>;base64,...')");
img = img.substr(comma + 1);
}
std::vector<uint8_t> bytes;
if (!base64_decode(img, &bytes) || bytes.empty())
return bad("image", "'image' is not valid base64");
mm::FrameRGBA f;
std::string why;
if (mm::decode_image_rgba(bytes.data(), bytes.size(), kMaxSourcePixels, &f, &why) < 0)
return bad("image", "the picture could not be decoded: " + why);
auto r = std::make_unique<gen::ShapeRequest>();
if (gen::shape_picture(info, f, &r->patches, &why) < 0) return bad("image", why);
auto int_field = [&](const char* k, int64_t lo, int64_t hi, int32_t* v) {
if (!b.contains(k) || b[k].is_null()) return true;
if (!b[k].is_number_integer() || b[k].get<int64_t>() < lo || b[k].get<int64_t>() > hi) {
bad(k, std::string("'") + k + "' must be an integer " + std::to_string(lo) + ".." +
std::to_string(hi));
return false;
}
*v = (int32_t)b[k].get<int64_t>();
return true;
};
if (!int_field("num_inference_steps", 2, info.max_steps, &r->steps) ||
!int_field("octree_resolution", info.min_resolution, info.max_resolution,
&r->resolution))
return RAD_E_INVAL;
if (b.contains("guidance_scale") && !b["guidance_scale"].is_null()) {
if (!b["guidance_scale"].is_number() || !(b["guidance_scale"].get<double>() >= 0.0) ||
!std::isfinite(b["guidance_scale"].get<double>()))
return bad("guidance_scale", "'guidance_scale' must be a finite number, not negative");
r->guidance = b["guidance_scale"].get<double>();
}
r->seed = 1234;
if (b.contains("seed") && !b["seed"].is_null()) {
if (!b["seed"].is_number_integer())
return bad("seed", "'seed' must be an integer");
r->seed = b["seed"].is_number_unsigned() ? b["seed"].get<uint64_t>()
: (uint64_t)b["seed"].get<int64_t>();
}
if (b.contains("volume_decoding") && !b["volume_decoding"].is_null()) {
const std::string v = b["volume_decoding"].is_string()
? b["volume_decoding"].get<std::string>() : "";
if (v != "hierarchical" && v != "dense")
return bad("volume_decoding", "'volume_decoding' is hierarchical or dense");
r->dense = v == "dense";
}
if (b.contains("type") && !b["type"].is_null()) {
if (!b["type"].is_string()) return bad("type", "'type' is glb, obj, ply or stl");
out->type = b["type"].get<std::string>();
if (out->type != "glb" && out->type != "obj" && out->type != "ply" && out->type != "stl")
return bad("type", "type '" + out->type + "' is not one this server writes: glb, obj, "
"ply or stl");
}
r->ticket = std::make_shared<gen::ShapeTicket>();
out->req = std::move(r);
return RAD_OK;
}
/* The ticket's field as a mesh file, once the driver is done with it. */
int finish_file(gen::ShapeTicket& t, const gen::ShapeGenInfo& info, const std::string& type,
std::string* file, std::string* mime, std::string* why) {
if (t.status() < 0) {
*why = t.why();
return t.status();
}
int32_t r = 0;
std::vector<float> field = t.take_field(&r);
gen::ShapeMesh mesh;
gen::shape_mesh(field, r, info.bounds, info.level, &mesh);
std::vector<float>().swap(field);
if (mesh.f.empty()) {
*why = "the model's field crosses the surface level nowhere in the grid: the picture made "
"no shape";
return RAD_E_INVAL;
}
return gen::shape_export(mesh, type, file, mime, why);
}
} /* namespace */
struct Server::ShapeJob {
std::string uid, type;
int64_t created_at = 0, done_at = 0;
std::shared_ptr<gen::ShapeTicket> ticket;
std::thread worker;
/* Under Server::shapes_m_ from here on. */
bool finished = false, failed = false;
std::string file, message;
};
void Server::shape_caps(json& caps, const IShapeGen* gen) {
const gen::ShapeGenInfo& info = gen->info();
caps["shape_max_steps"] = info.max_steps;
caps["shape_resolutions"] = { info.min_resolution, info.max_resolution };
caps["shape_formats"] = json::array({ "glb", "obj", "ply", "stl" });
}
HttpResponse Server::handle_shape_generate(const HttpRequest& req) {
if (!deps_.shapes)
return error_response(err_not_implemented(
"/generate requires a 3-D shape model; this one does not make shapes"), req.peer);
const gen::ShapeGenInfo& info = deps_.shapes->info();
ShapeAsk a;
ApiError err;
if (read_ask(req, lim_, info, &a, &err) < 0) return error_response(err, req.peer);
std::shared_ptr<gen::ShapeTicket> t = a.req->ticket;
std::string why;
if (const int st = deps_.shapes->submit(std::move(a.req), &why); st < 0)
return error_response(st == RAD_E_INVAL ? err_bad("image", why) : err_overloaded(why),
req.peer);
while (!t->wait(500))
if (stopping_.load()) {
t->cancel.store(true);
return error_response(err_overloaded("the server is stopping"), req.peer);
}
std::string file, mime;
if (const int st = finish_file(*t, info, a.type, &file, &mime, &why); st < 0)
return error_response(st == RAD_E_INVAL ? err_bad("image", why) : err_internal(why),
req.peer);
HttpResponse res;
res.content_type = mime;
res.body = std::move(file);
return res;
}
void Server::shape_work(std::shared_ptr<ShapeJob> j) {
const gen::ShapeGenInfo& info = deps_.shapes->info();
gen::ShapeTicket& t = *j->ticket;
while (!t.wait(500))
if (stopping_.load()) {
t.cancel.store(true);
t.wait(60000);
break;
}
std::string file, mime, why;
const int st = t.finished() ? finish_file(t, info, j->type, &file, &mime, &why)
: RAD_E_CANCELLED;
std::lock_guard<std::mutex> lk(shapes_m_);
j->finished = true;
j->done_at = unix_now();
if (st < 0) {
j->failed = true;
j->message = why.empty() ? std::string(rad_strerror(st)) : why;
} else {
j->file = std::move(file);
}
}
void Server::sweep_shapes_locked(int64_t now) {
for (size_t i = 0; i < shapes_.size();) {
ShapeJob& j = *shapes_[i];
const bool expired = j.finished && now - j.done_at > opt_.video_ttl_s;
if (!expired) { ++i; continue; }
if (j.worker.joinable()) j.worker.join();
shapes_.erase(shapes_.begin() + (std::ptrdiff_t)i);
}
/* Past the cap the oldest finished shapes go first. */
size_t done = 0;
for (const auto& j : shapes_) done += j->finished;
const size_t cap = (size_t)std::max<int64_t>(opt_.max_videos, 1);
for (size_t i = 0; done > cap && i < shapes_.size();) {
if (!shapes_[i]->finished) { ++i; continue; }
if (shapes_[i]->worker.joinable()) shapes_[i]->worker.join();
shapes_.erase(shapes_.begin() + (std::ptrdiff_t)i);
--done;
}
}
void Server::stop_shapes() {
std::vector<std::shared_ptr<ShapeJob>> all;
{
std::lock_guard<std::mutex> lk(shapes_m_);
all = shapes_;
}
for (auto& j : all) j->ticket->cancel.store(true);
for (auto& j : all)
if (j->worker.joinable()) j->worker.join();
}
HttpResponse Server::handle_shape_send(const HttpRequest& req) {
if (!deps_.shapes)
return error_response(err_not_implemented(
"/send requires a 3-D shape model; this one does not make shapes"), req.peer);
const gen::ShapeGenInfo& info = deps_.shapes->info();
ShapeAsk a;
ApiError err;
if (read_ask(req, lim_, info, &a, &err) < 0) return error_response(err, req.peer);
auto j = std::make_shared<ShapeJob>();
j->uid = random_id("shape_");
j->type = a.type;
j->created_at = unix_now();
j->ticket = a.req->ticket;
std::string why;
if (const int st = deps_.shapes->submit(std::move(a.req), &why); st < 0)
return error_response(st == RAD_E_INVAL ? err_bad("image", why) : err_overloaded(why),
req.peer);
{
std::lock_guard<std::mutex> lk(shapes_m_);
sweep_shapes_locked(unix_now());
shapes_.push_back(j);
}
j->worker = std::thread([this, j] { shape_work(j); });
json o;
o["uid"] = j->uid;
return HttpResponse::json_body(200, json_dump(o));
}
HttpResponse Server::handle_shape_status(const HttpRequest& req) {
if (!deps_.shapes)
return error_response(err_not_implemented(
"/status requires a 3-D shape model; this one does not make shapes"), req.peer);
const std::string uid = req.param("uid");
std::lock_guard<std::mutex> lk(shapes_m_);
sweep_shapes_locked(unix_now());
for (const auto& j : shapes_) {
if (j->uid != uid) continue;
json o;
if (!j->finished) {
o["status"] = "processing";
int32_t steps = 0, points = 0;
j->ticket->progress_of(&steps, &points);
o["steps_done"] = steps;
o["steps"] = j->ticket->steps;
} else if (j->failed) {
o["status"] = "error";
o["message"] = j->message;
} else {
o["status"] = "completed";
o["type"] = j->type;
o["model_base64"] = base64_encode(j->file.data(), j->file.size());
}
return HttpResponse::json_body(200, json_dump(o));
}
ApiError e = err_bad("uid", "no shape '" + uid + "'; it may have expired");
e.status = 404;
e.type = "not_found_error";
return error_response(e, req.peer);
}
} /* namespace server */
} /* namespace rad */
+1 -1
View File
@@ -535,7 +535,7 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
canvas_for(rw, rh, se, info.max_area, info.size_multiple, &W, &H);
}
if (W % info.size_multiple || H % info.size_multiple || W < info.min_side ||
H < info.min_side || W * H > info.max_area ||
H < info.min_side || W > info.max_area || H > info.max_area || W * H > info.max_area ||
std::max(W, H) > info.max_aspect * std::min(W, H)) {
int64_t sw = 0, sh = 0;
canvas_for((double)W, (double)H, short_def, info.max_area, info.size_multiple, &sw, &sh);
+6
View File
@@ -320,6 +320,12 @@ int parse_tokenizer_json(const char* path, VocabBuild& out);
/* Same, from an in-memory buffer, for a tokenizer.json that arrived some other way. */
int parse_tokenizer_json_buf(std::string_view json, const char* origin, VocabBuild& out);
/* The vocabulary of a model that reads no text (container metadata `radiance.text` = none: a
* picture-to-shape generator): one control token, which no request reaches, since such a program
* serves no text endpoint. rad-convert bakes it and the engine builds it for a checkpoint. */
void vocab_textless(VocabBuild& out);
inline bool meta_textless(const char* v) { return v && std::string_view(v) == "none"; }
/* Read a standalone chat template file into out.chat_template, trailing newlines stripped.
* A release that ships no template (DeepSeek's does not) needs one from elsewhere; the caller
* passes the file. An unreadable or empty file is an error, never a silent skip. Returns
+12 -2
View File
@@ -892,6 +892,14 @@ const PreEntry k_pre[] = {
} /* namespace */
void vocab_textless(VocabBuild& out) {
out = VocabBuild{};
out.kind = RAD_TOK_BPE;
out.tokens = { "<|no-text|>" };
out.types = { RAD_TT_CONTROL };
out.source = "none: the model reads no text";
}
int vocab_from_gguf(const GgufFile& g, VocabBuild& out) {
out = VocabBuild{};
out.source = g.path();
@@ -1107,7 +1115,8 @@ int vocab_deserialize(const void* file_base, uint64_t file_bytes, const RadVocab
* in, so the caller cannot pass a mismatched one. */
if (file_bytes < sizeof(RadFileHeader)) return RAD_E_FORMAT;
const RadFileHeader* fh = reinterpret_cast<const RadFileHeader*>(base);
if (fh->str_off + fh->str_bytes > file_bytes) return RAD_E_FORMAT;
if (fh->str_off > file_bytes || fh->str_bytes > file_bytes - fh->str_off)
return RAD_E_FORMAT;
strs = reinterpret_cast<const char*>(base + fh->str_off);
str_bytes = fh->str_bytes;
}
@@ -1128,7 +1137,8 @@ int vocab_deserialize(const void* file_base, uint64_t file_bytes, const RadVocab
out.ignore_merges = (h->flags & RAD_VOCAB_IGNORE_MERGES) != 0;
out.chat_template = S(h->chat_template);
if (!in_file(h->tok_text_off, (uint64_t)h->n_tokens * sizeof(rad_stroff)))
if ((h->n_tokens && !h->tok_text_off) ||
!in_file(h->tok_text_off, (uint64_t)h->n_tokens * sizeof(rad_stroff)))
return RAD_E_FORMAT;
const rad_stroff* toff = reinterpret_cast<const rad_stroff*>(base + h->tok_text_off);
out.tokens.resize(h->n_tokens);