sampler: res_multistep (DPM++2M data-pred) as a per-request field; ABI 24

Radiance's video denoising had only first-order Euler. The DaSiWa reference
workflow samples MiniMax-H3 with res_multistep + simple, so add it as a second
order option, exposed as a `sampler` field on /v1/videos (default euler).

New op `flow_res_multistep` across all three kernel tiers (device==avx==libref),
closed form reusing the driver's per-step scalars:
  x' = r*x + hb1*den + hb2*x0,  den = x + sigma*v,  r = sigma_next/sigma
  order 2: h=ln(sg/sgn), h_last=ln(sg_prev/sg), r_s=h_last/h,
           hb1=(1-r)(1+1/(2 r_s)), hb2=-(1-r)/(2 r_s)
hb1+hb2 == 1-r, so it collapses to Euler when x0==den. Order 1 (Euler) is forced
at the first step, the first full-size step after a latent upscale (stale
history), and the last step (sigma_next==0); order 2 otherwise. The previous
denoised estimate persists in new PERSIST buffers b_vx0/b_ax0. Verified equal to
k-diffusion sample_dpmpp_2m to 5.6e-17 on three sigma grids.

- ABI 23->24: trailing int32_t sampler on RadVideoGenBatch; RAD_SAMPLER_EULER=0
  / RAD_SAMPLER_RES_MULTISTEP=1 in rad_runtime.h.
- driver: R_SCHED region widened 6->16 f32 ([0..5] Euler, [6..10] video coeffs,
  [11..15] audio); step_dit branches on V->sampler.
- server: `sampler` string field ("euler"/empty, "res_multistep", else
  invalid_request_error with the supported list); echoed on the job object;
  capabilities advertise video_samplers.

Tests: rad-avx-check 816 + 451 hand-built, 0 fail (left-assoc grouping matches
ref/device at tol 0); r4d_selftest --case flow_res_multistep_f32 f32|bf16 x
order {1,2} exact, both INOUT pitch gaps untouched.

Device-verified (TP2, fp8 container, 256^2/2s/10-step, seed 1234 identical):
both samplers complete clean 73-frame h264; outputs differ (branch genuinely
consumed, not ignored); bad value rejected; field omitted -> euler. res_multistep
renders warmer/higher-contrast than euler -- a tone lever, not an over-exposure
fix. The euler default path is unchanged.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
gearwave00001andClaude committed 2026-10-20 18:28:49 -05:00
1 parent c8c8f93789
commit 8785774fc0
18 files changed
+391 -12

No files matched your search

