libref, libavx, libr4d: conv1d's stride and cu_div, and vq_encode -- a causal codec encoder's downsampling (the left pad the reach less the stride, every sequence a whole number of strides, the bounds read in samples at every rate) and one step of its residual quantiser, the code of greatest cosine and the residual it leaves (Fish Audio's codec encoding a reference)

This commit is contained in:
zivius committed 2026-10-21 01:00:13 +02:00
1 parent 00f9703892
commit 4e750fed01
15 files changed
+673 -110

No files matched your search

+82 -12
View File
@@ -51,8 +51,13 @@ inline int64_t ldi(const RadTensor* t, int64_t i) {
* them), outside of which the input reads zero (each sequence is padded on its own). w is
* PyTorch's Conv1d weight [cout, cin, k], b [cout], `dil` the dilation and the padding
* dil (k - 1) / 2 on each side (k odd), so a sequence keeps its length; with `causal` 1 all of it,
* dil (k - 1), on the left (any k). `res`, when bound, is added after the bias; then `act` (none,
* tanh, or clamp to [-1, 1], a vocoder's output clamp). f32 accumulation, one rounding. */
* dil (k - 1), on the left (any k). A `stride` s > 1 (causal only, a reach of at least s) keeps
* every s-th output row: the left pad is the reach less s, and a sequence of L rows (every bound a
* whole number of strides) gives L / s, y's and res's rows the input's over s. `cu_div` reads the
* bounds in units that many input rows apart: sequence e is input rows [cu[e] / cu_div,
* cu[e+1] / cu_div), each bound a multiple of cu_div stride. `res`, when bound, is added after the
* bias; then `act` (none, tanh, or clamp to [-1, 1], a vocoder's output clamp). f32
* accumulation, one rounding. */
int ref_conv1d(const RadArgs* a, RadStream) {
if (!have(a, 3)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *w = &a->t[1], *cu = &a->t[2];
@@ -60,29 +65,38 @@ int ref_conv1d(const RadArgs* a, RadStream) {
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), cd = p_int(a, "cu_div", 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)
causal < 0 || causal > 1 || st < 1 || (st > 1 && (!causal || dil * (k - 1) + 1 < st)) ||
cd < 1)
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;
/* A stride takes each sequence of L rows to L / stride, so every bound is a whole number of
* strides (of cu_div units each). */
for (int64_t e = 0; e <= n_seq; ++e)
if (cu_at(cu, e) % (cd * st)) return RAD_E_SHAPE;
const int64_t r0 = cu_at(cu, 0) / cd, r1 = cu_at(cu, n_seq) / cd;
if (r0 < 0 || r1 <= r0 || rows_of(y, cout) < r1 / st || 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;
REF_PAR_FOR((r1 - r0) * cout * cin * k)
for (int64_t r = r0; r < r1; ++r) {
const int64_t e = seq_of(cu, n_seq, r);
const int64_t s0 = cu_at(cu, e), s1 = cu_at(cu, e + 1);
if (res && rows_of(res, cout) < r1 / st) return RAD_E_SHAPE;
/* Causal: the reach is dil (k - 1) + 1 input rows and the left pad that less the stride, so
* output row o of a sequence reads input rows o stride - pad .. o stride + stride - 1. */
const int64_t pad = causal ? dil * (k - 1) + 1 - st : dil * (k - 1) / 2;
REF_PAR_FOR((r1 - r0) / st * cout * cin * k)
for (int64_t r = r0 / st; r < r1 / st; ++r) {
const int64_t e = seq_of(cu, n_seq, r * st * cd);
const int64_t s0 = cu_at(cu, e) / cd, s1 = cu_at(cu, e + 1) / cd;
const int64_t yb = rowoff(y, r, cout), ys = laststride(y);
for (int64_t co = 0; co < cout; ++co) {
float acc = 0.0f;
for (int64_t kk = 0; kk < k; ++kk) {
const int64_t ir = r + kk * dil - pad;
const int64_t ir = r * st + kk * dil - pad;
if (ir < s0 || ir >= s1) continue;
const int64_t xb = rowoff(x, ir, cin), xs = laststride(x);
for (int64_t ci = 0; ci < cin; ++ci)
@@ -418,6 +432,62 @@ int ref_rvq_embed(const RadArgs* a, RadStream) {
return RAD_OK;
}
/* ------------------------------------------------------------------ vq_encode */
/* One step of a residual vector quantiser with factorised, L2-normalised codes (DAC's
* VectorQuantize, as Fish Audio's codec encodes): per row of x [rows, n], e = in_w x + in_b
* (in_w [dim, n]); the code is the row of cb [bins, dim] of greatest cosine with e,
* (e / max(|e|, 1e-12)) . (cb_c / max(|cb_c|, 1e-12)), the lower index on a tie; then
* x -= out_w cb[code] + out_b (out_w [n, dim], the raw codebook row), rounded once into x. f32,
* every sum in index order. A chain of these over a codec's codebooks is its residual quantiser,
* each step quantising what the last left. */
int ref_vq_encode(const RadArgs* a, RadStream) {
if (!have(a, 7)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *iw = &a->t[1], *ib = &a->t[2], *cb = &a->t[3];
const RadTensor *ow = &a->t[4], *ob = &a->t[5], *codes = &a->t[6];
const int64_t n = p_int(a, "n", 0), dim = p_int(a, "dim", 0), bins = p_int(a, "bins", 0);
if (n <= 0 || dim <= 0 || bins <= 0) return RAD_E_SHAPE;
const int64_t rows = rows_of(x, n);
if (rows <= 0 || numel(codes) < rows || numel(iw) < dim * n || numel(ib) < dim ||
numel(cb) < bins * dim || numel(ow) < n * dim || numel(ob) < n)
return RAD_E_SHAPE;
/* The codebook normalised once, as F.normalize divides. */
std::vector<float> cn((size_t)(bins * dim));
for (int64_t c = 0; c < bins; ++c) {
float ss = 0.0f;
for (int64_t j = 0; j < dim; ++j) ss += ldt(cb, c * dim + j) * ldt(cb, c * dim + j);
const float nrm = std::max(std::sqrt(ss), 1e-12f);
for (int64_t j = 0; j < dim; ++j) cn[(size_t)(c * dim + j)] = ldt(cb, c * dim + j) / nrm;
}
REF_PAR_FOR(rows * (dim * n + bins * dim + n * dim))
for (int64_t r = 0; r < rows; ++r) {
const int64_t xb = rowoff(x, r, n), xs = laststride(x);
std::vector<float> e((size_t)dim);
float ss = 0.0f;
for (int64_t j = 0; j < dim; ++j) {
float acc = 0.0f;
for (int64_t d = 0; d < n; ++d) acc += ldt(iw, j * n + d) * ldt(x, xb + d * xs);
e[(size_t)j] = acc + ldt(ib, j);
ss += e[(size_t)j] * e[(size_t)j];
}
const float nrm = std::max(std::sqrt(ss), 1e-12f);
for (int64_t j = 0; j < dim; ++j) e[(size_t)j] /= nrm;
int64_t best = 0;
float bs = -INFINITY;
for (int64_t c = 0; c < bins; ++c) {
float s = 0.0f;
for (int64_t j = 0; j < dim; ++j) s += e[(size_t)j] * cn[(size_t)(c * dim + j)];
if (s > bs) { bs = s; best = c; }
}
st_int(codes->dtype, codes->data, offlin(codes, r), best);
for (int64_t d = 0; d < n; ++d) {
float q = 0.0f;
for (int64_t j = 0; j < dim; ++j) q += ldt(ow, d * dim + j) * ldt(cb, best * dim + j);
stt(x, xb + d * xs, ldt(x, xb + d * xs) - (q + ldt(ob, d)));
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ frame_mix_store */
/* A frame's conditioning row, stored into its lane: m = bf16(bf16(sum_l w_l h_l) * bf16(scale))
* with w = bf16(softmax(bf16(logits))) over the `L` hidden planes of hid [L, rows, n_embd], row
+2
View File
@@ -207,6 +207,7 @@ int ref_snake(const RadArgs*, RadStream);
int ref_snake_aa(const RadArgs*, RadStream);
int ref_cfg_topk_sample(const RadArgs*, RadStream);
int ref_rvq_embed(const RadArgs*, RadStream);
int ref_vq_encode(const RadArgs*, RadStream);
int ref_frame_mix_store(const RadArgs*, RadStream);
int ref_end_status(const RadArgs*, RadStream);
int ref_ras_pick(const RadArgs*, RadStream);
@@ -447,6 +448,7 @@ REF_SHAPE_FN(ref_snake);
REF_SHAPE_FN(ref_snake_aa);
REF_SHAPE_FN(ref_cfg_topk_sample);
REF_SHAPE_FN(ref_rvq_embed);
REF_SHAPE_FN(ref_vq_encode);
REF_SHAPE_FN(ref_frame_mix_store);
REF_SHAPE_FN(ref_end_status);
REF_SHAPE_FN(ref_ras_pick);
+12 -1
View File
@@ -884,7 +884,8 @@ static const RadOperandSpec oBweUp[] = { OPD("x"), OPD("res"), OUT("y") };
/* ---- audio generation (ref_audio.cpp) */
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("cu_div") };
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"),
@@ -908,6 +909,10 @@ static const RadParamSpec pRvqEmbed[] = { P_INT("M"), P_INT("n_embd"), P_INT("n_
P_INT("vocab"), P_INT("off0"), P_F64("scale"),
P_STR("dtype"), P_INTO("round"), P_INTO("clamp") };
static const RadOperandSpec oRvqEmbed[] = { OPD("codes"), WGT("t0"), WGT("t1"), OUT("y") };
static const RadParamSpec pVqEncode[] = { P_INT("M"), P_INT("n"), P_INT("dim"), P_INT("bins"),
P_STR("dtype") };
static const RadOperandSpec oVqEncode[] = { INOUT("x"), WGT("in_w"), WGT("in_b"), WGT("cb"),
WGT("out_w"), WGT("out_b"), OUT("codes") };
static const RadParamSpec pFrameMix[] = { P_INT("M"), P_INT("n_embd"), P_INT("L"), P_INT("stride"),
P_INTO("rep"), P_STR("dtype") };
static const RadOperandSpec oFrameMix[] = { OPD("hid"), WGT("logits"), WGT("scale"), OPD("lane"),
@@ -1769,6 +1774,10 @@ static const RadOpSchema kSchemas[] = {
"a frame's embedding from code-major residual codes [n_codes, rows]: t0[c0 + off0] plus the sum "
"of t1[c_k + (k - 1) vocab], times `scale`, rounded as bf16(bf16(t0 + bf16(sum)) * scale), or "
"with `round` 1 one f32 sum in codebook order times scale, rounded once." },
{ "vq_encode", ARR(pVqEncode), ARR(oVqEncode),
"one residual vector quantiser step: e = in_w x + in_b, the code the row of cb of greatest "
"cosine with e (the lower index on a tie), then x -= out_w cb[code] + out_b; f32, x rounded "
"once." },
{ "frame_mix_store", ARR(pFrameMix), ARR(oFrameMix),
"a frame's conditioning row: the softmax(logits)-weighted sum of hid's L planes times scale, "
"stored at dst[lane * stride + frame - 1] for frame >= 1 and status[lane] >= 0." },
@@ -2345,6 +2354,8 @@ SIMPLE("ref_cfg_topk_sample", "cfg_topk_sample", "sample", "a guided top-k pick
DT_FLOAT, ref_cfg_topk_sample),
SIMPLE("ref_rvq_embed", "rvq_embed", "elem", "a frame's embedding from its residual codes",
DT_FLOAT, ref_rvq_embed),
SIMPLE("ref_vq_encode", "vq_encode", "elem",
"a residual quantiser's step: the nearest code by cosine", DT_FLOAT, ref_vq_encode),
SIMPLE("ref_frame_mix_store", "frame_mix_store", "elem", "a frame's conditioning row into its lane",
DT_FLOAT, ref_frame_mix_store),
SIMPLE("ref_end_status", "end_status", "elem", "a frame's status from its first pick", DT_ANY,
+24 -4
View File
@@ -3112,16 +3112,20 @@ static int64_t two_seqs(int64_t M) { return M >= 4 ? 2 : 1; }
int ref_conv1d_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0), cin = gi(p, n_p, "cin", 0), cout = gi(p, n_p, "cout", 0);
const int64_t k = gi(p, n_p, "k", 0), causal = gi(p, n_p, "causal", 0);
if (M <= 0 || cin <= 0 || cout <= 0 || k <= 0 || (!causal && (k & 1) == 0))
const int64_t st = gi(p, n_p, "stride", 1), dil = gi(p, n_p, "dil", 1);
if (M <= 0 || cin <= 0 || cout <= 0 || k <= 0 || (!causal && (k & 1) == 0) || st < 1 ||
(st > 1 && (!causal || dil * (k - 1) + 1 < st || M % st)) || gi(p, n_p, "cu_div", 1) != 1)
return RAD_E_UNSUPPORTED;
const uint32_t D = act_dt(p, n_p);
const int64_t S = two_seqs(M);
/* A strided convolution is described over one sequence: two would each need a whole number
* of strides. Bounds in coarser units (cu_div) are not drawn; ref_test checks them. */
const int64_t S = st > 1 ? 1 : two_seqs(M);
Opd o;
o.t(D, { M, cin }); /* x */
o.t(D, { cout, cin, k }); /* w */
o.t_idx({ S + 1 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_seqlens */
o.t(D, { M, cout }); /* res */
o.t(D, { M, cout }); /* y */
o.t(D, { M / st, cout }); /* res */
o.t(D, { M / st, cout }); /* y */
o.t(D, { cout }); /* b */
return o.finish("conv1d", operand, out);
}
@@ -3199,6 +3203,22 @@ int ref_rvq_embed_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out
return o.finish("rvq_embed", operand, out);
}
int ref_vq_encode_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 int64_t dim = gi(p, n_p, "dim", 0), bins = gi(p, n_p, "bins", 0);
if (M <= 0 || n <= 0 || dim <= 0 || bins <= 0) return RAD_E_UNSUPPORTED;
const uint32_t F = (uint32_t)RAD_F32;
Opd o;
o.t(act_dt(p, n_p), { M, n }); /* x, INOUT */
o.t(F, { dim, n }); /* in_w */
o.t(F, { dim }); /* in_b */
o.t(F, { bins, dim }); /* cb */
o.t(F, { n, dim }); /* out_w */
o.t(F, { n }); /* out_b */
o.t_idx({ M }, bins, -1, 0); /* codes, OUT */
return o.finish("vq_encode", operand, out);
}
int ref_frame_mix_store_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0), D = gi(p, n_p, "n_embd", 0), L = gi(p, n_p, "L", 0);
const int64_t st = gi(p, n_p, "stride", 0);