Archived
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:
1 parent
cfa6a668f6
commit
769b4c64a6
122 files changed
+10092
-2203
No files matched your search
@@ -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 */
|
||||
@@ -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 */
|
||||
@@ -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 */
|
||||
@@ -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 */
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user