+1 -1
View File
@@ -17,7 +17,7 @@ extern "C" {
* kind of plugin reports it, and a plugin that does not report exactly this version is refused at
* load with both versions printed. A new optional export (e.g. rad_plugin_reference) is not a
* change of shape: a plugin without it gets the default. */
#define RAD_ABI_VERSION 23u
#define RAD_ABI_VERSION 24u
/* ================================================================== plugin identity */
/* One value per plugin, not flags (QUANT is 3). RAD_PLUGIN_QUANT is a quantiser plugin:
+12
View File
@@ -428,6 +428,15 @@ enum {
* AENCODE no rows of the pass's own: a reference audio's samples in `enc_samples`.
*
* Every pointer is device memory unless the name ends in _h. */
/* RadVideoGenBatch::sampler: which sampler advances a lane's latents each step. EULER is the
* first-order step (`flow_x0_step`) every model has run with; RES_MULTISTEP is the second-order
* Adams-Bashforth step on the clean estimate (`flow_res_multistep`, DPM-Solver++2M data-prediction
* / k-diffusion's res_multistep at eta=0), which needs the previous step's estimate kept between
* steps. The driver stages both schedules' scalars into `sched` regardless, so a plugin reads the
* one its sampler names. A batch without the field laid out is an older engine's: EULER. */
enum { RAD_SAMPLER_EULER = 0, RAD_SAMPLER_RES_MULTISTEP = 1 };
typedef struct RadVideoGenBatch {
int32_t lane;
RadVideoGeom geom; /* the request's geometry */
@@ -518,6 +527,9 @@ typedef struct RadVideoGenBatch {
* ride a fixed table. On a plain request (or one that merges nothing) it is exactly `seg_cu`; a
* driver stages the same bytes into both. Trailing since ABI 23. */
const int32_t* mod_cu;
/* ---- The sampler that advances the latents: RAD_SAMPLER_* above. Trailing since ABI 24. */
int32_t sampler;
} RadVideoGenBatch;
/* RadVideoGenBatch::enc_kind: which reference media an encode pass carries. A plugin's latent
+45 -7
View File
@@ -433,6 +433,8 @@ struct Model {
rad_buf b_nout = 0; /* [lanes * S, 3 * 2D] bf16: norm_out's, by segment */
rad_buf b_vstate = 0; /* [lanes * maxV, 96] f32 */
rad_buf b_astate = 0; /* [lanes * maxA, 32] f32 */
rad_buf b_vx0 = 0; /* [lanes * maxV, 96] f32: res_multistep's previous video estimate */
rad_buf b_ax0 = 0; /* [lanes * maxA, 32] f32: the soundtrack's */
rad_buf b_prev = 0; /* [lanes * 5 * area, 3] bf16: the decoder's frames across chunks */
/* ---- the DiT */
@@ -460,6 +462,7 @@ struct Model {
std::vector<DitBlock> dit;
rad_weight w_no_n = 0, w_vout = 0, b_vout = 0, w_aout = 0, b_aout = 0;
rad_op op_nout = 0, op_hcast = 0, op_vout = 0, op_aout = 0, op_ev = 0, op_ea = 0;
rad_op op_rmv = 0, op_rma = 0; /* the res_multistep step, video and soundtrack */
/* ---- the audio decoder */
std::string a_mean, a_std;
@@ -1107,6 +1110,8 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) {
/* ---- the lanes' latents, and the first step's noise */
m.b_vstate = decl_b(b, nm.f("lane.video"), RAD_F32, { La * m.maxV, kPatchVals }, RAD_BUF_PERSIST);
m.b_astate = decl_b(b, nm.f("lane.audio"), RAD_F32, { La * m.maxA, kAudioC }, RAD_BUF_PERSIST);
m.b_vx0 = decl_b(b, nm.f("lane.video.x0"), RAD_F32, { La * m.maxV, kPatchVals }, RAD_BUF_PERSIST);
m.b_ax0 = decl_b(b, nm.f("lane.audio.x0"), RAD_F32, { La * m.maxA, kAudioC }, RAD_BUF_PERSIST);
m.op_rnd_v = rw(b, RAD_OP(b, "randn_lanes",
RAD_PARAMS(RAD_RANGE("M", 1, m.maxV), RAD_INT("n", kPatchVals),
RAD_INT("stride", m.maxV), RAD_STR("dtype", "f32")),
@@ -1382,7 +1387,21 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) {
RAD_STR("dtype", "f32")),
RAD_NOWEIGHTS),
{ m.b_avel, m.b_astate }, { m.b_astate });
return m.op_hcast && m.op_vout && m.op_aout && m.op_ev && m.op_ea ? RAD_OK : RAD_E_INVAL;
/* The second-order step's two INOUT buffers: the estimate history is both read (previous d) and
* written (this d), and the latent x as before; the velocity is read-only. Issued instead of the
* Euler pair when the batch's sampler is RES_MULTISTEP. */
m.op_rmv = rw(b, RAD_OP(b, "flow_res_multistep",
RAD_PARAMS(RAD_RANGE("M", 1, m.maxV), RAD_INT("n", kPatchVals),
RAD_STR("dtype", "f32")),
RAD_NOWEIGHTS),
{ m.b_vel, m.b_vx0, m.b_vstate }, { m.b_vx0, m.b_vstate });
m.op_rma = rw(b, RAD_OP(b, "flow_res_multistep",
RAD_PARAMS(RAD_RANGE("M", 1, m.maxA), RAD_INT("n", kAudioC),
RAD_STR("dtype", "f32")),
RAD_NOWEIGHTS),
{ m.b_avel, m.b_ax0, m.b_astate }, { m.b_ax0, m.b_astate });
return m.op_hcast && m.op_vout && m.op_aout && m.op_ev && m.op_ea && m.op_rmv && m.op_rma
? RAD_OK : RAD_E_INVAL;
}
/* ================================================================== the audio decoder */
@@ -3524,12 +3543,31 @@ static void step_dit(RadCtx* c, const RadBatch* batch, const Model& m) {
};
heads(m.op_aout, m.w_aout, m.b_aout, aseg, arows, kAudioC, m.b_avel);
heads(m.op_vout, m.w_vout, m.b_vout, vseg, vrows, kPatchVals, m.b_vel);
RAD_ISSUE_N(c, m.op_ev, vrows, brows(m.b_vel, vrows), praw(V->sched, RAD_F32, 1),
praw(V->sched + 1, RAD_F32, 1), praw(V->sched + 2, RAD_F32, 1),
brow_slice(m.b_vstate, lane * m.maxV, vrows, kPatchVals));
RAD_ISSUE_N(c, m.op_ea, arows, brows(m.b_avel, arows), praw(V->sched + 3, RAD_F32, 1),
praw(V->sched + 4, RAD_F32, 1), praw(V->sched + 5, RAD_F32, 1),
brow_slice(m.b_astate, lane * m.maxA, arows, kAudioC));
/* The step: Euler (the clean estimate alone, the lane's latent only) or the second-order
* res_multistep, which also reads and rotates the previous estimate kept in the lane's x0 buffer.
* The driver stages the scalars for whichever runs: sched[0..5] the Euler t/sigmas, sched[6..10]
* the video's sigma/r/hb1/hb2/order and sched[11..15] the soundtrack's. */
if (V->sampler == RAD_SAMPLER_RES_MULTISTEP) {
RAD_ISSUE_N(c, m.op_rmv, vrows, brows(m.b_vel, vrows),
brow_slice(m.b_vx0, lane * m.maxV, vrows, kPatchVals),
praw(V->sched + 6, RAD_F32, 1), praw(V->sched + 7, RAD_F32, 1),
praw(V->sched + 8, RAD_F32, 1), praw(V->sched + 9, RAD_F32, 1),
praw(V->sched + 10, RAD_F32, 1),
brow_slice(m.b_vstate, lane * m.maxV, vrows, kPatchVals));
RAD_ISSUE_N(c, m.op_rma, arows, brows(m.b_avel, arows),
brow_slice(m.b_ax0, lane * m.maxA, arows, kAudioC),
praw(V->sched + 11, RAD_F32, 1), praw(V->sched + 12, RAD_F32, 1),
praw(V->sched + 13, RAD_F32, 1), praw(V->sched + 14, RAD_F32, 1),
praw(V->sched + 15, RAD_F32, 1),
brow_slice(m.b_astate, lane * m.maxA, arows, kAudioC));
} else {
RAD_ISSUE_N(c, m.op_ev, vrows, brows(m.b_vel, vrows), praw(V->sched, RAD_F32, 1),
praw(V->sched + 1, RAD_F32, 1), praw(V->sched + 2, RAD_F32, 1),
brow_slice(m.b_vstate, lane * m.maxV, vrows, kPatchVals));
RAD_ISSUE_N(c, m.op_ea, arows, brows(m.b_avel, arows), praw(V->sched + 3, RAD_F32, 1),
praw(V->sched + 4, RAD_F32, 1), praw(V->sched + 5, RAD_F32, 1),
brow_slice(m.b_astate, lane * m.maxA, arows, kAudioC));
}
}
/* The soundtrack: both channels, each a sequence, through the audio decoder, then interleaved. */
+3
View File
@@ -119,6 +119,9 @@ struct VideoRequest {
int32_t width = 0, height = 0; /* pixels, within the declaration's limits */
int32_t chunks = 0; /* the length in chunks (RadVideoGenDecl) */
int32_t steps = 0; /* sigma grid points; 0: the model's default */
/* The sampler: a RAD_SAMPLER_* value (abi/rad_runtime.h). 0 = Euler, the default; 1 =
* res_multistep, the second-order step on the clean estimate. */
int32_t sampler = 0;
/* Latent upscaling (abi/rad_builder.h, RadVideoGenDecl): the factor, 0 for none, and the
* evaluations at the full size after it, 0 for the model's default. */
double upscale = 0.0;
+43 -4
View File
@@ -165,7 +165,8 @@ int64_t carve(const RadVideoGenDecl& d, int64_t max_tok, int64_t ep, int64_t pd,
2 * 4, /* R_CU */
3 * max_tok * 4, /* R_ROPE: a step's rotary positions, a conditioning's [3,T] M-RoPE */
RAD_VGEOM_N * 4, /* R_GEOM */
6 * 4, /* R_SCHED */
16 * 4, /* R_SCHED: the Euler scalars [0..5], then the res_multistep
* coeffs -- video [6..10], audio [11..15] */
d.max_steps * 4, /* R_TV */
d.max_steps * 4, /* R_TA */
4 * 4, /* R_SEED */
@@ -886,6 +887,7 @@ void VideoDriver::base_batches(const Job& j, const RadVideoGeom& g, int64_t n_to
V.t_video = dptr<float>(ri, R_TV);
V.t_audio = dptr<float>(ri, R_TA);
V.step = j.step;
V.sampler = j.req->sampler;
V.sched = dptr<float>(ri, R_SCHED);
V.pos = dptr<float>(ri, R_ROPE);
V.seed = dptr<uint32_t>(ri, R_SEED);
@@ -1052,8 +1054,21 @@ const RadBatch* VideoDriver::build_cond(Job& j, int step) {
return &out_[0];
}
/* Step i's timesteps and sigmas, the video's then the soundtrack's (RadVideoGenBatch::sched);
* with `to_clean` the next sigmas are 0, so the step lands on its clean estimate. */
/* Step i's timesteps, sigmas and sampler coefficients (RadVideoGenBatch::sched). With `to_clean` the
* next sigmas are 0, so the step lands on its clean estimate. Both samplers' scalars are staged
* whichever runs, so the plugin reads the slots its sampler names:
* [0..5] Euler: video (t, sigma, sigma_next) then soundtrack.
* [6..10] res_multistep, video: sigma (= the velocity's weight), r = sigma_next/sigma, hb1, hb2,
* order (1 or 2).
* [11..15] res_multistep, soundtrack: the same five.
* The coefficients are DPM-Solver++2M data-prediction / k-diffusion res_multistep at eta=0: with
* h = log(sigma/sigma_next), h_last = log(sigma_prev/sigma) and rs = h_last/h,
* hb1 = (1 - r)(1 + 1/(2 rs)), hb2 = -(1 - r)/(2 rs), order = 2.
* They are used only on a step that has a previous estimate on the SAME latent grid, so `order` is 1
* (plain Euler, hb unused) on the first step, on the first full-size step after a latent upscale
* (i == split, whose grid and rows differ from the small run's stale history) and on a step whose
* next sigma is 0 (the last, or the last small step). hb1 + hb2 == 1 - r on the two-estimate steps,
* so every branch shares the Euler limit. */
void VideoDriver::stage_sched(const Job& j, int32_t i, bool to_clean) {
float* s = hptr<float>(R_SCHED);
s[0] = 1.0f - j.sched.sig_v[(size_t)i];
@@ -1062,7 +1077,31 @@ void VideoDriver::stage_sched(const Job& j, int32_t i, bool to_clean) {
s[3] = 1.0f - j.sched.sig_a[(size_t)i];
s[4] = j.sched.sig_a[(size_t)i];
s[5] = to_clean ? 0.0f : j.sched.sig_a[(size_t)i + 1];
reg_[R_SCHED].used = 6 * 4;
/* A stream's res_multistep coefficients, written to out[0..4]. `prev` is the step before this
* one's sigma (>= i so i > 0), and the restart step (i == split) forces Euler. */
auto coeffs = [&](const std::vector<float>& sig, float* out) {
const float sg = sig[(size_t)i];
const float sgn = to_clean ? 0.0f : sig[(size_t)i + 1];
const float r = sg > 0.0f ? sgn / sg : 0.0f;
float hb1 = 1.0f - r, hb2 = 0.0f, order = 1.0f;
const bool two = sgn > 0.0f && i > 0 && !(j.split > 0 && i == j.split);
if (two) {
const float h = std::log(sg / sgn);
const float h_last = std::log(sig[(size_t)i - 1] / sg);
const float rs = h_last / h;
hb1 = (1.0f - r) * (1.0f + 1.0f / (2.0f * rs));
hb2 = -(1.0f - r) / (2.0f * rs);
order = 2.0f;
}
out[0] = sg;
out[1] = r;
out[2] = hb1;
out[3] = hb2;
out[4] = order;
};
coeffs(j.sched.sig_v, s + 6);
coeffs(j.sched.sig_a, s + 11);
reg_[R_SCHED].used = 16 * 4;
}
/* The video's noise seed is the request's; the soundtrack's the same with its top bit flipped, so
+18
View File
@@ -59,6 +59,7 @@ struct Server::VideoJob {
std::string id, model, prompt, seconds, size;
int64_t created_at = 0;
uint64_t seed = 0;
int32_t sampler = 0; /* the request's RAD_SAMPLER_* */
std::shared_ptr<gen::VideoTicket> ticket;
std::thread worker;
/* Under Server::videos_m_ from here on. */
@@ -271,6 +272,8 @@ void Server::video_caps(json& caps, const IVideoGen* gen) {
/* The containers `format` accepts; mp4 is the default and always available, the webm codecs
* only when this build's libavcodec has the encoder and muxer for them. */
caps["video_formats"] = json::array({ "mp4", "webm", "webm-av1" });
/* The samplers `sampler` accepts; euler is the default and always available. */
caps["video_samplers"] = json::array({ "euler", "res_multistep" });
}
HttpResponse Server::handle_video_create(const HttpRequest& req) {
@@ -343,6 +346,7 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
static const char* kKnown[] = {
"model", "prompt", "seconds", "size", "input_reference", "seed", "num_inference_steps",
"task", "target", "conditions", "user", "latent_upscale", "upscale_refine_steps", "format",
"sampler",
};
for (auto it = body.begin(); it != body.end(); ++it) {
bool known = false;
@@ -553,6 +557,18 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
" (sigma grid points, the last one 0)");
r->steps = (int32_t)v;
}
if (has(body, "sampler")) {
const std::string sm = body["sampler"].is_string() ? body["sampler"].get<std::string>() : "";
if (sm.empty() || sm == "euler") r->sampler = RAD_SAMPLER_EULER;
else if (sm == "res_multistep") r->sampler = RAD_SAMPLER_RES_MULTISTEP;
else {
ApiError e = err_unsupported("sampler", "the sampler is euler (first order) or "
"res_multistep (second order on the clean "
"estimate)");
e.supported = { "euler", "res_multistep" };
return error_response(e, req.peer);
}
}
if (has(body, "latent_upscale")) {
double v = 0;
if (!(info.upscale_max > 0.0))
@@ -770,6 +786,7 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
j->size = std::to_string(W) + "x" + std::to_string(H);
j->created_at = unix_now();
j->seed = r->seed;
j->sampler = r->sampler;
j->fmt = fmt;
for (const gen::VideoRefMedia& m : r->refs) j->refs.push_back(m.name);
j->ticket = std::make_shared<gen::VideoTicket>();
@@ -955,6 +972,7 @@ json Server::video_json(const VideoJob& j) {
o["size"] = j.size;
o["seed"] = j.seed;
o["format"] = format_name(j.fmt); /* what /content will return */
o["sampler"] = j.sampler == RAD_SAMPLER_RES_MULTISTEP ? "res_multistep" : "euler";
if (j.refine > 0) {
o["latent_upscale"] = j.upscale;
o["upscale_refine_steps"] = j.refine;
+18
View File
@@ -2154,6 +2154,24 @@ void video_cases(std::vector<Hand>& hs) {
hs.push_back(std::move(h));
}
/* ---- the second-order sampler: a bf16 velocity, f32 state AND estimate history, both
* INOUT at wider pitches; order=2 leans on the history, order=1 is the Euler limit -- */
for (float order : { 2.0f, 1.0f }) {
Hand h((std::string(order >= 1.5f ? "two-estimate" : "Euler limit") +
", bf16 velocity, f32 state and history" + sfx).c_str(),
"flow_res_multistep", 0.0);
h.dense(dt, { 7, 96 }, hfill(422, 2.0f))
.view(RAD_F32, { 7, 96 }, { 99, 1 }, 7 * 99, hfill(423), true) /* x0, INOUT */
.dense(RAD_F32, { 1 }, [](int64_t) { return 0.5625f; }) /* sigma */
.dense(RAD_F32, { 1 }, [](int64_t) { return 0.625f; }) /* r */
.dense(RAD_F32, { 1 }, [](int64_t) { return 0.24f; }) /* hb1 */
.dense(RAD_F32, { 1 }, [](int64_t) { return -0.005f; }) /* hb2 */
.dense(RAD_F32, { 1 }, [order](int64_t) { return order; }) /* order */
.view(RAD_F32, { 7, 96 }, { 101, 1 }, 7 * 101, hfill(424), true) /* x, INOUT */
.pi("M", 7).pi("n", 96).ps("dtype", dn);
hs.push_back(std::move(h));
}
/* ---- the decoder's geometry: 3 frames of 6 x 9 latents, tiles of 4 over 1 ------------ *
* Rows split 6 -> starts 0, 2 (overlap 2); columns 9 -> 0, 2, 5 (overlaps 2, 1). */
{
+51
View File
@@ -694,6 +694,57 @@ AVX_KERNEL(flow_x0_step) {
return RAD_OK;
}
/* x' = f32(f32(r x) + f32(hb1 d) + f32(hb2 x0)) when order >= 2, else the Euler form
* f32(f32(r x) + f32((1 - r) d)), with d = f32(x + f32(sigma v)): libref's step bit for bit, `keep`
* holding each product to its own rounding. x0 is the previous estimate (read here, d written back). */
AVX_KERNEL(flow_res_multistep) {
if (!rad_args_have(a, 8)) return RAD_E_INVAL;
const RadTensor *V = &a->t[0], *X0 = &a->t[1], *SG = &a->t[2], *RR = &a->t[3];
const RadTensor *HB1 = &a->t[4], *HB2 = &a->t[5], *ORD = &a->t[6], *X = &a->t[7];
const int64_t n = p_int(a, "n", 0);
if (n <= 0) return RAD_E_SHAPE;
const int64_t rows = rows_of(X, n);
if (rows <= 0 || rows_of(V, n) < rows || rows_of(X0, n) < rows || numel(SG) < 1 ||
numel(RR) < 1 || numel(HB1) < 1 || numel(HB2) < 1 || numel(ORD) < 1)
return RAD_E_SHAPE;
const float sg = ldt(SG, offlin(SG, 0));
const float r = ldt(RR, offlin(RR, 0));
const float b1 = ldt(HB1, offlin(HB1, 0));
const float b2 = ldt(HB2, offlin(HB2, 0));
const bool two = ldt(ORD, offlin(ORD, 0)) >= 1.5f;
const float omr = 1.0f - r;
AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN)
for (int64_t k = 0; k < rows; ++k) {
float* buf = scratch_f32((size_t)(5 * n + 64));
float *vs = buf, *xs = buf + n + 16, *h0s = xs + n + 16, *o = h0s + n + 16, *o0 = o + n + 16;
const float* v = in_row(V, rowoff(V, k, n), n, vs);
const float* x = in_row(X, rowoff(X, k, n), n, xs);
const float* h0 = in_row(X0, rowoff(X0, k, n), n, h0s);
const vf vsg = vf_set1(sg), vr = vf_set1(r), vb1 = vf_set1(b1), vb2 = vf_set1(b2),
vo = vf_set1(omr);
int64_t c = 0;
for (; c + VF_N <= n; c += VF_N) {
const vf xv = vf_loadu(x + c);
const vf d = vf_add(xv, keep(vf_mul(vsg, vf_loadu(v + c))));
const vf a = keep(vf_mul(vr, xv));
vf xo = two ? vf_add(vf_add(a, keep(vf_mul(vb1, d))), keep(vf_mul(vb2, vf_loadu(h0 + c))))
: vf_add(a, keep(vf_mul(vo, d)));
vf_storeu(o + c, xo);
vf_storeu(o0 + c, d);
}
for (; c < n; ++c) {
const float d = x[c] + keep(sg * v[c]);
const float a = keep(r * x[c]);
o[c] = two ? (a + keep(b1 * d)) + keep(b2 * h0[c]) : a + keep(omr * d);
o0[c] = d;
}
out_row(X, rowoff(X, k, n), n, o);
out_row(X0, rowoff(X0, k, n), n, o0);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ chan_affine */
/* A per-channel affine from two lists of n bf16 values: `fma` is bf16(bf16(x * mul) + add), `inv`
* is bf16(bf16(x - add) / mul), the inner rounding in y's dtype. */
+1
View File
@@ -111,6 +111,7 @@ int avx_par_force(int threads);
X(scatter_add_rows) X(attn_prefix_self) \
/* ---- video generation */ \
X(rms_mod) X(rms_mod_quant_fp8) X(flow_x0_step) X(patch_unfold) \
X(flow_res_multistep) \
X(vtile_gather) X(vtile_stitch) X(grid_pos3) X(vsa_select) \
X(attn_vsa) X(conv3d_ndhwc) X(group_norm) X(tconv_dw) \
X(resize_bilinear) X(patch_fold) X(flow_renoise) \
+7
View File
@@ -485,6 +485,8 @@ static const RadOperandSpec oRmsModQ[] = { OPD_O("y"), OPD_O("g"), OPD("s"), WGT
OUT_O("z") };
static const RadOperandSpec oFlowX0[] = { OPD("v"), OPD("t"), OPD("sigma"), OPD("sigma_next"),
INOUT("x") };
static const RadOperandSpec oFlowRM[] = { OPD("v"), INOUT("x0"), OPD("sigma"), OPD("r"),
OPD("hb1"), OPD("hb2"), OPD("order"), INOUT("x") };
static const RadParamSpec pTimestep[] = { P_INT("M"), P_INT("n"), P_F64("scale"), P_F64("max_period"),
P_INTO("round"), P_F64O("clamp_min"), P_STR("dtype") };
static const RadOperandSpec oTimestep[] = { OPD("t"), OUT("y") };
@@ -938,6 +940,9 @@ static const RadOpSchema kSchemas[] = {
{ "flow_x0_step", ARR(pMnD), ARR(oFlowX0),
"x = r x + (1 - r)(x + (1 - t) v), r = sigma_next / sigma, each step one f32 rounding, bit for "
"bit libref's." },
{ "flow_res_multistep", ARR(pMnD), ARR(oFlowRM),
"x = r x + hb1 (x + sigma v) + hb2 x0, r = sigma_next / sigma; order<2 is Euler "
"(x = r x + (1 - r)(x + sigma v)); bit for bit libref's." },
{ "patch_unfold", ARR(pPatchUnfold), ARR(oPatchUnfold),
"patch rows to denormalised voxel rows, f32(f32(x * mul) + add), bit for bit libref's." },
{ "vtile_gather", ARR(pVtileGather), ARR(oVtileGather),
@@ -1419,6 +1424,8 @@ SIMPLE("avx_rms_mod_quant_fp8", "rms_mod_quant_fp8", "norm",
L(rms_mod_quant_fp8)),
SIMPLE("avx_flow_x0_step", "flow_x0_step", "elem", "a sampler step toward the clean estimate",
DT_FLOAT, L(flow_x0_step)),
SIMPLE("avx_flow_res_multistep", "flow_res_multistep", "elem",
"a second-order sampler step on the clean estimate", DT_FLOAT, L(flow_res_multistep)),
SIMPLE("avx_patch_unfold", "patch_unfold", "elem", "patch rows to denormalised voxel rows",
DT_FLOAT, L(patch_unfold)),
SIMPLE("avx_vtile_gather", "vtile_gather", "elem", "a video decoder's tiles out of the latent",
+1
View File
@@ -196,6 +196,7 @@ int r4d_rad_rms_mod (const RadArgs*, RadStream);
int r4d_rad_rms_mod_quant_fp8 (const RadArgs*, RadStream);
int r4d_rad_rms_mod_quant_i8 (const RadArgs*, RadStream);
int r4d_rad_flow_x0_step (const RadArgs*, RadStream);
int r4d_rad_flow_res_multistep (const RadArgs*, RadStream);
int r4d_rad_patch_unfold (const RadArgs*, RadStream);
int r4d_rad_vtile_gather (const RadArgs*, RadStream);
int r4d_rad_vtile_stitch (const RadArgs*, RadStream);
+15
View File
@@ -2306,6 +2306,11 @@ static const RadOperandSpec oFlowX0[] = {
{ "v", RAD_OPD_IN, 0 }, { "t", RAD_OPD_IN, 0 }, { "sigma", RAD_OPD_IN, 0 },
{ "sigma_next", RAD_OPD_IN, 0 }, { "x", RAD_OPD_INOUT, 0 },
};
static const RadOperandSpec oFlowRM[] = {
{ "v", RAD_OPD_IN, 0 }, { "x0", RAD_OPD_INOUT, 0 }, { "sigma", RAD_OPD_IN, 0 },
{ "r", RAD_OPD_IN, 0 }, { "hb1", RAD_OPD_IN, 0 }, { "hb2", RAD_OPD_IN, 0 },
{ "order", RAD_OPD_IN, 0 }, { "x", RAD_OPD_INOUT, 0 },
};
static const RadParamSpec pPatchUnfold[] = { P_INT("M"), P_INT("C"), P_INT("pt"), P_INT("ph"),
P_INT("pw"), P_STR("mul"), P_STR("add"),
P_STR("dtype") };
@@ -3047,6 +3052,9 @@ static const RadOpSchema kSchemas[] = {
SCHEMA("flow_x0_step", pGenMn, oFlowX0,
"x = r x + (1 - r) (x + (1 - t) v), r = sigma_next / sigma, each step one f32 "
"rounding."),
SCHEMA("flow_res_multistep", pGenMn, oFlowRM,
"x = r x + hb1 (x + sigma v) + hb2 x0, r = sigma_next / sigma, x0 the previous estimate; "
"order<2 is Euler."),
SCHEMA("patch_unfold", pPatchUnfold, oPatchUnfold,
"patch rows unfolded to voxel rows and denormalised with f32 lists."),
SCHEMA("vtile_gather", pVtileGather, oVtileGather,
@@ -7309,6 +7317,13 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
ROW(cGenF32), NOTUNE,
nullptr, nullptr, r4d_rad_flow_x0_step },
{ "flow_res_multistep_f32", "flow_res_multistep", "elem",
"a second-order sampler step on the clean estimate", "any M, row pitches honoured",
"f32 state and estimate history, f32 or bf16 velocity",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cGenF32), NOTUNE,
nullptr, nullptr, r4d_rad_flow_res_multistep },
{ "patch_unfold_f32", "patch_unfold", "elem",
"patch rows to denormalised voxel rows, the geometry read on the device",
"C <= 64, row pitches honoured", "f32",
+47
View File
@@ -6388,6 +6388,52 @@ void flow_x0_cases(const Plugin& pl) {
}
}
/* flow_res_multistep: an f32 and a bf16 velocity, the state AND the estimate history INOUT at wider,
* unequal pitches; order=2 leans on the history, order=1 is the Euler limit. Every value exact, and
* both INOUT buffers' pitch gaps left untouched -- the two-INOUT path exercised for the first time. */
void flow_rm_cases(const Plugin& pl) {
const RadKernelInfo* r = find(pl, "flow_res_multistep_f32");
if (!r) { ok("flow_res_multistep_f32", false, "row absent"); return; }
const int64_t M = 37, n = 96, xld = 100, x0ld = 102;
for (const bool bf : { false, true })
for (const float order : { 2.0f, 1.0f }) {
std::vector<float> x = randv((size_t)(M * xld), 3.0f), x0 = randv((size_t)(M * x0ld), 2.0f),
v = randv((size_t)(M * n), 2.0f);
const std::vector<float> sg = { 0.5625f }, rr = { 0.625f }, hb1 = { 0.24f },
hb2 = { -0.005f }, ord = { order };
void* dx = up_f32(x);
void* dx0 = up_f32(x0);
void* dv = bf ? up_bf16(v) : up_f32(v);
RadTensor tx = T(dx, RAD_F32, { M, n }); tx.stride[0] = xld;
RadTensor tx0 = T(dx0, RAD_F32, { M, n }); tx0.stride[0] = x0ld;
const std::string nm =
fmt("flow_res_multistep_f32 %s velocity order %g", bf ? "bf16" : "f32", order);
const int rc = launch(r, { T(dv, bf ? RAD_BF16 : RAD_F32, { M, n }), tx0,
T(up_f32(sg), RAD_F32, { 1 }), T(up_f32(rr), RAD_F32, { 1 }),
T(up_f32(hb1), RAD_F32, { 1 }), T(up_f32(hb2), RAD_F32, { 1 }),
T(up_f32(ord), RAD_F32, { 1 }), tx },
{ PI("M", M), PI("n", n), PS("dtype", "f32") });
if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; }
const bool two = order >= 1.5f;
const float ra = rr[0], b1 = hb1[0], b2 = hb2[0], omr = 1.0f - ra;
std::vector<float> wantx = x, wantx0 = x0; /* gaps keep their original bytes */
for (int64_t row = 0; row < M; ++row)
for (int64_t c = 0; c < n; ++c) {
const float xv = x[(size_t)(row * xld + c)];
const float h0 = x0[(size_t)(row * x0ld + c)];
const float p = sg[0] * v[(size_t)(row * n + c)];
const float d = xv + p;
const float a = ra * xv;
wantx[(size_t)(row * xld + c)] = two ? (a + b1 * d) + b2 * h0 : a + omr * d;
wantx0[(size_t)(row * x0ld + c)] = d;
}
int64_t bad = differ(down_f32(dx, wantx.size()), wantx);
bad += differ(down_f32(dx0, wantx0.size()), wantx0);
ok((nm + " exact, both INOUT gaps untouched").c_str(), bad == 0,
fmt("%lld values differ", (long long)bad));
}
}
/* grid_pos3: MiniMax-H3's tile of 7 x 16 x 16 and its registers over two periods, written into a
* [3, M] view of a wider plane; exact. */
void grid_pos3_cases(const Plugin& pl) {
@@ -19448,6 +19494,7 @@ static void device_phase(const Plugin& pl) {
if (sel("rms_mod_bf16")) vid::rms_mod_cases(pl, false);
if (sel("rms_mod_quant_fp8_bf16")) vid::rms_mod_cases(pl, true);
if (sel("flow_x0_step_f32")) vid::flow_x0_cases(pl);
if (sel("flow_res_multistep_f32")) vid::flow_rm_cases(pl);
if (sel("grid_pos3")) vid::grid_pos3_cases(pl);
if (sel("snake_aa_f32")) vid::snake_aa_cases(pl);
/* A video latent upscaler's ops, at its source and target sizes. */
+59
View File
@@ -165,6 +165,35 @@ __global__ __launch_bounds__(kT) void flow_x0_kernel(
*xp = ra * xv + omr * d;
}
// ---------------------------------------------------------------------------- flow_res_multistep
// A second-order sampler step on the clean estimate: d = x + sigma v, then x' = r x + hb1 d + hb2 x0
// with r = sigma_next / sigma and x0 the previous step's estimate (read, then d written back for the
// next step). order<2 is Euler -- x' = r x + (1 - r) d, the first step, a schedule restart and the
// last step -- and on the two-estimate steps hb1 + hb2 == 1 - r, so both share the Euler limit.
template <typename TV>
__global__ __launch_bounds__(kT) void flow_rm_kernel(
const TV* __restrict__ v, float* __restrict__ x0, const float* __restrict__ sg,
const float* __restrict__ rr, const float* __restrict__ hb1, const float* __restrict__ hb2,
const float* __restrict__ ord, float* __restrict__ x, int n, int v_ld, int x_ld, int x0_ld,
int64_t total) {
const int64_t id = (int64_t)blockIdx.x * kT + threadIdx.x;
if (id >= total) return;
const int64_t r = id / n;
const int c = (int)(id % n);
const float sgv = sg[0];
const float ra = rr[0];
const float b1 = hb1[0];
const float b2 = hb2[0];
const bool two = ord[0] >= 1.5f;
const float omr = 1.0f - ra;
float* xp = x + r * x_ld + c;
float* op = x0 + r * x0_ld + c;
const float xv = *xp;
const float d = xv + sgv * ldv(v, r * v_ld + c);
*xp = two ? ra * xv + b1 * d + b2 * (*op) : ra * xv + omr * d;
*op = d;
}
// ---------------------------------------------------------------------------- patch_unfold
// The two parameter lists of the latent's statistics, f32 kernel arguments.
constexpr int kMaxChan = 64;
@@ -517,6 +546,36 @@ extern "C" int r4d_rad_flow_x0_step(const RadArgs* a, RadStream s) {
return st_of(hipGetLastError());
}
extern "C" int r4d_rad_flow_res_multistep(const RadArgs* a, RadStream s) {
const RadTensor *v = r4d_opt(a, 0), *x0 = r4d_opt(a, 1), *sg = r4d_opt(a, 2);
const RadTensor *rr = r4d_opt(a, 3), *hb1 = r4d_opt(a, 4), *hb2 = r4d_opt(a, 5);
const RadTensor *ord = r4d_opt(a, 6), *x = r4d_opt(a, 7);
if (!v || !x0 || !sg || !rr || !hb1 || !hb2 || !ord || !x) return R4D_NO(RAD_E_INVAL);
if (!is_f32(x) || !is_f32(x0) || !is_f32(sg) || !is_f32(rr) || !is_f32(hb1) || !is_f32(hb2) ||
!is_f32(ord) || (!is_f32(v) && !is_bf16(v)))
return R4D_NO(RAD_E_DTYPE);
const long long n = r4d_geti_or(a, "n", 0);
long long rx = 0, rv = 0, rx0 = 0;
const long long xl = n > 0 ? r4d_rows_pitch(x, n, &rx) : -1;
const long long vl = n > 0 ? r4d_rows_pitch(v, n, &rv) : -1;
const long long x0l = n > 0 ? r4d_rows_pitch(x0, n, &rx0) : -1;
if (xl < 0 || vl < 0 || x0l < 0) return R4D_NO(RAD_E_STRIDE);
if (rx <= 0 || rv < rx || rx0 < rx || r4d_numel(sg) < 1 || r4d_numel(rr) < 1 ||
r4d_numel(hb1) < 1 || r4d_numel(hb2) < 1 || r4d_numel(ord) < 1)
return R4D_NO(RAD_E_SHAPE);
const int64_t total = (int64_t)rx * n;
#define R4D_FRM(TV) \
hipLaunchKernelGGL(flow_rm_kernel<TV>, dim3(blocks_for(total)), dim3(kT), 0, (hipStream_t)s, \
(const TV*)v->data, (float*)x0->data, (const float*)sg->data, \
(const float*)rr->data, (const float*)hb1->data, (const float*)hb2->data, \
(const float*)ord->data, (float*)x->data, (int)n, (int)vl, (int)xl, \
(int)x0l, total)
if (is_f32(v)) R4D_FRM(float);
else R4D_FRM(uint16_t);
#undef R4D_FRM
return st_of(hipGetLastError());
}
extern "C" int r4d_rad_patch_unfold(const RadArgs* a, RadStream s) {
const RadTensor *x = r4d_opt(a, 0), *geom = r4d_opt(a, 1), *y = r4d_opt(a, 2);
if (!x || !geom || !y) return R4D_NO(RAD_E_INVAL);
+44
View File
@@ -502,6 +502,50 @@ int ref_flow_x0_step(const RadArgs* a, RadStream) {
return RAD_OK;
}
/* ------------------------------------------------------------------ flow_res_multistep */
/* A second-order sampler step on the clean estimate (DPM-Solver++2M data-prediction, k-diffusion's
* res_multistep at eta=0). The estimate is d = x + sigma v (the same x0 an Euler step takes); the
* step then leans on the PREVIOUS step's estimate x0 (read here, then this step's d written back for
* the next): x' = r x + hb1 d + hb2 x0 with r = sigma_next / sigma. The coefficients hb1, hb2 and
* the `order` flag are the driver's -- computed so that on the first step, after a schedule restart,
* and on the last step (where the next sigma is 0) order is 1 and the two-estimate term drops out:
* with order<2 the step is Euler, x' = r x + (1 - r) d. On the two-estimate steps hb1 + hb2 == 1 - r
* exactly, so both branches share the Euler limit and the difference is the second-order correction
* alone. sigma, r, hb1, hb2 and order are one f32 value each; x and x0 f32, x the evolving latent,
* x0 the estimate history (both INOUT). */
int ref_flow_res_multistep(const RadArgs* a, RadStream) {
if (!have(a, 8)) return RAD_E_INVAL;
const RadTensor *v = &a->t[0], *x0 = &a->t[1], *sg = &a->t[2], *rr = &a->t[3];
const RadTensor *hb1 = &a->t[4], *hb2 = &a->t[5], *ord = &a->t[6], *x = &a->t[7];
const int64_t n = p_int(a, "n", 0);
if (n <= 0) return RAD_E_SHAPE;
const int64_t rows = rows_of(x, n);
if (rows <= 0 || rows_of(v, n) < rows || rows_of(x0, n) < rows || numel(sg) < 1 ||
numel(rr) < 1 || numel(hb1) < 1 || numel(hb2) < 1 || numel(ord) < 1)
return RAD_E_SHAPE;
const float sgv = ldt(sg, offlin(sg, 0));
const float r = ldt(rr, offlin(rr, 0));
const float b1 = ldt(hb1, offlin(hb1, 0));
const float b2 = ldt(hb2, offlin(hb2, 0));
const bool two = ldt(ord, offlin(ord, 0)) >= 1.5f;
const float omr = 1.0f - r;
REF_PAR_FOR(rows * n)
for (int64_t k = 0; k < rows; ++k) {
const int64_t vb = rowoff(v, k, n), vs = laststride(v);
const int64_t xb = rowoff(x, k, n), xs = laststride(x);
const int64_t ob = rowoff(x0, k, n), os = laststride(x0);
for (int64_t c = 0; c < n; ++c) {
const float xv = ldt(x, xb + c * xs);
const float d = xv + sgv * ldt(v, vb + c * vs);
const float nx = two ? r * xv + b1 * d + b2 * ldt(x0, ob + c * os)
: r * xv + omr * d;
stt(x, xb + c * xs, nx);
stt(x0, ob + c * os, d);
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ chan_affine */
/* A per-channel affine from two parameter lists (a latent's mean and deviation are configuration,
* not weights), each value rounded to bf16 as upstream holds it: mode `fma` is
+2
View File
@@ -147,6 +147,7 @@ int ref_flow_euler(const RadArgs*, RadStream);
int ref_rms_mod(const RadArgs*, RadStream);
int ref_rms_mod_quant_fp8(const RadArgs*, RadStream);
int ref_flow_x0_step(const RadArgs*, RadStream);
int ref_flow_res_multistep(const RadArgs*, RadStream);
/* ref_video.cpp */
int ref_patch_unfold(const RadArgs*, RadStream);
int ref_vtile_gather(const RadArgs*, RadStream);
@@ -350,6 +351,7 @@ REF_SHAPE_FN(ref_flow_euler);
REF_SHAPE_FN(ref_rms_mod);
REF_SHAPE_FN(ref_rms_mod_quant_fp8);
REF_SHAPE_FN(ref_flow_x0_step);
REF_SHAPE_FN(ref_flow_res_multistep);
REF_SHAPE_FN(ref_patch_unfold);
REF_SHAPE_FN(ref_vtile_gather);
REF_SHAPE_FN(ref_vtile_stitch);
+10
View File
@@ -677,6 +677,8 @@ static const RadOperandSpec oRmsModQ[] = { OPD_O("y"), OPD_O("g"), OPD("s"), WGT
/* `t`, `sigma` and `sigma_next` are one f32 value each. */
static const RadOperandSpec oFlowX0[] = { OPD("v"), OPD("t"), OPD("sigma"), OPD("sigma_next"),
INOUT("x") };
static const RadOperandSpec oFlowRM[] = { OPD("v"), INOUT("x0"), OPD("sigma"), OPD("r"),
OPD("hb1"), OPD("hb2"), OPD("order"), INOUT("x") };
static const RadParamSpec pTimestep[] = { P_INT("M"), P_INT("n"), P_F64("scale"), P_F64("max_period"),
P_INTO("round"), P_F64O("clamp_min"), P_STR("dtype") };
static const RadOperandSpec oTimestep[] = { OPD("t"), OUT("y") };
@@ -1438,6 +1440,12 @@ static const RadOpSchema kSchemas[] = {
"a sampler step toward a data-ward velocity's clean estimate, in f32: st = 1 - t, "
"d = x + st v, r = sigma_next / sigma, x = r x + (1 - r) d, each product and sum rounded "
"once; t, sigma and sigma_next one value each (MiniMax-H3's scheduler)." },
{ "flow_res_multistep", ARR(pMnD), ARR(oFlowRM),
"a second-order sampler step on the clean estimate: d = x + sigma v, then "
"x = r x + hb1 d + hb2 x0 with r = sigma_next / sigma, x0 the previous step's estimate (read, "
"then d written back for the next). order<2 makes it Euler (x = r x + (1 - r) d), the first "
"step, a schedule restart and the last step; there hb1 + hb2 = 1 - r. sigma, r, hb1, hb2 and "
"order one f32 each; x and x0 f32 (MiniMax-H3's DPM-Solver++2M / res_multistep)." },
{ "patch_unfold", ARR(pPatchUnfold), ARR(oPatchUnfold),
"patch rows [F Hp Wp, C pt ph pw] (geom = (F, Hp, Wp)) unfolded to voxel rows "
"[(F pt) (Hp ph) (Wp pw), C] and denormalised, f32(f32(x * mul[c]) + add[c]) with `mul` and "
@@ -1990,6 +1998,8 @@ SIMPLE("ref_rms_mod_quant_fp8", "rms_mod_quant_fp8", "norm",
"gated residual, modulated RMS norm, block-scaled E4M3", DT_FLOAT, ref_rms_mod_quant_fp8),
SIMPLE("ref_flow_x0_step", "flow_x0_step", "elem", "a sampler step toward the clean estimate",
DT_FLOAT, ref_flow_x0_step),
SIMPLE("ref_flow_res_multistep", "flow_res_multistep", "elem",
"a second-order sampler step on the clean estimate", DT_FLOAT, ref_flow_res_multistep),
SIMPLE("ref_patch_unfold", "patch_unfold", "elem", "patch rows to denormalised voxel rows",
DT_FLOAT, ref_patch_unfold),
SIMPLE("ref_vtile_gather", "vtile_gather", "elem", "a video decoder's tiles out of the latent",
+14
View File
@@ -2251,6 +2251,20 @@ int ref_flow_x0_step_shape(const RadParam* p, int n_p, int operand, RadOpdDesc*
o.t(F, { M, n }); /* x, INOUT */
return o.finish("flow_x0_step", operand, out);
}
int ref_flow_res_multistep_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
const uint32_t F = (uint32_t)RAD_F32;
Opd o;
o.t(act_dt(p, n_p), { M, n }); /* v */
o.t(F, { M, n }); /* x0, INOUT: the estimate history */
o.t_fill(F, { 1 }, (uint32_t)RAD_FILL_SIGMOID, 0); /* sigma */
o.t_fill(F, { 1 }, (uint32_t)RAD_FILL_SIGMOID, 0); /* r */
o.t_fill(F, { 1 }, (uint32_t)RAD_FILL_SIGMOID, 0); /* hb1 */
o.t_fill(F, { 1 }, (uint32_t)RAD_FILL_SIGMOID, 0); /* hb2 */
o.t_fill(F, { 1 }, (uint32_t)RAD_FILL_SIGMOID, 0); /* order */
o.t(F, { M, n }); /* x, INOUT */
return o.finish("flow_res_multistep", operand, out);
}
int ref_gate_add_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
const uint32_t D = act_dt(p, n_p);