PIN ref2va: verified device differential + ref-count gate (revert anchor)

Ref2VA ref-image conditioning verified on-device: ref step runs all steps no
fault; output differs ref-present vs ref-absent (by log). 6-9 images rejected
cleanly at submit (no engine crash). Merged-cell modulation (<=9) tracked next.
NOTE: placeholder author -- re-author before any push. Do NOT push this branch.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
gearwave00001andClaude committed 2026-10-19 12:04:47 -05:00
1 parent 816e24bd46
commit 490d4c604a
73 files changed
+16484 -432

No files matched your search

+27 -13
View File
@@ -235,20 +235,32 @@ AVX_KERNEL(conv1d) {
if (!Y->data) return RAD_E_INVAL;
const int64_t cin = p_int(a, "cin", 0), cout = p_int(a, "cout", 0), k = p_int(a, "k", 0);
const int64_t dil = p_int(a, "dil", 1), causal = p_int(a, "causal", 0);
const int64_t st = p_int(a, "stride", 1), ep = p_int(a, "pad", -1);
const char* act = p_str(a, "act", "none");
const bool tanh_out = act && !std::strcmp(act, "tanh");
const bool clamp_out = act && !std::strcmp(act, "clamp");
if (!tanh_out && !clamp_out && act && std::strcmp(act, "none")) return RAD_E_INVAL;
if (cin <= 0 || cout <= 0 || k <= 0 || (!causal && (k & 1) == 0) || dil <= 0 ||
causal < 0 || causal > 1)
if (cin <= 0 || cout <= 0 || k <= 0 || (!causal && st <= 1 && (k & 1) == 0) || dil <= 0 ||
causal < 0 || causal > 1 || st < 1 || (st > 1 && (causal || ep < 0)) ||
(st <= 1 && ep >= 0))
return RAD_E_SHAPE;
const int64_t n_seq = numel(cu) - 1;
if (n_seq <= 0) return RAD_E_SHAPE;
const int64_t r0 = cu_at(cu, 0), r1 = cu_at(cu, n_seq);
if (r0 < 0 || r1 <= r0 || rows_of(Y, cout) < r1 || rows_of(X, cin) < r1) return RAD_E_SHAPE;
if (r0 < 0 || r1 <= r0 || rows_of(X, cin) < r1) return RAD_E_SHAPE;
if (numel(W) < cout * cin * k || (B && numel(B) < cout)) return RAD_E_SHAPE;
if (res && rows_of(res, cout) < r1) return RAD_E_SHAPE;
const int64_t pad = causal ? dil * (k - 1) : dil * (k - 1) / 2, KK = k * cin;
/* The strided form (libref's rule): bf16, one full sequence, y the formula's rows. */
int64_t hi = r1;
if (st > 1) {
if (X->dtype != RAD_BF16) return RAD_E_DTYPE;
if (n_seq != 1 || r0 != 0 || r1 != rows_of(X, cin)) return RAD_E_SHAPE;
hi = (r1 + 2 * ep - dil * (k - 1) - 1) / st + 1;
if (hi <= 0 || rows_of(Y, cout) != hi) return RAD_E_SHAPE;
} else if (rows_of(Y, cout) < r1) {
return RAD_E_SHAPE;
}
if (res && rows_of(res, cout) < hi) return RAD_E_SHAPE;
const int64_t pad = ep >= 0 ? ep : (causal ? dil * (k - 1) : dil * (k - 1) / 2), KK = k * cin;
static thread_local std::vector<uint8_t> wbuf, pbuf;
static thread_local std::vector<float> ybuf;
@@ -263,16 +275,18 @@ AVX_KERNEL(conv1d) {
const bool b16 = X->dtype == RAD_BF16 && laststride(X) == 1;
const uint32_t adt = b16 ? (uint32_t)RAD_BF16 : (uint32_t)RAD_F32;
const size_t ael = b16 ? 2 : 4;
/* A 1-wide kernel's patch row is x's own row. */
const bool direct = k == 1 && X->rank == 2 && X->shape[1] == cin && X->stride[1] == 1 &&
(X->dtype == RAD_BF16 || X->dtype == RAD_F32);
const int64_t band = band_rows(KK, cout, r1 - r0);
/* A 1-wide kernel's patch row is x's own row; a strided op reads rows `stride` apart, so it
* always builds patches. */
const bool direct = k == 1 && st == 1 && X->rank == 2 && X->shape[1] == cin &&
X->stride[1] == 1 && (X->dtype == RAD_BF16 || X->dtype == RAD_F32);
const int64_t lo = st > 1 ? 0 : r0; /* a strided op's rows are output rows from 0 */
const int64_t band = band_rows(KK, cout, hi - lo);
if (!direct) pbuf.resize((size_t)(band * KK) * ael + 64);
ybuf.resize((size_t)(band * cout) + 16);
char* pp = (char*)pbuf.data();
float* yp = ybuf.data();
for (int64_t b0 = r0; b0 < r1; b0 += band) {
const int64_t nb = std::min(band, r1 - b0);
for (int64_t b0 = lo; b0 < hi; b0 += band) {
const int64_t nb = std::min(band, hi - b0);
RadTensor pt;
if (direct) {
pt = mat_view((char*)X->data + (size_t)(b0 * X->stride[0]) * rad_dtype_bits(X->dtype) / 8,
@@ -282,10 +296,10 @@ AVX_KERNEL(conv1d) {
pt = mat_view(pp, adt, nb, KK);
AVX_PARALLEL_FOR_IF(nb * KK >= AVX_PAR_MIN)
for (int64_t p = 0; p < nb; ++p) {
const int64_t r = b0 + p, e = seq_of(cu, n_seq, r);
const int64_t r = b0 + p, e = seq_of(cu, n_seq, st > 1 ? r * st : r);
const int64_t s0 = cu_at(cu, e), s1 = cu_at(cu, e + 1);
for (int64_t t = 0; t < k; ++t) {
const int64_t ir = r + t * dil - pad;
const int64_t ir = r * st + t * dil - pad;
patch_slot(X, ir, cin, ir >= s0 && ir < s1, b16,
pp + (size_t)(p * KK + t * cin) * ael);
}
+19
View File
@@ -97,6 +97,10 @@ std::vector<Case> build_cases() {
HS("dtype", dt) });
add("pool_rows", { HI("M", 27), HI("n", 645), HI("k", 9), HF("mult", 27.712812921102035),
HS("dtype", dt) }, EB(27, 645, w, 1));
add("pool_cols", { HI("M", 27), HI("n", 648), HI("k", 9), HF("mult", 27.712812921102035),
HS("dtype", dt) }, EB(27, 648, w, 1));
add("pool_cols", { HI("M", 40), HI("n", 256), HI("k", 8), HS("dtype", dt) },
EB(40, 256, w, 1));
add("scatter_rows", { HI("M", 6), HI("n", 645), HS("dtype", dt) }, EB(6, 645, w, 2));
add("scale_rows", { HI("M", 6), HI("n", 645), HS("act", "sigmoid"), HS("dtype", dt) },
EB(6, 645, w, 2));
@@ -317,6 +321,11 @@ std::vector<Case> build_cases() {
add("attn_dense", { HI("M", 24), HI("head_dim", 64), HI("gqa", 1), HI("causal", 0),
HS("dtype", dt), HF("scale", 0.125), HI("max_seqlen", 24),
HI("block", 7) });
/* An audio encoder's own-heads attention: head_dim 256, no GQA, causal with a window. */
for (const char* dt : { "f32", "bf16" })
add("attn_dense", { HI("M", 24), HI("head_dim", 256), HI("gqa", 1), HI("causal", 1),
HS("dtype", dt), HF("scale", 0.125), HI("max_seqlen", 24),
HI("window", 8) });
for (const char* dt : { "f32", "bf16" })
add("seg_sinusoid", { HI("M", 30), HI("n", 64), HI("period", 13), HS("dtype", dt) });
/* Gemma 4's audio attention: left 12, over segments longer than the window. */
@@ -768,6 +777,9 @@ std::vector<Case> build_cases() {
HS("act", act), HS("dtype", dt) });
add("group_norm", { HI("M", 150), HI("n", 96), HI("groups", 4), HF("eps", 1e-5),
HS("act", "silu"), HS("dtype", dt) });
/* Four channels a group at the video encoder's first level, its eps. */
add("group_norm", { HI("M", 130), HI("n", 128), HI("groups", 32), HF("eps", 1e-6),
HS("act", "silu"), HS("dtype", dt) });
add("tconv_dw", { HI("M", 27), HI("n", 645), HI("k", 5), HS("dtype", dt) });
add("tconv_dw", { HI("M", 64), HI("n", 37), HI("k", 3), HS("dtype", dt) });
add("resize_bilinear", { HI("M", 27), HI("n", 645), HS("dtype", dt) });
@@ -829,6 +841,13 @@ std::vector<Case> build_cases() {
for (int dil : { 1, 3 })
add("conv1d", { HI("M", 24), HI("cin", 20), HI("cout", 13), HI("k", 7),
HI("dil", dil), HI("causal", 1), HS("dtype", dt) });
/* The strided downsample (a DAC encoder block's): kernel 2 stride, pad ceil(stride / 2),
* one sequence. The form is bf16-only, so it rides the bf16 arm alone. */
if (std::strcmp(dt, "bf16") == 0)
for (int s : { 2, 4, 5 })
add("conv1d", { HI("M", 24), HI("cin", 20), HI("cout", 13), HI("k", 2 * s),
HI("dil", 1), HI("stride", s), HI("pad", (s + 1) / 2),
HS("dtype", dt) });
for (int s : { 2, 4, 8 })
add("conv_t1d", { HI("M", 12), HI("cin", 20), HI("cout", 13), HI("stride", s),
HS("dtype", dt) });
+98
View File
@@ -2266,6 +2266,84 @@ void upscaler_cases(std::vector<Hand>& hs) {
.pi("M", R).pi("cin", ci).pi("cout", co).pi("k", 2).pi("kt", 3).ps("dtype", dn)
.refuses(RAD_E_SHAPE);
hs.push_back(std::move(e));
/* The video encoder's CausalConv3d forms: the cube's geoms never stride, never
* mirror and never pad one side, so the downsample, a mirror-everywhere res block
* and the one-frame case are built by hand. */
{
/* (3 + 2 - 3) / 2 + 1 = 2 frames, (4 + 1 - 3) / 2 + 1 = 2 rows, (5 + 1 - 3) / 2
* + 1 = 2 columns: the bottom/right-only pad and both stride axes, with the
* frame drop and a column of reflected taps. */
Hand h(("3 x 4 x 5 causal, stride 2 down reflect" + sfx).c_str(),
"conv3d_ndhwc", tol);
h.dense(dt, { 3 * 4 * 5, ci }, hfill(960))
.dense(dt, { co, ci, 3, 3, 3 }, hfill(961, 0.3f))
.dense(dt, { co }, hfill(962, 0.5f))
.idx({ 3, 4, 5 })
.none()
.dense(dt, { 8, co }, hfill(963), true)
.pi("M", 8).pi("cin", ci).pi("cout", co).pi("k", 3).pi("kt", 3).ps("dtype", dn)
.pi("stride", 2).pi("stride_t", 2).pi("causal", 1).ps("pad", "down")
.pi("reflect", 1);
hs.push_back(std::move(h));
Hand g(("2 x 2 x 3 causal reflect, a mirror on every edge" + sfx).c_str(),
"conv3d_ndhwc", tol);
g.dense(dt, { 12, ci }, hfill(964))
.dense(dt, { co, ci, 3, 3, 3 }, hfill(965, 0.3f))
.dense(dt, { co }, hfill(966, 0.5f))
.idx({ 2, 2, 3 })
.none()
.dense(dt, { 12, co }, hfill(967), true)
.pi("M", 12).pi("cin", ci).pi("cout", co).pi("k", 3).pi("kt", 3).ps("dtype", dn)
.pi("causal", 1).pi("reflect", 1);
hs.push_back(std::move(g));
/* One frame in, one out: the causal pad's front zeros are the reference's tap
* truncation; the residual is the output itself. */
Hand q(("one frame, causal reflect, residual in place" + sfx).c_str(),
"conv3d_ndhwc", tol);
q.dense(dt, { 4, ci }, hfill(968))
.dense(dt, { co, ci, 3, 3, 3 }, hfill(969, 0.3f))
.dense(dt, { co }, hfill(970, 0.5f))
.idx({ 1, 2, 2 })
.dense(dt, { 4, co }, hfill(971), true)
.alias(4)
.pi("M", 4).pi("cin", ci).pi("cout", co).pi("k", 3).pi("kt", 3).ps("dtype", dn)
.pi("causal", 1).pi("reflect", 1);
hs.push_back(std::move(q));
/* The refusals, held to libref's error codes: a 5-wide kernel with a stride, a
* pad that is neither `same` nor `down`, a reflect whose one-px pad reaches an
* axis of 1, y short of the strided output and a zero stride. */
const auto refusal = [&](const char* what, const std::vector<int64_t>& g3,
int k, const char* pad, int stride, int causal,
int reflect, int64_t yrows) {
Hand z((std::string(what) + sfx).c_str(), "conv3d_ndhwc", tol);
z.dense(dt, { 12, ci }, hfill(972))
.dense(dt, { co, ci, (uint32_t)k, (uint32_t)k, (uint32_t)k }, hfill(973))
.dense(dt, { co }, hfill(974))
.idx(g3)
.none()
.dense(dt, { yrows, co }, zero, true)
.pi("M", yrows).pi("cin", ci).pi("cout", co).pi("k", k).pi("kt", k)
.ps("dtype", dn);
if (stride != 1) z.pi("stride", stride);
if (pad && *pad) z.ps("pad", pad);
if (causal) z.pi("causal", causal);
if (reflect) z.pi("reflect", reflect);
z.refuses(RAD_E_SHAPE);
hs.push_back(std::move(z));
};
refusal("a stride with a 5-wide kernel is refused", { 2, 2, 3 }, 5, nullptr, 2, 0,
0, 12);
refusal("a reflect pad reaching an axis of 1 is refused", { 2, 1, 2 }, 3, nullptr,
1, 1, 1, 4);
refusal("a mirror pad is refused", { 2, 2, 3 }, 3, "mirror", 1, 0, 0, 12);
refusal("y short of the strided output is refused", { 3, 4, 5 }, 3, "down", 2, 1,
1, 7);
refusal("a zero stride is refused", { 2, 2, 3 }, 3, nullptr, 0, 0, 0, 12);
}
}
/* ---- group_norm: stats f32 of exactly groups (2 + 3 1024) values --------------------- */
@@ -3782,6 +3860,26 @@ void audio_cases(std::vector<Hand>& hs) {
.pi("causal", 1).ps("dtype", dn);
hs.push_back(std::move(h));
}
if (dt == (uint32_t)RAD_BF16) {
/* The strided downsample (an encoder's), bf16 only: one sequence, kernel 2 stride,
* pad stride / 2, so 16 input rows give exactly 16 / stride output rows. */
const int64_t cin = 20, cout = 13;
for (const int64_t s : { 2, 4 }) {
const int64_t k = 2 * s, in = 16, out = in / s;
Hand h(("stride " + std::to_string(s) + ", even kernel, one sequence" + sfx)
.c_str(),
"conv1d", norm_tol);
h.dense(dt, { in, cin }, hfill(350 + s))
.dense(dt, { cout, cin, k }, hfill(356, 0.3f))
.idx({ 0, in })
.none()
.dense(dt, { out, cout }, zero, true)
.dense(dt, { cout }, hfill(357, 0.5f))
.pi("M", in).pi("cin", cin).pi("cout", cout).pi("k", k).pi("dil", 1)
.pi("stride", s).pi("pad", s / 2).ps("dtype", dn);
hs.push_back(std::move(h));
}
}
for (const int64_t s : { 5, 3 }) {
/* A codec's odd strides at kernel 2 stride, causal, over sequences of 3, 1 and 5 rows
* from row 1. */
+31
View File
@@ -555,6 +555,37 @@ AVX_KERNEL(pool_rows) {
return RAD_OK;
}
/* ------------------------------------------------------------------ pool_cols */
/* As libref: the mean of every k consecutive columns of each row, summed in f32 and rounded to
* y's dtype, then the multiplier and a second rounding (the unfused pair). pool_rows' dual.
* Parallel over rows. */
AVX_KERNEL(pool_cols) {
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
const RadTensor *X = &a->t[0], *Y = &a->t[1];
const int64_t n = p_int(a, "n", 0), k = p_int(a, "k", 0);
const float mult = p_f32(a, "mult", 1.0f);
if (n <= 0 || k <= 0 || n % k) return RAD_E_SHAPE;
const int64_t M = rows_of(X, n), nw = n / k;
if (M <= 0 || numel(Y) < M * nw) return RAD_E_SHAPE;
const float inv = 1.0f / (float)k;
AVX_PARALLEL_FOR_IF(M * nw * k >= AVX_PAR_MIN)
for (int64_t r = 0; r < M; ++r) {
float* acc = scratch_f32((size_t)nw);
float* sx = scratch_f32_b((size_t)n);
const float* v = in_row(X, rowoff(X, r, n), n, sx);
for (int64_t c = 0; c < nw; ++c) {
float s = 0.0f;
for (int64_t j = 0; j < k; ++j) s += v[c * k + j];
acc[c] = s * inv;
}
roundtrip(Y->dtype, acc, nw, sx);
for (int64_t c = 0; c < nw; ++c) acc[c] *= mult;
out_row(Y, rowoff(Y, r, nw), nw, acc);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ scale_rows */
/* y[m, i] = x[m, i] * act(s[m]), plus add[m, i] when the optional residual is passed.
*
+2 -1
View File
@@ -414,6 +414,7 @@ AVX_KERNEL(timestep_embed) {
const float scale = p_f32(a, "scale", 1000.0f);
const double mp = p_f32(a, "max_period", 10000.0f);
const int round = (int)p_int(a, "round", 0);
const float clamp = p_f32(a, "clamp_min", 0.0f);
if (n <= 0 || (n & 1)) return RAD_E_SHAPE;
const int64_t rows = rows_of(Y, n);
if (rows <= 0 || numel(T) < rows) return RAD_E_SHAPE;
@@ -423,7 +424,7 @@ AVX_KERNEL(timestep_embed) {
float *f = buf, *row = buf + n;
for (int64_t i = 0; i < h; ++i) f[i] = sc_exp(coef * (float)i / (float)h);
for (int64_t m = 0; m < rows; ++m) {
const float tv = ldt(T, offlin(T, m));
const float tv = std::fmax(ldt(T, offlin(T, m)), clamp); /* ref pins are floors */
const float tt = round ? scale * narrow1(RAD_BF16, narrow1(RAD_BF16, tv * scale) / scale)
: scale * tv;
for (int64_t i = 0; i < h; ++i) {
+2 -1
View File
@@ -77,7 +77,8 @@ int avx_par_force(int threads);
X(scatter_rows) X(ngram_ids) \
X(ple_gate) X(ple_conv) X(cast) X(softmax) \
X(scale_rows) X(scale) X(fill) X(act_mul) \
X(seg_mean) X(mul_weight) X(pool_rows) X(relu) \
X(seg_mean) X(mul_weight) X(pool_rows) X(pool_cols) \
X(relu) \
X(clamp) X(conv2d) X(conv1d_dw) X(rel_sinusoid) \
X(seg_sinusoid) X(conv2d_unfold) \
/* ---- quantisation and rotation */ \
+15 -5
View File
@@ -486,7 +486,7 @@ static const RadOperandSpec oRmsModQ[] = { OPD_O("y"), OPD_O("g"), OPD("s"), WGT
static const RadOperandSpec oFlowX0[] = { OPD("v"), OPD("t"), OPD("sigma"), OPD("sigma_next"),
INOUT("x") };
static const RadParamSpec pTimestep[] = { P_INT("M"), P_INT("n"), P_F64("scale"), P_F64("max_period"),
P_INTO("round"), P_STR("dtype") };
P_INTO("round"), P_F64O("clamp_min"), P_STR("dtype") };
static const RadOperandSpec oTimestep[] = { OPD("t"), OUT("y") };
static const RadOperandSpec oGather2[] = { OPD("a"), OPD("b"), OPD("idx"), OUT("y") };
static const RadParamSpec pLane[] = { P_INT("M"), P_INT("n"), P_INT("stride"), P_STR("dtype") };
@@ -554,7 +554,9 @@ static const RadOperandSpec oAttnVsa[] = { OPD("q"), OPD("k"), OPD("v"), OPD("se
/* ---- the latent upscaler (avx_video.cpp), as libref declares it; patch_fold takes
* patch_unfold's parameters and operands ------------------------------------------------------ */
static const RadParamSpec pConv3d[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("k"),
P_INT("kt"), P_STR("dtype") };
P_INT("kt"), P_STR("dtype"), P_INTO("stride"),
P_INTO("stride_t"), P_INTO("causal"), P_STRO("pad"),
P_INTO("reflect") };
static const RadOperandSpec oConv3d[] = { OPD("x"), WGT("w"), WGT("b"), OPD("geom"),
OPD_O("res"), OUT("y") };
static const RadParamSpec pGroupNorm[] = { P_INT("M"), P_INT("n"), P_INT("groups"), P_F64("eps"),
@@ -571,7 +573,7 @@ static const RadOperandSpec oFlowRenoise[] = { OPD("sigma"), OPD("seed"), INOUT(
/* ---- audio generation (avx_audio.cpp), as libref declares it ------------------------------ */
static const RadParamSpec pConv1d[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("k"),
P_INT("dil"), P_STRO("act"), P_STR("dtype"),
P_INTO("causal") };
P_INTO("causal"), P_INTO("stride"), P_INTO("pad") };
static const RadOperandSpec oConv1d[] = { OPD("x"), WGT("w"), OPD("cu_seqlens"), OPD_O("res"),
OUT("y"), WGT_O("b") };
static const RadParamSpec pConvT1d[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("stride"),
@@ -737,6 +739,9 @@ static const RadOpSchema kSchemas[] = {
"local attention with a relative-position term and a softcap (Gemma 4's audio)." },
{ "pool_rows", ARR(pPoolRows), ARR(oUnary),
"y[r] = the mean of x's rows [r*k, r*k + k), rounded to y's dtype, times mult, rounded again." },
{ "pool_cols", ARR(pPoolRows), ARR(oUnary),
"y[m][c] = the mean of x[m]'s columns [c*k, c*k + k), rounded to y's dtype, times mult, rounded "
"again." },
{ "silu_mul", ARR(pMnD), ARR(oGateUp),
"silu-gated product over a fused [M, 2n] gate_up: y = silu(gate) * up." },
{ "gelu_mul", ARR(pMnD), ARR(oGateUp),
@@ -952,8 +957,11 @@ static const RadOpSchema kSchemas[] = {
"and their `sel` tiles, blocked online softmax; the gated coarse term on the output rounded "
"to its dtype." },
{ "conv3d_ndhwc", ARR(pConv3d), ARR(oConv3d),
"a 3-D convolution over voxel rows, `same` zero padding, PyTorch's [cout, cin, kt, k, k] "
"weight, as GEMMs over bands of patch rows; with `res` (possibly y) rd(rd(acc + b) + res)." },
"a 3-D convolution over voxel rows, defaults `same` zero padding, PyTorch's "
"[cout, cin, kt, k, k] weight, as GEMMs over bands of patch rows. `stride`/`stride_t` pad "
"then stride (3x3x3 only), `causal` 1 pads time front-only with kt - 1 zeros, `pad` `down` "
"pads none above/left and one below/right, `reflect` 1 mirrors the spatial padding. With "
"`res` (possibly y) rd(rd(acc + b) + res)." },
{ "group_norm", ARR(pGroupNorm), ARR(oGroupNorm),
"a group norm over all rows, its statistics in f64 over fixed row blocks combined in order, "
"then the optional [scale | shift] row and silu, one rounding; stats[0, 2 groups) the mean "
@@ -1183,6 +1191,8 @@ SIMPLE("avx_seg_mean", "seg_mean", "elem", "mean of each cu_seqlens segment's ro
L(seg_mean)),
SIMPLE("avx_pool_rows", "pool_rows", "elem", "mean of every k consecutive rows, then a multiplier",
DT_FLOAT, L(pool_rows)),
SIMPLE("avx_pool_cols", "pool_cols", "elem", "mean of every k consecutive columns, then a "
"multiplier", DT_FLOAT, L(pool_cols)),
SIMPLE("avx_relu", "relu", "elem", "max(x, 0)", DT_FLOAT, L(relu)),
SIMPLE("avx_clamp", "clamp", "elem", "x clamped to two weight scalars", DT_FLOAT, L(clamp)),
SIMPLE("avx_conv2d", "conv2d", "elem", "segment-wise 2-D convolution, channels innermost",
+52 -20
View File
@@ -443,16 +443,26 @@ AVX_KERNEL(vtile_stitch) {
/* ================================================================== the latent upscaler
* Voxel rows (t, i, j) of a T x H x W volume, channels innermost, the volume in `geom`. */
/* Floor division, Python-style, for the output lengths' PyTorch rule. */
static int64_t idiv_floor(int64_t x, int64_t d) {
const int64_t q = x / d;
return (x % d && (x < 0) != (d < 0)) ? q - 1 : q;
}
/* ------------------------------------------------------------------ conv3d_ndhwc */
/* A 3-D convolution as GEMMs over bands of patch rows, as conv2d_nhwc and conv1d take theirs. The
* weight [cout, cin, kt, k, k] is re-laid once a launch as [cout][dt][kh][kw][cin] (bf16 copies
* when it is bf16, f32 otherwise), so an output voxel's patch row is its kt k k input voxels'
* channel runs back to back, zeros outside the volume: bf16 copies when x is bf16 with dense
* rows, f32 otherwise. A band is one gemm_nt_into into f32 rows, the bias added there; each row
* is then rounded once into y, or with `res` rounded to y's dtype, its residual row added and
* rounded again. A band's residual rows are read before its rows of y are written, row by row,
* so `res` may be y. The patches and the weight live in thread_local vectors that keep their
* high-water size, leaving the GEMM's scratch arenas to it. */
* channel runs back to back, zeros outside the volume (or `reflect`'s mirror): bf16 copies when x
* is bf16 with dense rows, f32 otherwise. A band is one gemm_nt_into into f32 rows, the bias
* added there; each row is then rounded once into y, or with `res` rounded to y's dtype, its
* residual row added and rounded again. A band's residual rows are read before its rows of y are
* written, row by row, so `res` may be y. The patches and the weight live in thread_local vectors
* that keep their high-water size, leaving the GEMM's scratch arenas to it.
*
* The optional `stride`/`stride_t`/`causal`/`pad`/`reflect` are libref's CausalConv3d forms (its
* comment and docs/OPS.md); an output voxel is read from `stride`-spaced, pad-shifted input
* voxels of the (T2, H2, W2) output grid. */
AVX_KERNEL(conv3d_ndhwc) {
if (a->n_t < 6 || !rad_args_have(a, 4) || !rad_arg_in(a, 5)) return RAD_E_INVAL;
const RadTensor *X = &a->t[0], *W = &a->t[1], *B = &a->t[2], *G = &a->t[3];
@@ -461,10 +471,27 @@ AVX_KERNEL(conv3d_ndhwc) {
const int64_t k = p_int(a, "k", 0), kt = p_int(a, "kt", 0);
if (cin <= 0 || cout <= 0 || k <= 0 || kt <= 0 || !(k & 1) || !(kt & 1) || numel(G) < 3)
return RAD_E_SHAPE;
const int64_t sp = p_int(a, "stride", 1), st = p_int(a, "stride_t", 1);
const int64_t causal = p_int(a, "causal", 0), reflect = p_int(a, "reflect", 0);
const char* pads = p_str(a, "pad", "same");
const bool down = pads && !std::strcmp(pads, "down");
if (sp <= 0 || st <= 0 || (causal && causal != 1) || (reflect && reflect != 1) ||
!(!pads || !std::strcmp(pads, "same") || down))
return RAD_E_SHAPE;
const bool gen = sp != 1 || st != 1 || causal || down || reflect;
if (gen && (k != 3 || kt != 3)) return RAD_E_SHAPE;
const int64_t T = at(G, 0), H = at(G, 1), Wd = at(G, 2);
if (T <= 0 || H <= 0 || Wd <= 0) return RAD_E_SHAPE;
const int64_t rows = T * H * Wd, taps = kt * k * k, KK = taps * cin;
if (rows_of(Y, cout) < rows || rows_of(X, cin) < rows || (R && rows_of(R, cout) < rows) ||
const int64_t ft = causal ? kt - 1 : kt / 2, bk = causal ? 0 : kt / 2;
const int64_t pt = down ? 0 : k / 2, pb = down ? 1 : k / 2;
const int64_t pl = down ? 0 : k / 2, pr = down ? 1 : k / 2;
if (reflect && (std::max(pt, pb) >= H || std::max(pl, pr) >= Wd)) return RAD_E_SHAPE;
const int64_t T2 = idiv_floor(T + ft + bk - kt, st) + 1;
const int64_t H2 = idiv_floor(H + pt + pb - k, sp) + 1;
const int64_t W2 = idiv_floor(Wd + pl + pr - k, sp) + 1;
if (T2 <= 0 || H2 <= 0 || W2 <= 0) return RAD_E_SHAPE;
const int64_t rows = T * H * Wd, orows = T2 * H2 * W2, taps = kt * k * k, KK = taps * cin;
if (rows_of(Y, cout) < orows || rows_of(X, cin) < rows || (R && rows_of(R, cout) < orows) ||
numel(W) < cout * KK || numel(B) < cout)
return RAD_E_SHAPE;
static thread_local std::vector<uint8_t> wbuf, pbuf;
@@ -490,22 +517,27 @@ AVX_KERNEL(conv3d_ndhwc) {
const size_t ael = x16 ? 2 : 4;
const int64_t want = std::min<int64_t>((int64_t)1 << 25,
std::max<int64_t>((int64_t)1 << 23, 8 * cout * KK));
const int64_t band = std::max<int64_t>(1, std::min(rows, want / KK));
const int64_t band = std::max<int64_t>(1, std::min(orows, want / KK));
pbuf.resize((size_t)(band * KK) * ael + 64);
ybuf.resize((size_t)(band * cout) + 16);
char* pp = (char*)pbuf.data();
float* yp = ybuf.data();
const int64_t pz = kt / 2, ps = k / 2;
for (int64_t r0 = 0; r0 < rows; r0 += band) {
const int64_t nb = std::min(band, rows - r0);
for (int64_t r0 = 0; r0 < orows; r0 += band) {
const int64_t nb = std::min(band, orows - r0);
AVX_PARALLEL_FOR_IF(nb * KK >= AVX_PAR_MIN)
for (int64_t pr = 0; pr < nb; ++pr) {
const int64_t r = r0 + pr, t = r / (H * Wd), i = (r / Wd) % H, j = r % Wd;
char* d = pp + (size_t)(pr * KK) * ael;
for (int64_t br = 0; br < nb; ++br) {
const int64_t r = r0 + br, t = r / (H2 * W2), i = (r / W2) % H2, j = r % W2;
char* d = pp + (size_t)(br * KK) * ael;
for (int64_t dz = 0; dz < kt; ++dz)
for (int64_t kh = 0; kh < k; ++kh)
for (int64_t kw = 0; kw < k; ++kw, d += (size_t)cin * ael) {
const int64_t tz = t + dz - pz, iy = i + kh - ps, ix = j + kw - ps;
const int64_t tz = t * st + dz - ft;
int64_t iy = i * sp + kh - pt;
int64_t ix = j * sp + kw - pl;
if (reflect) { /* torch's mirror, no repeated edge, then the bounds */
if (iy < 0) iy = -iy; else if (iy >= H) iy = 2 * H - 2 - iy;
if (ix < 0) ix = -ix; else if (ix >= Wd) ix = 2 * Wd - 2 - ix;
}
if (tz < 0 || tz >= T || iy < 0 || iy >= H || ix < 0 || ix >= Wd) {
std::memset(d, 0, (size_t)cin * ael);
continue;
@@ -524,16 +556,16 @@ AVX_KERNEL(conv3d_ndhwc) {
const int st = gemm_nt_into(&pt, &wt, B, &yt, nb, cout, KK);
if (st < 0) return st;
AVX_PARALLEL_FOR_IF(nb * cout >= AVX_PAR_MIN)
for (int64_t pr = 0; pr < nb; ++pr) {
float* row = yp + pr * cout;
for (int64_t br = 0; br < nb; ++br) {
float* row = yp + br * cout;
if (R) {
float* buf = scratch_f32((size_t)(2 * cout + 32));
float *tmp = buf, *rs = buf + cout + 16;
narrow_row(Y->dtype, row, cout, tmp);
const float* rr = in_row(R, rowoff(R, r0 + pr, cout), cout, rs);
const float* rr = in_row(R, rowoff(R, r0 + br, cout), cout, rs);
for (int64_t c = 0; c < cout; ++c) row[c] += rr[c];
}
out_row(Y, rowoff(Y, r0 + pr, cout), cout, row);
out_row(Y, rowoff(Y, r0 + br, cout), cout, row);
}
}
return RAD_OK;