Merge upstream main (v1.17.0 -> v2.1.0) into the SYCL port

102 upstream commits. Nine conflicts resolved. Fork side of the merge:
- libxe2: declare the givens_dense_quant schema (upstream 2.0 dropped it
  from libavx and libref; the device libraries now each carry it).
- plain_norm becomes an ABI 42 append to RadBuildCtx; abi layout table
  regenerated, kTableAbi = 42.

Known before the PR: arch_test (MTP lint and pinned graph hashes for
qwen35_fp8, qwen35moe_fp8, qwen4exp with MTP).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
aneinanderandClaude Opus 5.5 committed 2026-11-18 15:06:17 +01:00
commit 4b70a96378
850 files changed
+157819 -58519

No files matched your search

+90 -29
View File
@@ -30,6 +30,7 @@
#include "ref_ops.h"
#include <algorithm>
#include <cstring>
using namespace ref;
@@ -72,6 +73,32 @@ struct KvDyn {
float operator()(const void* p, int64_t i) const { return ld_dt(dt, p, i); }
};
/* The int8 cache (abi/rad_builder.h): a token's row in a head is head_dim K codes, head_dim V
* codes and the two f16 scales, K's then V's. `row` is the row's byte offset in the cache; `half`
* 0 reads K's scale, 1 V's. A value is its code times its scale. */
static inline float kv_i8_scale(const void* cache, int64_t row, int64_t head_dim, int half) {
uint16_t h;
std::memcpy(&h, (const uint8_t*)cache + row + 2 * head_dim + 2 * half, sizeof h);
return f16_to_f32(h);
}
/* One head's K or V into its row of the int8 cache: the scale is the head's absmax / 127 rounded
* to f16 (clamped at 515 so 127 times it stays an f16), the codes round(x / scale) against the
* rounded scale, clamped to +-127. An all-zero head stores scale 0 and codes 0. */
static inline void kv_i8_put(void* cache, int64_t row, int64_t head_dim, int half,
const RadTensor* x, int64_t xb, int64_t x_ds) {
float am = 0.0f;
for (int64_t d = 0; d < head_dim; ++d) am = std::fmax(am, std::fabs(ldt(x, xb + d * x_ds)));
const uint16_t h = f32_to_f16(std::fmin(am / 127.0f, 515.0f));
const float sc = f16_to_f32(h);
int8_t* const c = (int8_t*)cache + row + half * head_dim;
for (int64_t d = 0; d < head_dim; ++d) {
const float r = sc > 0.0f ? std::nearbyint(ldt(x, xb + d * x_ds) / sc) : 0.0f;
c[d] = (int8_t)std::fmin(std::fmax(r, -127.0f), 127.0f);
}
std::memcpy((uint8_t*)cache + row + 2 * head_dim + 2 * half, &h, sizeof h);
}
} /* namespace */
/* ------------------------------------------------------------------ attn_paged */
@@ -125,6 +152,11 @@ static int attn_paged_impl(const RadArgs* a, const RadTensor* sinks, int oi, boo
if (numel(o) < rows * q_heads * head_dim) return RAD_E_SHAPE;
if (kv->rank == 4 && kv->shape[2] != block_size) return RAD_E_SHAPE;
if (kv->rank == 4 && kv->shape[3] < 2 * head_dim) return RAD_E_SHAPE;
/* The int8 cache: dense rows of 2 * head_dim + 4 bytes, each key's scales in its own row, and
* no descales. */
const bool i8 = kv->dtype == RAD_I8;
if (i8 && (kv->rank != 4 || kv->shape[3] != 2 * head_dim + 4 || kv->stride[3] != 1))
return RAD_E_SHAPE;
const int64_t max_blocks = bt->rank >= 2 ? bt->shape[bt->rank - 1] : numel(bt) / n_seq;
const int64_t bt_rs = bt->rank >= 2 ? bt->stride[bt->rank - 2] : max_blocks;
@@ -146,7 +178,8 @@ static int attn_paged_impl(const RadArgs* a, const RadTensor* sinks, int oi, boo
/* Every (query row, head) is one output row, computed as below in a fixed order: per visible
* key, dot = sum over d of q[d] * (k[d] * k_descale), score = dot * scale; then the max over the
* scores in key order; then sum and acc[d] accumulate exp(score - max) and
* exp(...) * (v[d] * v_descale) in key order. The query row is widened once, each score is kept
* exp(...) * (v[d] * v_descale) in key order. At the int8 cache k[d] and v[d] are codes and
* the key's own K and V scales stand where the descales do. The query row is widened once, each score is kept
* for the second pass instead of recomputed, and four keys' dot chains run side by side; none
* of that changes a value. */
REF_PAR_REGION(total * head_dim * 64)
@@ -196,8 +229,12 @@ static int attn_paged_impl(const RadArgs* a, const RadTensor* sinks, int oi, boo
}
const int64_t wpos = tree ? base + tdep : pos;
const float kds = kdes ? ldt(kdes, s * kv_heads + kh) : 1.0f;
const float vds = vdes ? ldt(vdes, s * kv_heads + kh) : 1.0f;
const float kds = i8 ? 1.0f : kdes ? ldt(kdes, s * kv_heads + kh) : 1.0f;
const float vds = i8 ? 1.0f : vdes ? ldt(vdes, s * kv_heads + kh) : 1.0f;
/* A key's K (half 0) or V (half 1) multiplier. */
auto mul_of = [&](int64_t kb, int half) -> float {
return i8 ? kv_i8_scale(kv->data, kb, head_dim, half) : half ? vds : kds;
};
/* Keys past the block table's width are never read. */
const int64_t jend = std::min(ctx, jcap);
@@ -228,21 +265,24 @@ static int attn_paged_impl(const RadArgs* a, const RadTensor* sinks, int oi, boo
for (int64_t j0 = 0; j0 < jend; j0 += 4) {
int64_t kb[4];
float dot[4] = { 0.0f, 0.0f, 0.0f, 0.0f };
float km[4] = { kds, kds, kds, kds };
const int nk = (int)std::min<int64_t>(4, jend - j0);
for (int u = 0; u < 4; ++u) kb[u] = u < nk ? key_at(j0 + u) : -1;
if (i8)
for (int u = 0; u < nk; ++u) if (kb[u] >= 0) km[u] = mul_of(kb[u], 0);
if (kb[0] >= 0 && kb[1] >= 0 && kb[2] >= 0 && kb[3] >= 0) {
for (int64_t d = 0; d < head_dim; ++d) {
const float qd = qf[d];
dot[0] += qd * (kl(kv->data, kb[0] + d * kvv.sd) * kds);
dot[1] += qd * (kl(kv->data, kb[1] + d * kvv.sd) * kds);
dot[2] += qd * (kl(kv->data, kb[2] + d * kvv.sd) * kds);
dot[3] += qd * (kl(kv->data, kb[3] + d * kvv.sd) * kds);
dot[0] += qd * (kl(kv->data, kb[0] + d * kvv.sd) * km[0]);
dot[1] += qd * (kl(kv->data, kb[1] + d * kvv.sd) * km[1]);
dot[2] += qd * (kl(kv->data, kb[2] + d * kvv.sd) * km[2]);
dot[3] += qd * (kl(kv->data, kb[3] + d * kvv.sd) * km[3]);
}
} else {
for (int u = 0; u < nk; ++u) {
if (kb[u] < 0) continue;
for (int64_t d = 0; d < head_dim; ++d)
dot[u] += qf[d] * (kl(kv->data, kb[u] + d * kvv.sd) * kds);
dot[u] += qf[d] * (kl(kv->data, kb[u] + d * kvv.sd) * km[u]);
}
}
for (int u = 0; u < nk; ++u) {
@@ -275,8 +315,9 @@ static int attn_paged_impl(const RadArgs* a, const RadTensor* sinks, int oi, boo
const float w = ref_exp(sc[j] - mx);
sum += w;
const int64_t vb = kb + head_dim * kvv.sd;
const float vm = mul_of(kb, 1);
for (int64_t d = 0; d < head_dim; ++d)
acc[d] += w * (kl(kv->data, vb + d * kvv.sd) * vds);
acc[d] += w * (kl(kv->data, vb + d * kvv.sd) * vm);
}
if (sinks) sum += ref_exp(sk - mx);
const float inv = sum > 0.0f ? 1.0f / sum : 0.0f;
@@ -285,7 +326,7 @@ static int attn_paged_impl(const RadArgs* a, const RadTensor* sinks, int oi, boo
switch (kv->dtype) {
case RAD_F32: unit(KvFix<RAD_F32>{}); break;
case RAD_BF16: unit(KvFix<RAD_BF16>{}); break;
case RAD_F8E4M3: unit(KvFix<RAD_F8E4M3>{}); break;
case RAD_I8: unit(KvFix<RAD_I8>{}); break;
default: unit(KvDyn{ kv->dtype }); break;
}
}
@@ -605,8 +646,12 @@ int ref_kv_store(const RadArgs* a, RadStream) {
const int64_t v_hs = v->rank >= 3 ? v->stride[v->rank - 2] : head_dim * v_ds;
const int64_t v_rs = row_stride(v, kv_heads * head_dim);
const KVView kvv = kv_view(kv, head_dim, block_size, kv_heads);
/* An fp8 cache stores k / k_scale, where the scales are the reader's descales (default 1.0).
* A wider cache stores the value itself. */
/* The int8 cache stores each head's codes and scale (kv_i8_put). An fp8 cache (GLM-5.3's
* latent attention) stores k / k_scale, where the scales are the reader's descales (default
* 1.0). A wider cache stores the value itself. */
const bool i8 = kv->dtype == RAD_I8;
if (i8 && (kv->rank != 4 || kv->shape[3] != 2 * head_dim + 4 || kv->stride[3] != 1))
return RAD_E_SHAPE;
const bool fp8 = kv->dtype == RAD_F8E4M3 || kv->dtype == RAD_F8E5M2;
const float ks = fp8 ? 1.0f / p_f32(a, "k_scale", 1.0f) : 1.0f;
const float vs = fp8 ? 1.0f / p_f32(a, "v_scale", 1.0f) : 1.0f;
@@ -623,6 +668,11 @@ int ref_kv_store(const RadArgs* a, RadStream) {
const int64_t blk = slot / block_size, off = slot % block_size;
for (int64_t h = 0; h < kv_heads; ++h) {
const int64_t cb = blk * kvv.sb + h * kvv.sh + off * kvv.so;
if (i8) {
kv_i8_put(kv->data, cb, head_dim, 0, k, t * k_rs + h * k_hs, k_ds);
kv_i8_put(kv->data, cb, head_dim, 1, v, t * v_rs + h * v_hs, v_ds);
continue;
}
for (int64_t d = 0; d < head_dim; ++d) {
stt(kv, cb + d * kvv.sd, ldt(k, t * k_rs + h * k_hs + d * k_ds) * ks);
stt(kv, cb + (head_dim + d) * kvv.sd, ldt(v, t * v_rs + h * v_hs + d * v_ds) * vs);
@@ -653,19 +703,22 @@ int ref_kv_store_streamed(const RadArgs* a, RadStream) {
if (k->dtype != RAD_BF16 || v->dtype != RAD_BF16) return RAD_E_DTYPE;
if (sm->dtype != RAD_I32 || res->dtype != RAD_I32) return RAD_E_DTYPE;
if (host->dtype != RAD_U8) return RAD_E_DTYPE;
/* E4M3 or bf16: a bf16 group doubles every offset and stores the value itself, as
* kv_store_bf16 does. A packed fp8_v4/k6_v4 group has no streamed row. */
const bool fp8 = kv->dtype == RAD_F8E4M3;
if (!fp8 && kv->dtype != RAD_BF16) return RAD_E_UNSUPPORTED;
/* The int8 cache, bf16 or E4M3: a bf16 group stores the value itself, as kv_store_bf16 does,
* the int8 one each head's codes and scale, an E4M3 one (GLM-5.3's latent attention) the
* value over the reader's descale. */
const bool i8 = kv->dtype == RAD_I8, fp8 = kv->dtype == RAD_F8E4M3;
if (!i8 && !fp8 && kv->dtype != RAD_BF16) return RAD_E_UNSUPPORTED;
const float ks = fp8 ? 1.0f / p_f32(a, "k_scale", 1.0f) : 1.0f;
const float vs = fp8 ? 1.0f / p_f32(a, "v_scale", 1.0f) : 1.0f;
if (kv->rank != 4) return RAD_E_SHAPE;
if (kv->shape[1] != kv_heads || kv->shape[2] != block_size ||
kv->shape[3] != 2 * head_dim) return RAD_E_SHAPE;
const int64_t rowe = i8 ? 2 * head_dim + 4 : 2 * head_dim; /* a token's row in a head */
if (kv->shape[1] != kv_heads || kv->shape[2] != block_size || kv->shape[3] != rowe ||
kv->stride[3] != 1) return RAD_E_SHAPE;
if (host->rank != 2) return RAD_E_SHAPE;
/* Both planes are dense rows of one block of one layer: a padded mirror row would copy over its
* neighbour, and the two copies must share offsets. */
const int64_t EB = fp8 ? 1 : 2;
const int64_t row = kv_heads * block_size * 2 * head_dim * EB;
const int64_t row = kv_heads * block_size * rowe * (kv->dtype == RAD_BF16 ? 2 : 1);
const int64_t slots = kv->shape[0], blocks = host->shape[0];
if (host->shape[1] != row || host->stride[0] * rad_dtype_bytes(host->dtype, 1) != row)
return RAD_E_STRIDE;
@@ -683,10 +736,6 @@ int ref_kv_store_streamed(const RadArgs* a, RadStream) {
const int64_t v_ds = v->rank >= 2 ? v->stride[v->rank - 1] : 1;
const int64_t v_hs = v->rank >= 3 ? v->stride[v->rank - 2] : head_dim * v_ds;
const int64_t v_rs = row_stride(v, kv_heads * head_dim);
/* kv_store_bf16 stores the value itself; only the E4M3 row divides by the reader's descales. */
const float ks = fp8 ? 1.0f / p_f32(a, "k_scale", 1.0f) : 1.0f;
const float vs = fp8 ? 1.0f / p_f32(a, "v_scale", 1.0f) : 1.0f;
/* Everything that can refuse is checked before the first write: a half-written mirror would
* make later copies plausible and wrong. */
const int32_t* const R = (int32_t*)res->data;
@@ -698,9 +747,11 @@ int ref_kv_store_streamed(const RadArgs* a, RadStream) {
if (R[blk] < -1 || R[blk] >= slots) return RAD_E_INVAL;
}
/* The mirror seen as the plane it holds, so both copies round the same. */
RadTensor hkv = *host;
hkv.dtype = kv->dtype;
/* The mirror seen as the plane it holds, so both copies round the same. A view's strides are
* in the plane's elements: the mirror's row pitch is `row` bytes. */
RadTensor hkv = *kv;
hkv.data = host->data;
hkv.shape[0] = blocks;
const KVView kvv = kv_view(kv, head_dim, block_size, kv_heads);
const KVView hv = kv_view(&hkv, head_dim, block_size, kv_heads);
@@ -713,9 +764,19 @@ int ref_kv_store_streamed(const RadArgs* a, RadStream) {
/* A non-resident block is written to the mirror alone; the resolve copies it in whole. */
const int64_t cb = R[blk] >= 0 ? R[blk] * kvv.sb + off * kvv.so : -1;
for (int64_t h = 0; h < kv_heads; ++h) {
const int64_t kx = t * k_rs + h * k_hs, vx = t * v_rs + h * v_hs;
if (i8) {
kv_i8_put(hkv.data, hb + h * hv.sh, head_dim, 0, k, kx, k_ds);
kv_i8_put(hkv.data, hb + h * hv.sh, head_dim, 1, v, vx, v_ds);
if (cb >= 0) {
kv_i8_put(kv->data, cb + h * kvv.sh, head_dim, 0, k, kx, k_ds);
kv_i8_put(kv->data, cb + h * kvv.sh, head_dim, 1, v, vx, v_ds);
}
continue;
}
for (int64_t d = 0; d < head_dim; ++d) {
const float xk = ldt(k, t * k_rs + h * k_hs + d * k_ds) * ks;
const float xv = ldt(v, t * v_rs + h * v_hs + d * v_ds) * vs;
const float xk = ldt(k, kx + d * k_ds) * ks;
const float xv = ldt(v, vx + d * v_ds) * vs;
stt(&hkv, hb + h * hv.sh + d * hv.sd, xk);
stt(&hkv, hb + h * hv.sh + (head_dim + d) * hv.sd, xv);
if (cb >= 0) {
+44
View File
@@ -46,6 +46,50 @@ inline int64_t ldi(const RadTensor* t, int64_t i) {
} /* namespace */
/* ------------------------------------------------------------------ conv1d */
int ref_elu(const RadArgs* a, RadStream) {
if (!have(a, 2)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *y = &a->t[1];
if (numel(y) <= 0 || numel(x) < numel(y)) return RAD_E_SHAPE;
REF_PAR_FOR(numel(y))
for (int64_t i = 0; i < numel(y); ++i) {
const float v = ldt(x, offlin(x, i));
stt(y, offlin(y, i), v >= 0 ? v : std::expm1(v));
}
return RAD_OK;
}
/* Mimi's Euclidean RVQ, not the cosine quantiser used by drama-3. Projections belong to
* the enclosing split quantiser; each step subtracts its centroid in the projected space. */
int ref_vq_euclidean(const RadArgs* a, RadStream) {
if (!have(a, 3)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *cb = &a->t[1], *codes = &a->t[2];
const int64_t n = p_int(a, "n", 0), bins = p_int(a, "bins", 0);
if (n <= 0 || bins <= 0 || numel(cb) != bins * n || codes->dtype != RAD_I32)
return RAD_E_SHAPE;
const int64_t rows = rows_of(x, n);
if (rows < 1 || numel(codes) < rows) return RAD_E_SHAPE;
REF_PAR_FOR(rows * bins * n)
for (int64_t r = 0; r < rows; ++r) {
float best = INFINITY;
int64_t pick = 0;
for (int64_t k = 0; k < bins; ++k) {
float d = 0;
for (int64_t j = 0; j < n; ++j) {
const float delta = ldt(x, rowoff(x, r, n) + j * laststride(x)) -
ldt(cb, rowoff(cb, k, n) + j * laststride(cb));
d += delta * delta;
}
if (d < best) { best = d; pick = k; }
}
st_int(codes->dtype, codes->data, offlin(codes, r), pick);
for (int64_t j = 0; j < n; ++j) {
const int64_t at = rowoff(x, r, n) + j * laststride(x);
stt(x, at, ldt(x, at) - ldt(cb, rowoff(cb, pick, n) + j * laststride(cb)));
}
}
return RAD_OK;
}
/* A 1-D convolution over sequences of rows, channels innermost: x [rows, cin], y [rows, cout],
* `cu_seqlens` bounding each sequence (row indices of both operands, as every sequenced op reads
* them), outside of which the input reads zero (each sequence is padded on its own). w is
+172
View File
@@ -316,6 +316,178 @@ int ref_grid_embed_cpe(const RadArgs* a, RadStream) {
return RAD_OK;
}
/* ------------------------------------------------------------------ grid_embed_pad */
/* The same learned table and operands as grid_embed's, resampled in the half-pixel-centre form
* (align_corners=False) with grid_sample's padding_mode="zeros": taps whose UNCLAMPED index falls
* outside [0, side-1) contribute nothing rather than reading the edge. Per axis,
* src = (i + 0.5) * side / size - 0.5; floor(src) and floor(src) + 1, each carrying the linear hat
* weight (1 - |src - tap|)+ masked to zero off the table. For grids no larger than the table the
* mask never fires and the op agrees with grid_embed_aa's centre positions (not grid_embed's
* corners-aligned ones); it differs from them only when a grid upsamples past the table, which is
* the common case for Muse. The four products are summed in f32 in grid_embed's order (top-left,
* top-right, bottom-left, bottom-right), rounded to x's dtype, then added and rounded again. */
int ref_grid_embed_pad(const RadArgs* a, RadStream) {
if (!have(a, 3)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *tab = &a->t[1], *crd = &a->t[2];
const int64_t n = p_int(a, "n", tab->rank ? tab->shape[tab->rank - 1] : 0);
const int64_t side = p_int(a, "side", 0);
if (n <= 0 || side <= 0 || numel(tab) < side * side * n) return RAD_E_SHAPE;
const int64_t rows = rows_of(x, n);
if (rows <= 0 || crd->rank != 2 || crd->shape[0] < 4 || crd->shape[1] < rows)
return RAD_E_SHAPE;
const int64_t cs = crd->stride[0], ms = crd->stride[1];
const int64_t ts = laststride(tab);
REF_PAR_FOR(rows * n * 4)
for (int64_t r = 0; r < rows; ++r) {
const int64_t gr = ld_int(crd->dtype, crd->data, 0 * cs + r * ms);
const int64_t gc = ld_int(crd->dtype, crd->data, 1 * cs + r * ms);
const int64_t gh = ld_int(crd->dtype, crd->data, 2 * cs + r * ms);
const int64_t gw = ld_int(crd->dtype, crd->data, 3 * cs + r * ms);
int64_t th[2], tw[2];
float wh[2], ww[2];
auto axis = [&](int64_t idx, int64_t size, int64_t* t, float* w) {
if (size < 1) size = 1;
const float src = (float)side / (float)size * ((float)idx + 0.5f) - 0.5f;
const float fl = std::floor(src);
for (int k = 0; k < 2; ++k) {
const int64_t raw = (int64_t)fl + k;
t[k] = raw < 0 ? 0 : (raw > side - 1 ? side - 1 : raw);
const float d = std::fabs(src - fl - (float)k);
const float u = 1.0f - d > 0.0f ? 1.0f - d : 0.0f;
w[k] = raw >= 0 && raw <= side - 1 ? u : 0.0f;
}
};
axis(gr, gh, th, wh);
axis(gc, gw, tw, ww);
const int64_t xb = rowoff(x, r, n), xs = laststride(x);
for (int64_t i = 0; i < n; ++i) {
float acc = 0.0f;
for (int ki = 0; ki < 2; ++ki)
for (int kj = 0; kj < 2; ++kj)
acc += ldt(tab, rowoff(tab, th[ki] * side + tw[kj], n) + i * ts) *
(wh[ki] * ww[kj]);
const float pe = round_dt(x->dtype, acc);
stt(x, xb + i * xs, ldt(x, xb + i * xs) + pe);
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ window_order */
/* The window-attention permutation of one encoder pass, computed entirely from the on-device
* coordinate planes: HF's get_vision_window_index as a gather-index computation. Windows partition
* each segment (one segment == one frame): window row = row/window, window col = col/window,
* windows scanned window-row-major and ragged at the segment's right and bottom edges; within a
* window patches keep raster order, and windows never span segments.
*
* `crd` is [4, P] i32 -- row, column, segment height, segment width per patch -- and `cu` is [S+1]
* i32, the per-frame segment boundaries in patches. Outputs, all i32: `idx` [P], slot -> source
* patch (the gather index); `inv` [P], source patch -> slot; `pos` [2, P], each slot's rope
* positions (col + 1, row + 1) -- Muse's rotary wants the axes swapped and offset by one relative
* to the coordinate planes (HF's position_ids.flip(-1) + 1) -- laid out component-major like the
* planes; and `cuw` [P+1], the cumulative window boundaries in the permuted order, n_windows + 1
* entries used, the rest holding the total. `M` is the patches this pass covers, 1..P: slots past
* M are the identity, so a caller may reuse buffers sized for a bigger pass. `window` <= 0 makes
* the permutation the identity and cuw = cu. */
int ref_window_order(const RadArgs* a, RadStream) {
if (!have(a, 6)) return RAD_E_INVAL;
const RadTensor *crd = &a->t[0], *cu = &a->t[1];
RadTensor *idx = const_cast<RadTensor*>(&a->t[2]), *inv = const_cast<RadTensor*>(&a->t[3]),
*pos = const_cast<RadTensor*>(&a->t[4]), *cuw = const_cast<RadTensor*>(&a->t[5]);
const int64_t M = p_int(a, "M", 0);
const int64_t win = p_int(a, "window", 0);
if (M <= 0 || crd->rank != 2 || crd->shape[0] < 4 || crd->shape[1] < M) return RAD_E_SHAPE;
if (numel(cu) < 2 || numel(idx) < M || numel(inv) < M || numel(pos) < 2 * M ||
numel(cuw) < M + 1)
return RAD_E_SHAPE;
const int64_t P = crd->shape[1];
const int64_t cs = crd->stride[0], ms = crd->stride[1];
auto gx = [&](int c, int64_t p) {
return ld_int(crd->dtype, crd->data, (int64_t)c * cs + p * ms);
};
/* The identity: every slot its own patch, cuw = cu, the tail padded with the last boundary. */
auto identity = [&]() {
for (int64_t p = 0; p < P; ++p) {
st_int(idx->dtype, idx->data, p, p);
st_int(inv->dtype, inv->data, p, p);
if (p < M) {
st_int(pos->dtype, pos->data, p, gx(1, p) + 1);
st_int(pos->dtype, pos->data, P + p, gx(0, p) + 1);
} else {
st_int(pos->dtype, pos->data, p, 1);
st_int(pos->dtype, pos->data, P + p, 1);
}
}
int64_t last = 0;
const int64_t k = numel(cu) < M + 1 ? numel(cu) : M + 1;
for (int64_t i = 0; i < k; ++i) {
last = ld_int(cu->dtype, cu->data, i);
st_int(cuw->dtype, cuw->data, i, last);
}
for (int64_t i = k; i < M + 1; ++i) st_int(cuw->dtype, cuw->data, i, last);
};
if (win <= 0) {
identity();
return RAD_OK;
}
/* Slot arithmetic: patch p's segment, its window and its rank in the window follow from the
* coordinates alone, so a first walk writes the window boundaries and a second scatters. */
std::vector<int64_t> seg(M), seg_nw, seg_first_win;
std::vector<int64_t> wbase((size_t)M); /* each window's base slot; windows <= M */
int64_t s = 0, slot = 0, nwin = 0;
const int64_t S = numel(cu) - 1;
while (s < S) {
const int64_t start = ld_int(cu->dtype, cu->data, s);
if (start >= M) break;
int64_t end = ld_int(cu->dtype, cu->data, s + 1);
if (end > M) end = M;
const int64_t gh = start < end ? gx(2, start) : 1;
const int64_t gw = start < end ? gx(3, start) : 1;
const int64_t nh = (gh + win - 1) / win, nw = (gw + win - 1) / win;
seg_first_win.push_back(nwin);
seg_nw.push_back(nw);
for (int64_t p = start; p < end; ++p) seg[p] = (int64_t)seg_first_win.size() - 1;
for (int64_t wr = 0; wr < nh; ++wr)
for (int64_t wc = 0; wc < nw; ++wc) {
const int64_t rows_in = std::min(win, gh - wr * win);
const int64_t cols_in = std::min(win, gw - wc * win);
st_int(cuw->dtype, cuw->data, nwin, slot);
wbase[(size_t)nwin] = slot;
++nwin;
slot += rows_in * cols_in;
}
++s;
}
st_int(cuw->dtype, cuw->data, nwin, slot);
for (int64_t i = nwin + 1; i < M + 1; ++i) st_int(cuw->dtype, cuw->data, i, slot);
for (int64_t p = 0; p < P; ++p) {
if (p >= M) {
st_int(idx->dtype, idx->data, p, p);
st_int(inv->dtype, inv->data, p, p);
st_int(pos->dtype, pos->data, p, 1);
st_int(pos->dtype, pos->data, P + p, 1);
continue;
}
const int64_t r = gx(0, p), c = gx(1, p);
const int64_t gw = gx(3, p);
int64_t wr = r / win, wc = c / win;
if (wr < 0) wr = 0;
if (wc < 0) wc = 0;
const int64_t cols_in = std::min(win, gw - wc * win);
const int64_t wid = seg_first_win[(size_t)seg[p]] + wr * seg_nw[(size_t)seg[p]] + wc;
const int64_t at = wbase[(size_t)wid] + (r - wr * win) * cols_in + (c - wc * win);
st_int(idx->dtype, idx->data, at, p);
st_int(inv->dtype, inv->data, p, at);
st_int(pos->dtype, pos->data, at, c + 1);
st_int(pos->dtype, pos->data, P + at, r + 1);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ add / mul */
/* Elementwise over the output's extent. `b` may be a single row of exactly `n` elements, which
* broadcasts along rows (a bias add); nothing else broadcasts, so a shape bug cannot pass as a
+20
View File
@@ -535,6 +535,26 @@ static int gemm_ntq_impl(const RadArgs* a, bool bias_operand) {
if (zg)
return gemm_zp(*zg, A, as_, B, bs_, t_in(a, 5), Y, M, N, K, p_int(a, "group", 0), pb1,
pb2);
/* A scale in two levels, joined (ref_layout_gemm_q): an integer per (row, group) under a float
* a row. Their product in f32 is the scale the loop below reads. */
std::vector<float> two_level;
RadTensor bs_two;
if (is_joined(bs_)) {
const JPlane s1 = jplane(bs_, "scale"), s2 = jplane(bs_, "scale.1");
if (!s1 || !s2 || s1.dt != RAD_U8 || !float_scale_dt(s2.dt)) return RAD_E_DTYPE;
if (s1.rows != N || s1.cols <= 0 || s2.rows != N || s2.cols != 1) return RAD_E_SHAPE;
two_level.resize((size_t)(N * s1.cols));
for (int64_t n = 0; n < N; ++n)
for (int64_t g = 0; g < s1.cols; ++g)
two_level[(size_t)(n * s1.cols + g)] = s1.at(n, g) * s2.at(n, 0);
std::memset(&bs_two, 0, sizeof(bs_two));
bs_two.data = two_level.data();
bs_two.dtype = RAD_F32;
bs_two.rank = 2;
bs_two.shape[0] = N; bs_two.shape[1] = s1.cols;
bs_two.stride[0] = s1.cols; bs_two.stride[1] = 1;
bs_ = &bs_two;
}
if (pb1 > 0 || pb2 > 0) {
if (bias_operand || B->dtype != RAD_FP4E2M1 || A->rank < 2) return RAD_E_UNSUPPORTED;
const int64_t e1 = pb1 > 0 ? std::min<int64_t>(pb1, N) : N;
-96
View File
@@ -107,61 +107,6 @@ int ref_gate_add(const RadArgs* a, RadStream) {
return RAD_OK;
}
/* ------------------------------------------------------------------ ln_mod_quant_fp8 */
/* gate_add (with `gated` 1), ln_mod and quant_act_fp8 over each row, each step's output rounded
* to its stored dtype as the three ops would store it: the residual to x's, the norm to bf16, and
* the codes as ref_quant_act_fp8 writes them over that bf16 row. */
int ref_ln_mod_quant_fp8(const RadArgs* a, RadStream) {
if (a->n_t < 8) return RAD_E_INVAL;
const RadTensor *y = t_in(a, 0), *g = t_in(a, 1), *s = &a->t[2], *cu = &a->t[3];
const RadTensor *x = &a->t[4], *q = &a->t[5], *sc = &a->t[6], *z = t_in(a, 7);
const int64_t n = p_int(a, "n", 0), grp = p_int(a, "group", 0);
const bool gated = p_int(a, "gated", 0) != 0;
const float eps = p_f32(a, "eps", 1e-6f);
if (n <= 0 || grp <= 0 || n % grp || (gated && (!y || !g))) return RAD_E_SHAPE;
const int64_t rows = rows_of(q, n), n_seq = numel(cu) - 1, ngrp = n / grp;
if (rows <= 0 || n_seq <= 0 || rows_of(x, n) < rows || numel(sc) < rows * ngrp)
return RAD_E_SHAPE;
const int64_t s_rs = row_stride(s, n), s_cs = laststride(s);
const int64_t g_rs = gated ? row_stride(g, n) : 0, g_cs = gated ? laststride(g) : 0;
REF_PAR_FOR(rows * n)
for (int64_t r = 0; r < rows; ++r) {
const int64_t e = seq_of(cu, n_seq, r);
const int64_t xb = rowoff(x, r, n), xs = laststride(x);
std::vector<float> v((size_t)n), o((size_t)n);
for (int64_t i = 0; i < n; ++i) {
float xv = ldt(x, xb + i * xs);
if (gated) {
const float t = round_dt(x->dtype, ref_tanh(ldt(g, e * g_rs + i * g_cs)));
const float d = ldt(y, rowoff(y, r, n) + i * laststride(y));
xv = round_dt(x->dtype, xv + round_dt(x->dtype, t * d));
stt(x, xb + i * xs, xv);
}
v[(size_t)i] = xv;
}
float sum = 0.0f;
for (int64_t i = 0; i < n; ++i) sum += v[(size_t)i];
const float mean = sum / (float)n;
float var = 0.0f;
for (int64_t i = 0; i < n; ++i) { const float d = v[(size_t)i] - mean; var += d * d; }
const float rs = 1.0f / std::sqrt(var / (float)n + eps);
for (int64_t i = 0; i < n; ++i) {
const float ln = round_dt(RAD_BF16, (v[(size_t)i] - mean) * rs);
const float sm = round_dt(RAD_BF16, 1.0f + ldt(s, e * s_rs + i * s_cs));
o[(size_t)i] = round_dt(RAD_BF16, ln * sm);
if (z) stt(z, rowoff(z, r, n) + i * laststride(z), o[(size_t)i]);
}
const int64_t qb = rowoff(q, r, n), qs = laststride(q);
for (int64_t gi = 0; gi < ngrp; ++gi) {
const float* og = o.data() + gi * grp;
const float scl = q8_group([&](int64_t i) { return og[i]; }, grp, 448.0f, q,
qb + gi * grp * qs, qs);
stt(sc, rowoff(sc, r, ngrp) + gi * laststride(sc), scl);
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ rms_mod / rms_mod_quant_fp8 */
/* The checks both forms share: `s` holds [shift | scale] in each of its n_seq rows, `g` a gate
* row per sequence when `gated`, and every row operand at least `rows` rows. With `mapped`, the
@@ -265,47 +210,6 @@ int ref_rms_mod(const RadArgs* a, RadStream) {
return RAD_OK;
}
/* rms_mod in front of a quantised linear: the norm chain in bf16, then the codes and scales as
* ref_quant_act_fp8 writes them over that bf16 row (ln_mod_quant_fp8's rule), z written when
* bound. */
int ref_rms_mod_quant_fp8(const RadArgs* a, RadStream) {
if (a->n_t < 9) return RAD_E_INVAL;
const RadTensor *y = t_in(a, 0), *g = t_in(a, 1), *s = &a->t[2], *w = t_in(a, 3);
const RadTensor *cu = &a->t[4], *x = &a->t[5], *q = &a->t[6], *sc = &a->t[7], *z = t_in(a, 8);
const RadTensor *cm = t_in(a, 9);
const int64_t n = p_int(a, "n", 0), grp = p_int(a, "group", 0);
const bool gated = p_int(a, "gated", 0) != 0;
const float eps = p_f32(a, "eps", 1e-6f);
const float wadd = p_f32(a, "wadd", 0.0f);
const bool once = p_int(a, "norm_once", 0) != 0;
const char* nk = p_str(a, "norm", "rms");
const bool layer = std::strcmp(nk, "layer") == 0, none = std::strcmp(nk, "none") == 0;
if (!layer && !none && std::strcmp(nk, "rms") != 0) return RAD_E_INVAL;
if (none && t_in(a, 3)) return RAD_E_INVAL;
if (n <= 0 || grp <= 0 || n % grp || (gated && (!y || !g))) return RAD_E_SHAPE;
const int64_t rows = rows_of(q, n), n_seq = numel(cu) - 1, ngrp = n / grp;
if (cm && (cm->dtype != RAD_I32 || numel(cm) < n_seq)) return RAD_E_SHAPE;
RAD_REF_TRY(rms_mod_check(y, g, s, w, x, n, n_seq, rows, gated, cm != nullptr));
if (numel(sc) < rows * ngrp || (z && rows_of(z, n) < rows)) return RAD_E_SHAPE;
REF_PAR_FOR(rows * n)
for (int64_t r = 0; r < rows; ++r) {
std::vector<float> o((size_t)n);
int64_t e = seq_of(cu, n_seq, r);
if (cm) e = (int64_t)ldt(cm, e);
rms_mod_row(y, g, s, w, x, r, e, n, eps, gated, RAD_BF16, o.data(), wadd, once, layer, none);
const int64_t zb = z ? rowoff(z, r, n) : 0, zs = z ? laststride(z) : 0;
for (int64_t i = 0; z && i < n; ++i) stt(z, zb + i * zs, o[(size_t)i]);
const int64_t qb = rowoff(q, r, n), qs = laststride(q);
for (int64_t gi = 0; gi < ngrp; ++gi) {
const float* og = o.data() + gi * grp;
const float scl = q8_group([&](int64_t i) { return og[i]; }, grp, 448.0f, q,
qb + gi * grp * qs, qs);
stt(sc, rowoff(sc, r, ngrp) + gi * laststride(sc), scl);
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ timestep_embed */
/* y[m] = [cos(t' f_0) .. cos(t' f_{h-1}) | sin(t' f_0) .. sin(t' f_{h-1})], h = n / 2, where
* f_i = exp(-ln(max_period) * i / h) in f32 and t' = scale * t -- or, with `round` 1, the value
+8 -5
View File
@@ -122,8 +122,8 @@ int ref_hc_read(const RadArgs* a, RadStream) {
if (numel(q) < rows * n || !s || !s->data || numel(s) < rows * ngrp) return RAD_E_SHAPE;
}
/* The rotated form rotates each scale group whole, so the group must be a power of two that
* tiles the row; no weight block was rotated across padding. The result equals
* had_quant_act_fp8 of the stored `x`. */
* tiles the row; no weight block was rotated across padding. The result is the
* rotated quantiser's (had_quant_act_i8g's at int8 codes) of the stored `x`. */
int64_t rg = 0;
if (rq) {
rg = p_int(a, "group", 0);
@@ -198,12 +198,14 @@ int ref_hc_read(const RadArgs* a, RadStream) {
for (int64_t gi = 0; gi < ngrp; ++gi) {
const int64_t k0 = gi * g, k1 = (k0 + g < n) ? k0 + g : n;
const float sc = q8_group([&](int64_t i) { return ldt(x, xb + (k0 + i) * xs); },
k1 - k0, 448.0f, q, qb + k0 * qs, qs);
k1 - k0, q->dtype == RAD_I8 ? 127.0f : 448.0f, q,
qb + k0 * qs, qs);
stt(s, rowoff(s, r, ngrp) + gi * laststride(s), sc);
}
}
/* ---- optional rotated fp8 form of x, from the same stored values. */
/* ---- optional rotated form of x, from the same stored values: E4M3 codes, or int8
* (had_quant_act_i8g's) where the buffer is. */
if (rq) {
float buf[REF_HAD_MAX];
const int64_t qb = rowoff(rq, r, n), qs = laststride(rq), rgrp = n / rg;
@@ -211,7 +213,8 @@ int ref_hc_read(const RadArgs* a, RadStream) {
const int64_t k0 = gi * rg;
for (int64_t i = 0; i < rg; ++i) buf[i] = ldt(x, xb + (k0 + i) * xs);
fwht(buf, rg);
const float sc = q8_group([&](int64_t i) { return buf[i]; }, rg, 448.0f, rq,
const float sc = q8_group([&](int64_t i) { return buf[i]; }, rg,
rq->dtype == RAD_I8 ? 127.0f : 448.0f, rq,
qb + k0 * qs, qs);
stt(rs, rowoff(rs, r, rgrp) + gi * laststride(rs), sc);
}
+18 -6
View File
@@ -295,6 +295,10 @@ static CbForm cb_form(const RadParam* p, int n_p) {
if (s && !std::strcmp(s, "w4nl64a8h")) return CbForm{ 4, 64, RAD_F8E4M3, true };
if (s && !std::strcmp(s, "w4nl32a8h")) return CbForm{ 4, 32, RAD_F8E4M3, true };
if (s && !std::strcmp(s, "w5nl64a8h")) return CbForm{ 5, 64, RAD_F8E4M3, true };
if (s && !std::strcmp(s, "w6nl64a8h")) return CbForm{ 6, 64, RAD_F8E4M3, true };
/* The same stored experts under their names against an int8 activation. */
if (s && !std::strcmp(s, "w4nl64a8i8h")) return CbForm{ 4, 64, RAD_F8E4M3, true };
if (s && !std::strcmp(s, "w4nl32a8i8h")) return CbForm{ 4, 32, RAD_F8E4M3, true };
return CbForm{ 0, 0, 0, false };
}
@@ -315,7 +319,7 @@ static int cb_check(const RadParam* p, int n_p, int operand, const RadEncoding*
const RadEncPlane& b = enc->plane[sel[1]];
if (codes)
return !std::strcmp(a.role, "codes") && a.kind == RAD_PLANE_TILED &&
a.dtype == (f.bits == 5 ? (uint32_t)RAD_U5 : (uint32_t)RAD_U4) &&
a.dtype == (f.bits == 6 ? (uint32_t)RAD_U6 : f.bits == 5 ? (uint32_t)RAD_U5 : (uint32_t)RAD_U4) &&
a.block[0] == 1 && a.block[1] == 1 && !std::strcmp(b.role, "table") &&
b.kind == RAD_PLANE_TABLE && b.dtype == RAD_F32 && b.extent[0] == 1 &&
b.extent[1] == ((int64_t)1 << f.bits)
@@ -365,7 +369,7 @@ static const RadPlanesHeader* cb_joined(const RadTensor& t) {
* `row_bytes` apart, the layout rad_planes.h keeps. */
struct CbTensor {
RadTensor t; /* `data`: the codes plane, from the tile's first weight row */
float tab[32];
float tab[64];
int64_t cols = 0, row_bytes = 0;
int bits = 0;
};
@@ -382,13 +386,13 @@ struct LdCb {
* codes not covering [n, k]. A u4 or u5 entry is always joined: only its table says what a code
* means. */
static int cb_codes(const RadTensor& w, int64_t n, int64_t k, CbTensor* out) {
if (w.dtype != RAD_U4 && w.dtype != RAD_U5) return 0;
if (w.dtype != RAD_U4 && w.dtype != RAD_U5 && w.dtype != RAD_U6) return 0;
const RadPlanesHeader* h = rad_planes_header(w.data);
const RadPlanesEntry *ec = nullptr, *et = nullptr;
const void* codes = h ? rad_planes_find(w.data, "codes", &ec) : nullptr;
const void* tab = h ? rad_planes_find(w.data, "table", &et) : nullptr;
if (!codes || !tab || h->n_planes != 2) return RAD_E_DTYPE;
const int bits = ec->dtype == RAD_U4 ? 4 : ec->dtype == RAD_U5 ? 5 : 0;
const int bits = ec->dtype == RAD_U4 ? 4 : ec->dtype == RAD_U5 ? 5 : ec->dtype == RAD_U6 ? 6 : 0;
if (!bits || ec->kind != RAD_PLANE_TILED || ec->block[0] != 1 || ec->block[1] != 1 ||
et->kind != RAD_PLANE_TABLE || et->dtype != RAD_F32 ||
et->rows * et->cols != ((int64_t)1 << bits))
@@ -519,7 +523,9 @@ static int moe_gemm_impl(const RadArgs* a, bool quant, int ncls = 2) {
const Mat ma = as_mat(A, K);
const Scales SA = make_scales(as_, AR, K, false);
const int64_t gp = p_int(a, "group", 0);
/* The activation's scales are per `a_group` of K where the caller states one (an int8
* activation at one scale per 256 against experts scaled per 128), else per `group`. */
const int64_t gp = p_int(a, "a_group", p_int(a, "group", 0));
if (quant && gp > 0 && SA.p && SA.group != gp) return RAD_E_SHAPE;
const int64_t y_rs = row_stride(Y, N);
@@ -711,8 +717,14 @@ static int moe_gemm_impl(const RadArgs* a, bool quant, int ncls = 2) {
int ref_moe_gemm(const RadArgs* a, RadStream) { return moe_gemm_impl(a, false); }
int ref_moe_gemm_q(const RadArgs* a, RadStream s) {
const char* dt = p_str(a, "dtype", "");
if (dt && std::strcmp(dt, "w4a8") == 0) return ref_moe_gemm_w4a8(a, s);
if (dt && std::strcmp(dt, "w4a4") == 0) return ref_moe_gemm_w4a4(a, s);
/* w4a8 over bf16 scales has its own body, summed in the order libr3d's kernel sums. Any other
* four-bit expert (f16 scales, a code plane with a zero point) is a form that body does not
* read, and the general one does. */
if (dt && std::strcmp(dt, "w4a8") == 0) {
const int rc = ref_moe_gemm_w4a8(a, s);
if (rc != RAD_E_DTYPE) return rc;
}
return moe_gemm_impl(a, true);
}
int ref_moe_gemm_q_mod4(const RadArgs* a, RadStream) { return moe_gemm_impl(a, true, 4); }
+8 -10
View File
@@ -72,8 +72,10 @@ int ref_hc_project (const RadArgs*, RadStream);
int ref_mtp_enter (const RadArgs*, RadStream);
int ref_layernorm (const RadArgs*, RadStream);
int ref_grid_embed (const RadArgs*, RadStream);
int ref_grid_embed_pad (const RadArgs*, RadStream);
int ref_grid_embed_aa (const RadArgs*, RadStream);
int ref_grid_embed_cpe (const RadArgs*, RadStream);
int ref_window_order (const RadArgs*, RadStream);
int ref_lili_cand (const RadArgs*, RadStream);
int ref_lili_attn (const RadArgs*, RadStream);
int ref_lili_factor (const RadArgs*, RadStream);
@@ -131,10 +133,7 @@ int ref_quant_act_i8g (const RadArgs*, RadStream);
int ref_had_quant_act_i8 (const RadArgs*, RadStream);
int ref_quant_act_fp8 (const RadArgs*, RadStream);
int ref_quant_cols_fp8 (const RadArgs*, RadStream);
int ref_had_quant_act_fp8 (const RadArgs*, RadStream);
int ref_had_quant_act_i8g (const RadArgs*, RadStream);
int ref_givens_dense_quant(const RadArgs*, RadStream);
int ref_givens_rotate(const RadArgs*, RadStream);
int ref_rmsnorm_quant_fp8 (const RadArgs*, RadStream);
int ref_gated_quant_fp8 (const RadArgs*, RadStream);
int ref_gemm_nt_q_gated (const RadArgs*, RadStream);
@@ -186,7 +185,6 @@ int ref_rope_table (const RadArgs*, RadStream);
int ref_qk_norm_rope (const RadArgs*, RadStream);
/* image generation (ref_gen.cpp) */
int ref_ln_mod(const RadArgs*, RadStream);
int ref_ln_mod_quant_fp8(const RadArgs*, RadStream);
int ref_gate_add(const RadArgs*, RadStream);
int ref_timestep_embed(const RadArgs*, RadStream);
int ref_gather_rows2(const RadArgs*, RadStream);
@@ -197,7 +195,6 @@ int ref_flow_euler(const RadArgs*, RadStream);
int ref_kd_input(const RadArgs*, RadStream);
int ref_kd_step(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 */
@@ -237,6 +234,10 @@ int ref_vsa_select(const RadArgs*, RadStream);
int ref_attn_vsa(const RadArgs*, RadStream);
/* ref_audio.cpp */
int ref_conv1d(const RadArgs*, RadStream);
int ref_elu(const RadArgs*, RadStream);
int ref_vq_euclidean(const RadArgs*, RadStream);
int ref_elu_shape(const RadParam*, int, int, RadOpdDesc*);
int ref_vq_euclidean_shape(const RadParam*, int, int, RadOpdDesc*);
int ref_conv_t1d(const RadArgs*, RadStream);
int ref_snake(const RadArgs*, RadStream);
int ref_snake_aa(const RadArgs*, RadStream);
@@ -367,8 +368,10 @@ REF_SHAPE_FN(ref_hc_project);
REF_SHAPE_FN(ref_mtp_enter);
REF_SHAPE_FN(ref_layernorm);
REF_SHAPE_FN(ref_grid_embed);
REF_SHAPE_FN(ref_grid_embed_pad);
REF_SHAPE_FN(ref_grid_embed_aa);
REF_SHAPE_FN(ref_grid_embed_cpe);
REF_SHAPE_FN(ref_window_order);
REF_SHAPE_FN(ref_lili_cand);
REF_SHAPE_FN(ref_lili_attn);
REF_SHAPE_FN(ref_lili_factor);
@@ -425,10 +428,7 @@ REF_SHAPE_FN(ref_quant_act_i8g);
REF_SHAPE_FN(ref_had_quant_act_i8);
REF_SHAPE_FN(ref_quant_act_fp8);
REF_SHAPE_FN(ref_quant_cols_fp8);
REF_SHAPE_FN(ref_had_quant_act_fp8);
REF_SHAPE_FN(ref_had_quant_act_i8g);
REF_SHAPE_FN(ref_givens_dense_quant);
REF_SHAPE_FN(ref_givens_rotate);
REF_SHAPE_FN(ref_rmsnorm_quant_fp8);
REF_SHAPE_FN(ref_gated_quant_fp8);
REF_SHAPE_FN(ref_gemm_nt_q_gated);
@@ -474,7 +474,6 @@ REF_SHAPE_FN(ref_pixtral_merge);
REF_SHAPE_FN(ref_rope_table);
REF_SHAPE_FN(ref_qk_norm_rope);
REF_SHAPE_FN(ref_ln_mod);
REF_SHAPE_FN(ref_ln_mod_quant_fp8);
REF_SHAPE_FN(ref_gate_add);
REF_SHAPE_FN(ref_timestep_embed);
REF_SHAPE_FN(ref_gather_rows2);
@@ -485,7 +484,6 @@ REF_SHAPE_FN(ref_flow_euler);
REF_SHAPE_FN(ref_kd_input);
REF_SHAPE_FN(ref_kd_step);
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);
+18 -1
View File
@@ -185,13 +185,30 @@ static inline int ref_layout_mtp(const RadParam*, int, int operand, const RadEnc
/* gemm_nt_q: `b_scale` (operand 3) as the scale and zero of the zero-point grid `dtype` names,
* one each per (row, `group` of K), over codes of that grid's width. The codes (operand 2) are one
* plane and stored as they are. A "givens" transform is the activation's (givens_rotate,
* givens_dense_quant), so the planes are read the same way under it. */
* givens_dense_quant), so the planes are read the same way under it.
*
* A symmetric int8 grid's scale in two levels is joined the same way: an unsigned integer "scale"
* per (row, `group` of K) under a float "scale.1" a row (IQ8R), whose product is the scale. */
static inline int ref_layout_gemm_q(const RadParam* p, int n_p, int operand,
const RadEncoding* enc, const int* sel,
const RadTensor* planes, int n, RadLayout* out) {
if (n < 2 || operand != 3) return RAD_E_UNSUPPORTED;
const ZpGrid* zg = zp_grid(rad_param_gets(p, n_p, "dtype", nullptr));
const long long group = rad_param_geti(p, n_p, "group", 0);
if (!zg && sel_roles(enc, sel, n, "scale", "scale.1")) {
if (group <= 0 || !rad_enc_is(enc, "affine") || enc->n_planes != 3) return RAD_E_DTYPE;
const RadEncPlane& c = enc->plane[0];
const RadEncPlane& s = enc->plane[sel[0]];
const RadEncPlane& s2 = enc->plane[sel[1]];
if (std::strncmp(c.role, "codes", RAD_ENC_STR) != 0 || c.dtype != RAD_I8 ||
c.block[0] != 1 || c.block[1] != 1)
return RAD_E_DTYPE;
if (s.kind != RAD_PLANE_TILED || s.dtype != RAD_U8 || s.block[0] != 1 ||
s.block[1] != group || s2.kind != RAD_PLANE_TILED || !float_scale_dt(s2.dtype) ||
s2.block[0] != 1 || s2.block[1] != 0)
return RAD_E_DTYPE;
return rad_planes_layout(enc, sel, planes, n, out);
}
if (!zg || group <= 0 || !rad_enc_is(enc, "affine")) return RAD_E_DTYPE;
if (enc->transform[0] && std::strncmp(enc->transform, "givens", RAD_ENC_STR) != 0)
return RAD_E_DTYPE;
+8 -128
View File
@@ -279,22 +279,6 @@ int ref_dequant(const RadArgs* a, RadStream) {
* s = (k%64)/16, and the k inside the step is 4*lh + _KOFF[i] with _KOFF = {0,8,1,9,2,10,3,11}.
* The scale dword at [t][g][r] holds the f16 scale low and -(1024+zero) high. */
static const int kKOFF[8] = {0, 8, 1, 9, 2, 10, 3, 11};
static float f16_bits_to_f32(uint16_t h) {
uint32_t sign = (uint32_t)(h >> 15) << 31;
uint32_t exp = (uint32_t)(h >> 10) & 0x1fu;
uint32_t mant = (uint32_t)(h & 0x3ffu);
uint32_t f32;
if (exp == 0) {
if (mant == 0) f32 = sign;
else { while (!(mant & 0x400u)) { mant <<= 1; --exp; } f32 = sign | ((exp + 126u) << 23) | ((mant & 0x3ffu) << 13); }
} else if (exp == 31) {
f32 = sign | 0x7f800000u | (mant << 13);
} else {
f32 = sign | ((exp + 112u) << 23) | (mant << 13);
}
float f; std::memcpy(&f, &f32, 4); return f;
}
int ref_dequant_w4(const RadArgs* a, RadStream) {
if (!have(a, 3)) return RAD_E_INVAL;
const RadTensor *wq = &a->t[0], *ws = &a->t[1], *y = &a->t[2];
@@ -319,8 +303,8 @@ int ref_dequant_w4(const RadArgs* a, RadStream) {
const int kbase = kb * 64 + s * 16 + 4 * lh;
const uint32_t sz = Ws[(size_t)(t * ng + kbase / group) * 16 + r];
const float sc = f16_bits_to_f32((uint16_t)(sz & 0xFFFFu));
const float nz = f16_bits_to_f32((uint16_t)(sz >> 16));
const float sc = rad_f16_to_f32((uint16_t)(sz & 0xFFFFu));
const float nz = rad_f16_to_f32((uint16_t)(sz >> 16));
const float zero = -nz - 1024.f;
for (int i = 0; i < 8; i++) {
@@ -423,8 +407,9 @@ int ref_quant_cols_fp8(const RadArgs* a, RadStream) {
* carries the matching rotation and /g.
*
* had_quant_act_i8g is the same at int8 codes (`top` 127), for the i8a8h weight, whose scale
* carries the /g the same way. */
static int had_quant_act_q8(const RadArgs* a, float top) {
* carries the /g the same way. Its rotation is at most `rot_cap` (128) wide: a wider group (IQ8R's
* 256) is whole 128-wide rotations under one scale, the weight's scale carrying /128. */
static int had_quant_act_q8(const RadArgs* a, float top, int64_t rot_cap = 0) {
if (!have(a, 3)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *q = &a->t[1], *s = &a->t[2];
const int64_t n = p_int(a, "n", 0);
@@ -432,6 +417,7 @@ static int had_quant_act_q8(const RadArgs* a, float top) {
/* n % g != 0 is refused: no weight block was rotated across the row's end. */
if (n <= 0 || !pow2(g) || n % g != 0) return RAD_E_SHAPE;
if (g > REF_HAD_MAX) return RAD_E_UNSUPPORTED;
const int64_t rw = rot_cap > 0 && g > rot_cap ? rot_cap : g;
const int64_t rows = numel(x) / n;
const int64_t ngrp = n / g;
if (rows <= 0 || numel(q) < rows * n) return RAD_E_SHAPE;
@@ -445,7 +431,7 @@ static int had_quant_act_q8(const RadArgs* a, float top) {
for (int64_t gi = 0; gi < ngrp; ++gi) {
const int64_t k0 = gi * g;
for (int64_t i = 0; i < g; ++i) buf[i] = ldt(x, xb + (k0 + i) * xs);
fwht(buf, g);
for (int64_t b = 0; b < g; b += rw) fwht(buf + b, rw);
const float sc = q8_group([&](int64_t i) { return buf[i]; }, g, top, q,
qb + k0 * qs, qs);
stt(s, rowoff(s, r, ngrp) + gi * laststride(s), sc);
@@ -454,114 +440,8 @@ static int had_quant_act_q8(const RadArgs* a, float top) {
return RAD_OK;
}
int ref_had_quant_act_fp8(const RadArgs* a, RadStream) {
return had_quant_act_q8(a, 448.0f);
}
int ref_had_quant_act_i8g(const RadArgs* a, RadStream) {
return had_quant_act_q8(a, 127.0f);
}
/* ------------------------------------------------------------- givens_rotate */
/* ParoQuant's activation side: each row divided by its channel factors and rotated by `stages`
* rounds of disjoint Givens pairs, written in y's dtype. A weight stored as v = w . D . G_1 ... G_S
* (abi/rad_encoding.h, "givens") meets x . D^-1 . G_1 ... G_S, since each G is orthogonal and so
* <v, x D^-1 G_1..G_S> = <w, x>. For GEMMs reading a 16-bit activation (w5a16); the quantising
* form is givens_dense_quant.
*
* Parts: a fused projection (gate|up, q|k|v) was rotated per piece, so y is [rows, parts * n] with
* part p at columns [p*n, (p+1)*n). The tables stack per part: `stages` rows of pairs and angles,
* one row of scales. A part's pairs stay within one `group` (128 in the checkpoints).
*
* The device kernel's arithmetic: divide by the channel scale, then per stage
* a' = a cos t + b sin t, b' = b cos t - a sin t in f32. Not bit-identical: libm's and the GPU's
* cos and sin differ by an ulp. */
int ref_givens_rotate(const RadArgs* a, RadStream) {
if (!have(a, 5)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *pr = &a->t[1], *an = &a->t[2], *sc = &a->t[3], *q = &a->t[4];
const int64_t n = p_int(a, "n", 0), S = p_int(a, "stages", 0), P = p_int(a, "parts", 1);
const int64_t g = p_int(a, "group", 0);
if (n <= 0 || S <= 0 || P <= 0 || (n & 1)) return RAD_E_SHAPE;
if (g <= 0 || g > n || n % g != 0) return RAD_E_SHAPE;
if (numel(pr) < P * S * n || numel(an) < P * S * (n / 2) || numel(sc) < P * n) return RAD_E_SHAPE;
const int64_t rows = numel(x) / n;
if (rows <= 0 || numel(q) < rows * P * n) return RAD_E_SHAPE;
// validated before the loop, because an OpenMP body cannot return
for (int64_t i = 0; i < P * S * n; ++i) {
const int64_t c = ld_int(pr->dtype, pr->data, i);
if (c < 0 || c >= n) return RAD_E_INVAL;
}
REF_PAR_FOR(rows * P * n * S)
for (int64_t r = 0; r < rows; ++r) {
std::vector<float> buf((size_t)n);
const int64_t xb = rowoff(x, r, n), qb = rowoff(q, r, P * n);
const int64_t xs = laststride(x), qs = laststride(q);
for (int64_t p = 0; p < P; ++p) {
for (int64_t k = 0; k < n; ++k) buf[(size_t)k] = ldt(x, xb + k * xs) / ldt(sc, p * n + k);
for (int64_t st = 0; st < S; ++st) {
const int64_t t0 = (p * S + st) * n, a0 = (p * S + st) * (n / 2);
for (int64_t j = 0; j < n / 2; ++j) {
const int64_t ia = ld_int(pr->dtype, pr->data, t0 + 2 * j);
const int64_t ib = ld_int(pr->dtype, pr->data, t0 + 2 * j + 1);
const float th = ldt(an, a0 + j), c = ref_cos(th), sn = ref_sin(th);
const float va = buf[(size_t)ia], vb = buf[(size_t)ib];
buf[(size_t)ia] = va * c + vb * sn;
buf[(size_t)ib] = vb * c - va * sn;
}
}
for (int64_t k = 0; k < n; ++k) st_dt(q->dtype, q->data, qb + (p * n + k) * qs, buf[(size_t)k]);
}
}
return RAD_OK;
}
/* ParoQuant's activation quantiser: the rotation as a dense matrix, y[j] = sum_i T[j][i] * x[i] / D[i]
* per (part, 128-column group), then the quantiser named by `q`'s dtype. T is an f16 weight, one
* [128, 128] matrix per (part, group), composed by rad-convert from the givens tables ("t.dense"). */
int ref_givens_dense_quant(const RadArgs* a, RadStream) {
if (!have(a, 5)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *tm = &a->t[1], *sc = &a->t[2], *q = &a->t[3], *s = &a->t[4];
const int64_t n = p_int(a, "n", 0), P = p_int(a, "parts", 1), g = p_int(a, "group", 0);
if (n <= 0 || P <= 0 || g != 128 || n % g != 0) return RAD_E_SHAPE;
const bool i8 = q->dtype == RAD_I8;
if (!i8 && q->dtype != RAD_F8E4M3) return RAD_E_DTYPE;
if (std::strcmp(p_str(a, "out", ""), i8 ? "i8" : "fp8") != 0) return RAD_E_DTYPE; // `out` names q's dtype
const int64_t rows = numel(x) / n, ngrp = n / g;
if (rows <= 0 || numel(tm) < P * n * g || numel(sc) < P * n || numel(q) < rows * P * n ||
numel(s) < rows * P * ngrp) return RAD_E_SHAPE;
const float qmax = i8 ? 127.0f : 448.0f;
REF_PAR_FOR(rows * P * n * g)
for (int64_t r = 0; r < rows; ++r) {
const int64_t xb = rowoff(x, r, n), qb = rowoff(q, r, P * n);
const int64_t xs = laststride(x), qs = laststride(q);
std::vector<float> in((size_t)g), y((size_t)g);
for (int64_t p = 0; p < P; ++p)
for (int64_t gi = 0; gi < ngrp; ++gi) {
for (int64_t i = 0; i < g; ++i)
in[(size_t)i] = ldt(x, xb + (gi * g + i) * xs) / ldt(sc, p * n + gi * g + i);
float amax = 0.0f;
for (int64_t j = 0; j < g; ++j) {
double acc = 0.0;
for (int64_t i = 0; i < g; ++i)
acc += (double)ldt(tm, ((p * ngrp + gi) * g + j) * g + i) * (double)in[(size_t)i];
y[(size_t)j] = (float)acc;
amax = std::max(amax, std::fabs(y[(size_t)j]));
}
const float scl = amax > 0.0f ? amax * (1.0f / qmax) : 1.0f;
const float inv = 1.0f / scl;
for (int64_t j = 0; j < g; ++j) {
float v = y[(size_t)j] * inv;
if (v > qmax) v = qmax;
if (v < -qmax) v = -qmax;
if (i8) v = std::nearbyint(v);
st_dt(q->dtype, q->data, qb + (p * n + gi * g + j) * qs, v);
}
stt(s, rowoff(s, r, P * ngrp) + (p * ngrp + gi) * laststride(s), scl);
}
}
return RAD_OK;
return had_quant_act_q8(a, 127.0f, 128);
}
+49 -58
View File
@@ -172,6 +172,10 @@ static const RadOperandSpec oLayernorm[] = { OPD("x"), WGT("w"), WGT_O("b"), OUT
/* A learned position table resampled to each row's grid and added in (a vision tower's). */
static const RadParamSpec pGridEmbed[] = { P_INT("M"), P_INT("n"), P_INT("side"), P_STR("dtype") };
static const RadOperandSpec oGridEmbed[] = { INOUT("x"), WGT("table"), OPD("coord") };
/* window_order: the window permutation of one pass, from the coordinate planes alone. */
static const RadParamSpec pWindowOrder[] = { P_INT("M"), P_INT("window") };
static const RadOperandSpec oWindowOrder[] = { OPD("crd"), OPD_O("cu"), OUT("idx"), OUT("inv"),
OUT("pos"), OUT("cuw") };
/* grid_embed_cpe adds the rows a segment carries ahead of its patches (n_prefix, `prefix`). */
static const RadParamSpec pGridEmbedCpe[] = { P_INT("M"), P_INT("n"), P_INT("side"), P_STR("dtype"),
P_INTO("n_prefix") };
@@ -647,7 +651,7 @@ static const RadOperandSpec oMoeGemm[] = { OPD("a"), WTAB("w"), OPD("sorted_tok"
static const RadParamSpec pMoeGemmQ[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_INT("n_expert"),
P_INT("top_k"), P_INT("group"), P_STR("a_order"),
P_STR("dtype"), P_INTO("N_odd"), P_INTO("K_odd"),
P_INTO("parts") };
P_INTO("parts"), P_INTO("a_group") };
static const RadOperandSpec oMoeGemmQ[] = { OPD("a"), OPD_O("a_scale"), WTAB("w"), WTAB("w_scale"),
OPD("sorted_tok"), OPD("expert_offset"),
WTAB("w_odd"), WTAB("w_odd_scale"), OUT("y") };
@@ -658,7 +662,7 @@ static const RadParamSpec pMoeGemmQMod4[] = { P_INT("M"), P_INT("N"), P_INT("K")
P_INT("top_k"), P_INT("group"), P_STR("a_order"),
P_STR("dtype"), P_INTO("N_1"), P_INTO("K_1"),
P_INTO("N_2"), P_INTO("K_2"), P_INTO("N_3"),
P_INTO("K_3"), P_INTO("parts") };
P_INTO("K_3"), P_INTO("parts"), P_INTO("a_group") };
static const RadOperandSpec oMoeGemmQMod4[] = { OPD("a"), OPD_O("a_scale"), WTAB("w"),
WTAB("w_scale"), OPD("sorted_tok"),
OPD("expert_offset"), WTAB("w_1"),
@@ -1095,6 +1099,8 @@ static const RadParamSpec pVqEncode[] = { P_INT("M"), P_INT("n"), P_INT("dim"),
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 pVqEuclidean[] = { P_INT("M"), P_INT("n"), P_INT("bins"), P_STR("dtype") };
static const RadOperandSpec oVqEuclidean[] = { INOUT("x"), WGT("cb"), 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"),
@@ -1201,6 +1207,8 @@ static const RadOpSchema kSchemas[] = {
"quantised from the NARROWED x and not from the accumulator. With `rotate` (and `group`), `rq` "
"and `rscale` carry had_quant_act_fp8 of the same stored x: each scale group rotated by an "
"unnormalised Hadamard before its absmax, for a consumer whose weight carries the rotation. "
"An int8 `q` or `rq` takes int8 codes instead (scale absmax / 127), quant_act_i8g's and "
"had_quant_act_i8g's. "
"`mix` names the mixing matrices' STORED format, \"bf16\" or \"e4m3\"; the arithmetic is the "
"same and an oracle reads either as the dense tensor its kernel's inverse returns." },
{ "hc_write", ARR(pHcWrite), ARR(oHcWrite),
@@ -1225,6 +1233,23 @@ static const RadOpSchema kSchemas[] = {
"`coord` is [4, M] -- row, column, grid height, grid width -- and the position is sampled "
"bilinearly with the grid's corners on the table's corners (align_corners), edge taps clamped. "
"The taps are summed in f32 and rounded to x's dtype, then added to x and rounded again." },
{ "grid_embed_pad", ARR(pGridEmbed), ARR(oGridEmbed),
"x[m] += the table resampled at row m's grid position in the half-pixel-centre form "
"(align_corners=False) with grid_sample's padding_mode=\"zeros\": per axis taps at floor(src) "
"and floor(src) + 1 of src = (i + 0.5) * side / size - 0.5, each carrying the hat weight "
"(1 - |src - tap|)+, and a tap whose UNCLAMPED index falls outside the table contributes zero "
"rather than reading an edge. Same operands and tap order as `grid_embed`; equal to it whenever "
"the grid fits the table, different only when a grid upsamples past it (Muse's case)." },
{ "window_order", ARR(pWindowOrder), ARR(oWindowOrder),
"The window-attention permutation of one encoder pass (HF's get_vision_window_index) computed "
"from the coordinates alone: `crd` [4, P] i32 is row, column, segment height, segment width per "
"patch and `cu` [S+1] i32 the per-frame segment boundaries. Windows of `window` patches "
"partition each segment, window-row-major, ragged at the segment's right and bottom edges, "
"patches raster within a window and windows never across segments. Outputs i32: `idx` [P], "
"slot -> source patch (the gather index); `inv` [P], the inverse; `pos` [2, P], each slot's rope "
"positions (col + 1, row + 1), component-major like the planes; `cuw` [P+1], the cumulative "
"window boundaries in the permuted order, n_windows + 1 entries used. `M` bands the pass; slots "
"past M are the identity. `window` <= 0 is the identity permutation, cuw = cu." },
{ "grid_embed_aa", ARR(pGridEmbed), ARR(oGridEmbed),
"x += the side x side table resampled as torch's F.interpolate(bilinear, align_corners=False, "
"antialias=True) resamples it to the row's grid -- SigLIP2's position embedding: per axis a "
@@ -1477,31 +1502,17 @@ static const RadOpSchema kSchemas[] = {
"with log probability parent + log_softmax(score / temp) over them, and each round selects the "
"unselected child with the largest (ties to the first pushed). tokens[j-1] and parents[j-1] are "
"the j-th selected node and its parent's index (0 the anchor)." },
{ "givens_dense_quant", ARR(pGivensDense), ARR(oGivensDense),
"ParoQuant's activation quantiser with the rotation as a dense per-group matrix: y = T (x / "
"rscale) for each of `parts` rotated copies, T the [128, 128] f16 matrix a (part, 128-column "
"group) that its Givens stages compose to, then the block-scaled quantiser `out` names "
"(\"i8\": scale amax / 127, round to nearest; \"fp8\": E4M3, amax / 448). q is [M, parts * n] "
"and scale [M, parts * n / group]; tdense is [parts * n, 128]. The same activation as "
"the sequential rotation, up to the f16 rounding of T." },
{ "givens_rotate", ARR(pGivensRotate), ARR(oGivensRotate),
"ParoQuant's rotation without a quantiser: y = x / rscale rotated by `stages` rounds of Givens "
"pairs, `parts` copies side by side ([M, parts * n]) in y's own dtype. For a weight whose GEMM "
"reads a 16-bit activation. `group` is the width a pair stays inside." },
/* The rotated fp8 twin. Unlike had_quant_act_i8, the group is both rotation width and scale
* granularity, and the factor of `group` is left entirely to the paired w4a8h weight plane, where
* the division is an exact exponent shift on a bf16 (libref/ref_quant.cpp). */
{ "had_quant_act_fp8", ARR(pQuant), ARR(oQuantFp8),
"A Walsh-Hadamard rotation of width `group` along n, then symmetric E4M3 per group: scale = "
"amax(rotated) / 448, shaped [M, n/group] in f32. n must be a multiple of `group` -- a rotation "
"block cannot straddle the end of a row. NOT interchangeable with quant_act_fp8 in either "
"direction: the consumer must be a weight that was rotated the same way." },
/* Its int8 twin, the activation of the i8a8h GEMMs; the factor of `group` is the weight's here
* too. */
{ "had_quant_act_i8g", ARR(pQuant), ARR(oQuantFp8),
"quant_act_i8g with a Walsh-Hadamard rotation of width `group` along n first: scale = "
"amax(rotated) / 127 per group, [M, n/group] in f32, n a multiple of `group`. Pairs with an i8 "
"weight rotated the same way, its scale carrying the factor of `group` (dtype i8a8h)." },
"weight rotated the same way, its scale carrying the factor of `group` (dtype i8a8h). A `group` "
"above 128 is whole 128-wide rotations under one scale (IQ8R's 256), the weight's scale "
"carrying the factor of 128." },
/* The calibration op, the only one no forward pass issues: it runs under a calibration flag and
* its output is read at convert time, in another process, through a file. `dtype` is the input's:
* fp8a8 where the tap is a quantiser's output, bf16 without `a_scale` for a plain activation. */
@@ -1883,10 +1894,6 @@ static const RadOpSchema kSchemas[] = {
"For a row with RAD_SP_LOGPROBS: the raw logits' max, sum of exp(l - max) and k largest as (id, "
"logit) pairs, descending, ties to the lower id. Other rows are not written." },
/* ---- image generation -------------------------------------------------------------------- */
{ "ln_mod_quant_fp8", ARR(pLnModQ), ARR(oLnModQ),
"the DiT block's norm in front of a quantised linear, in one pass: with `gated` 1 the branch "
"before it is added first, x = bf16(x + bf16(bf16(tanh(g[seq])) * y)); then z = ln_mod(x) and "
"(q, scale) = quant_act_fp8(z, group) -- written when bound, z." },
{ "ln_mod", ARR(pLnMod), ARR(oLnMod),
"y = bf16(bf16(LN(x)) * bf16(1 + s[seq])): a layer norm with no gain or bias, then the row's "
"sequence's modulation row of `s` ([n_seq, >= n] at its own pitch). A diffusion transformer's "
@@ -1969,9 +1976,6 @@ static const RadOpSchema kSchemas[] = {
"(no tanh), stored; then n1 = bf16(x * rsqrt(mean(x^2) + eps)), n2 = bf16(n1 * w), "
"m = bf16(n2 * bf16(1 + scale[seq])), z = bf16(m + shift[seq]), `s` [n_seq, >= 2n] holding "
"[shift | scale] at its own pitch." },
{ "rms_mod_quant_fp8", ARR(pRmsModQ), ARR(oRmsModQ),
"rms_mod with the norm chain in bf16, then (q, scale) = quant_act_fp8(z, group) as "
"ln_mod_quant_fp8 makes them; z written when bound." },
{ "flow_x0_step", ARR(pMnD), ARR(oFlowX0),
"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 "
@@ -2112,8 +2116,8 @@ static const RadOpSchema kSchemas[] = {
"a 1-D convolution over the sequences `cu_seqlens` bounds, channels innermost: x [rows, cin], "
"y [rows, cout], PyTorch's [cout, cin, k] weight and an optional bias, dilation `dil` and padding "
"dil (k - 1) / 2 a side (k odd), or dil (k - 1) on the left with `causal` 1, zeros outside each "
"sequence; `res` added after the bias, then `act` none, tanh or clamp (to [-1, 1]). bf16 only "
"with `stride` > 1: one sequence [0, rows of x], an explicit `pad` and any k, output row m "
"sequence; `res` added after the bias, then `act` none, tanh or clamp (to [-1, 1]). With "
"`stride` > 1 and an explicit `pad` (bf16 only): one sequence [0, rows of x], any k, output row m "
"reading x[m * stride + tap * dil - pad] — PyTorch's zero-padded strided conv exactly." },
{ "conv_t1d", ARR(pConvT1d), ARR(oConvT1d),
"a transposed 1-D convolution of kernel `k` >= stride (2 stride by default), padding `pad` "
@@ -2142,7 +2146,10 @@ static const RadOpSchema kSchemas[] = {
{ "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." },
"once." },
{ "vq_euclidean", ARR(pVqEuclidean), ARR(oVqEuclidean),
"nearest Euclidean centroid (lower index on ties), codes written and centroid subtracted from x." },
{ "elu", ARR(pMnD), ARR(oUnary), "y = x >= 0 ? x : expm1(x), alpha 1." },
{ "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." },
@@ -2193,10 +2200,6 @@ static const RadOpSchema kSchemas[] = {
"rmsnorm, for rows a model declares in thousands (the head norms over head_dim)." },
{ "rope_rows", ARR(pRope), ARR(oRope),
"rope, for a model that wants the per-(token, pair) angles form at prefill row counts." },
{ "gemm_nt_q_short", ARR(pGemmQ), ARR(oGemmQ),
"gemm_nt_q, for the short-prompt split rule's rows." },
{ "gemm_nt_q_gated_wide", ARR(pGemmQGated), ARR(oGemmQGated),
"gemm_nt_q_gated at any M." },
};
/* ================================================================== the kernel table */
@@ -2337,7 +2340,7 @@ int ref_unrelayout_gemm_q_m2(const RadParam*, int, int, const RadEncoding*, cons
#define DT_FLOAT "bf16 f16 f32 fp8_e4m3 fp8_e5m2 i8 i32, chosen per operand from its own dtype"
#define DT_ANY "any dtype rad_types.h names, per operand"
#define DT_FLOAT_CB DT_FLOAT "; or u4 / u5 codes into an f32 table, joined (w4nl* / w5nl*)"
#define DT_FLOAT_CB DT_FLOAT "; or u4 / u5 / u6 codes into an f32 table, joined (w4nl* / w5nl* / w6nl*)"
static const RadKernelInfo kKernels[] = {
SIMPLE("ref_rmsnorm", "rmsnorm", "norm", "root-mean-square norm with a gain", DT_FLOAT,
@@ -2379,6 +2382,12 @@ SIMPLE("ref_layernorm", "layernorm", "norm", "layer norm with gain and bias", DT
ref_layernorm),
SIMPLE("ref_grid_embed", "grid_embed", "elem",
"bilinear resample of a learned position grid, added in", DT_FLOAT, ref_grid_embed),
SIMPLE("ref_grid_embed_pad", "grid_embed_pad", "elem",
"half-pixel bilinear resample of a position grid, zero-padded taps, added in", DT_FLOAT,
ref_grid_embed_pad),
SIMPLE("ref_window_order", "window_order", "elem",
"the window-attention permutation of one pass, from its coordinates", DT_ANY,
ref_window_order),
SIMPLE("ref_grid_embed_aa", "grid_embed_aa", "elem",
"antialiased half-pixel bilinear resample of a position grid, added in", DT_FLOAT,
ref_grid_embed_aa),
@@ -2515,19 +2524,9 @@ SIMPLE("ref_dflash_markov_greedy_f32", "dflash_markov_greedy_f32", "draft",
SIMPLE("ref_dflash_tree", "dflash_tree", "draft",
"DFlash2's candidate lattice grown best-first into a tree",
"i32 candidates, bf16 codebooks, i32 tokens and parents out", ref_dflash_tree),
SIMPLE("ref_givens_rotate", "givens_rotate", "quant",
"channel scale and Givens rotations per part, in the output's dtype",
"float in, float out; int32 pairs, f32 angles and channel scales", ref_givens_rotate),
SIMPLE("ref_givens_dense_quant", "givens_dense_quant", "quant",
"the rotation as a dense per-group matrix, then the block-scaled int8 or E4M3 quantiser",
"float in, int8 or fp8_e4m3 out, f32 scale per group; f16 matrices and f32 channel scales",
ref_givens_dense_quant),
SIMPLE("ref_had_quant_act_fp8", "had_quant_act_fp8", "quant",
"width-`group` Hadamard, then the same symmetric block-scaled E4M3 quantiser",
"float in, fp8_e4m3 out, f32 scale per group; n a multiple of group",
ref_had_quant_act_fp8),
SIMPLE("ref_had_quant_act_i8g", "had_quant_act_i8g", "quant",
"width-`group` Hadamard, then the symmetric int8 quantiser, one scale per group",
"width-`group` Hadamard (128-wide rotations where `group` is wider), then the symmetric "
"int8 quantiser, one scale per group",
"float in, i8 out, f32 scale per group; n a multiple of group",
ref_had_quant_act_i8g),
SIMPLE("ref_gram_accum", "gram_accum", "quant",
@@ -2728,9 +2727,6 @@ SIMPLE("ref_ln_mod", "ln_mod", "norm", "gainless layer norm times (1 + a sequenc
DT_FLOAT, ref_ln_mod),
SIMPLE("ref_gate_add", "gate_add", "elem", "x += act(gate row) * y, act tanh or none", DT_FLOAT,
ref_gate_add),
SIMPLE("ref_ln_mod_quant_fp8", "ln_mod_quant_fp8", "norm",
"gated residual, gainless layer norm times (1 + scale row), block-scaled E4M3",
DT_FLOAT, ref_ln_mod_quant_fp8),
SIMPLE("ref_timestep_embed", "timestep_embed", "elem", "sinusoidal timestep embedding",
DT_FLOAT, ref_timestep_embed),
SIMPLE("ref_gather_rows2", "gather_rows2", "elem", "rows from two sources by a signed index",
@@ -2769,8 +2765,6 @@ SIMPLE("ref_attn_prefix_self", "attn_prefix_self", "attn",
SIMPLE("ref_rms_mod", "rms_mod", "norm",
"gated residual, RMS norm with a gain times (1 + scale row) plus a shift row", DT_FLOAT,
ref_rms_mod),
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",
@@ -2843,7 +2837,10 @@ SIMPLE("ref_cfg_topk_sample", "cfg_topk_sample", "sample", "a guided top-k pick
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),
"a residual quantiser's step: the nearest code by cosine", DT_FLOAT, ref_vq_encode),
SIMPLE("ref_vq_euclidean", "vq_euclidean", "elem", "Euclidean residual quantiser", DT_FLOAT,
ref_vq_euclidean),
SIMPLE("ref_elu", "elu", "elem", "ELU, alpha 1", DT_FLOAT, ref_elu),
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,
@@ -2876,12 +2873,6 @@ SIMPLE("ref_sub_i32", "sub_i32", "elem", "a device int32 vector less a device sc
SIMPLE("ref_rmsnorm_rows", "rmsnorm_rows", "norm", "rmsnorm under its row-form name", DT_FLOAT,
ref_rmsnorm),
SIMPLE("ref_rope_rows", "rope_rows", "attn", "rope under its row-form name", DT_FLOAT, ref_rope),
ROWL_GQ("ref_gemm_nt_q_short", "gemm_nt_q_short", "gemm", "gemm_nt_q under its row-form name",
"as ref_gemm_nt_q", ref_check_gemm_q, ref_gemm_nt_q_m2, ref_layout_gemm_q_m2,
ref_relayout_gemm_q_m2, ref_unrelayout_gemm_q_m2),
SIMPLE("ref_gemm_nt_q_gated_wide", "gemm_nt_q_gated_wide", "gemm",
"gemm_nt_q_gated under its row-form name", "fp8_e4m3 operands, fp8_e4m3 out, f32 scale",
ref_gemm_nt_q_gated),
};
/* ================================================================== plugin exports */
+78 -80
View File
@@ -64,6 +64,7 @@
#include "ref_ops.h"
/* rad_param_find / rad_param_getdim / rad_param_gets / rad_dtype_parse. */
#include "rad_builder.h" /* rad_kv_row_elems */
#include "rad_plugin.h"
#include "rad_runtime.h" /* RAD_VGEOM_N */
#include "rad_sample.h"
@@ -509,6 +510,22 @@ int ref_grid_embed_aa_shape(const RadParam* p, int n_p, int operand, RadOpdDesc*
return o.finish("grid_embed_aa", operand, out);
}
/* grid_embed_pad's: the same operands and drawing as grid_embed's. */
int ref_grid_embed_pad_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const uint32_t D = act_dt(p, n_p);
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0), side = gi(p, n_p, "side", 0);
if (M <= 0 || n <= 0 || side <= 0) return RAD_E_UNSUPPORTED;
Opd o;
o.t(D, { M, n }); /* x, INOUT */
o.t(D, { side * side, n }); /* table */
o.t_idx({ 4, M }, side, -1, 0);
return o.finish("grid_embed_pad", operand, out);
}
/* window_order declines: its `crd` rows, segment grids and `cu` boundaries must describe whole
* raster grids, and an index draw cannot; avx_check_hand.cpp and the unit tests build them. */
int ref_window_order_shape(const RadParam*, int, int, RadOpdDesc*) { return RAD_E_UNSUPPORTED; }
/* grid_embed's operands plus the prefix rows; coordinates drawn over the table's side. */
int ref_grid_embed_cpe_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const uint32_t D = act_dt(p, n_p);
@@ -1249,30 +1266,6 @@ int ref_gram_accum_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* ou
return o.finish("gram_accum", operand, out);
}
/* Declined: `pairs` must pair each group's columns (every column once per stage, partner in the
* group), and a drawn index operand has repeats, so it would not be a rotation. r4d_selftest builds
* real pairings. */
int ref_givens_dense_quant_shape(const RadParam*, int, int, RadOpdDesc*) {
return RAD_E_UNSUPPORTED; /* a composed rotation cannot be drawn: it is a weight, built from real pairings */
}
int ref_givens_rotate_shape(const RadParam*, int, int, RadOpdDesc*) {
return RAD_E_UNSUPPORTED; /* a pairing cannot be drawn: a described operand can only be drawn, and an index draw has repeats */
}
/* The same extents as quant_act_fp8: `group` is both rotation width and scale granularity here,
* unlike the int8 rotated forms, so the rotation changes the values, not the shapes. */
int ref_had_quant_act_fp8_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const uint32_t D = act_dt(p, n_p);
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
const int64_t ng = scale_groups(n, gi(p, n_p, "group", 0));
Opd o;
o.t(D, { M, n }); /* x */
o.t((uint32_t)RAD_F8E4M3, { M, n }); /* q */
o.t((uint32_t)RAD_F32, { M, ng }); /* scale, a dequant multiplier (amax / 448) */
return o.finish("had_quant_act_fp8", operand, out);
}
/* quant_act_i8g's extents: the rotation changes the values, not the shapes. */
int ref_had_quant_act_i8g_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const uint32_t D = act_dt(p, n_p);
@@ -1555,11 +1548,13 @@ static int ref_attn_paged_shape_impl(const RadParam* p, int n_p, int operand, Ra
if (ctx < M) ctx = M;
const int64_t max_blocks = (ctx + bs - 1) / bs;
/* `q_dtype` and `kv_dtype` are read separately: the engine issues fp8 caches beside bf16
* queries. */
/* `q_dtype` and `kv_dtype` are read separately: the engine issues int8 caches beside bf16
* queries. An int8 cache is not described: a row's two f16 scales cannot be drawn at random
* (the hand cases build one). */
const uint32_t Q = act_dt(p, n_p);
const uint32_t kv = dt_parse(gs(p, n_p, "kv_dtype"));
const uint32_t KV = kv == (uint32_t)RAD_DT_INVALID ? Q : kv;
if (KV == (uint32_t)RAD_I8) return RAD_E_UNSUPPORTED;
Opd o;
o.t(Q, { S * M, nh, hd }); /* q */
@@ -1734,7 +1729,7 @@ int ref_kv_store_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out)
/* Two blocks of slack so the slot mapping is not a dense prefix and the block index matters. */
const int64_t nb = (M + bs - 1) / bs + 2;
/* Only the cache takes `kv_dtype`: k and v are bf16 activations whatever the cache stores
* (act_dt would fall back on kv_dtype and describe an fp8 k). */
* (act_dt would fall back on kv_dtype and describe an int8 k). */
const uint32_t D = (uint32_t)RAD_BF16;
const uint32_t kv = dt_parse(gs(p, n_p, "kv_dtype"));
const uint32_t KV = kv == (uint32_t)RAD_DT_INVALID ? D : kv;
@@ -1744,7 +1739,7 @@ int ref_kv_store_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out)
o.t(D, { M, kvh, hd }); /* v */
/* A scatter destination: distinct (see the file header), over the whole cache in slots. */
o.t_idx({ M }, nb * bs, -1, (uint32_t)RAD_OPD_F_IDX_UNIQUE); /* slot_mapping */
o.t(KV, { nb, kvh, bs, 2 * hd }); /* kv_cache, INOUT */
o.t(KV, { nb, kvh, bs, rad_kv_row_elems(KV, hd) }); /* kv_cache, INOUT */
return o.finish("kv_store", operand, out);
}
@@ -1760,14 +1755,15 @@ int ref_kv_store_streamed_shape(const RadParam* p, int n_p, int operand, RadOpdD
const int64_t bs = gi(p, n_p, "block_size", 0);
if (M <= 0 || hd <= 0 || kvh <= 0 || bs <= 0 || M > bs) return RAD_E_UNSUPPORTED;
const uint32_t kv = dt_parse(gs(p, n_p, "kv_dtype"));
const uint32_t KV = kv == (uint32_t)RAD_DT_INVALID ? (uint32_t)RAD_F8E4M3 : kv;
const int64_t row = kvh * bs * 2 * hd * (KV == (uint32_t)RAD_BF16 ? 2 : 1);
const uint32_t KV = kv == (uint32_t)RAD_DT_INVALID ? (uint32_t)RAD_I8 : kv;
const int64_t rowe = rad_kv_row_elems(KV, hd);
const int64_t row = kvh * bs * rowe * (KV == (uint32_t)RAD_BF16 ? 2 : 1);
Opd o;
o.t((uint32_t)RAD_BF16, { M, kvh, hd }); /* k */
o.t((uint32_t)RAD_BF16, { M, kvh, hd }); /* v */
o.t_idx({ M }, bs, -1, (uint32_t)RAD_OPD_F_IDX_UNIQUE); /* slot_mapping, one block */
o.t(KV, { 1, kvh, bs, 2 * hd }); /* kv_cache, INOUT */
o.t(KV, { 1, kvh, bs, rowe }); /* kv_cache, INOUT */
o.t_idx({ 1 }, 1, -1, 0); /* res -- resident in slot 0 */
o.t((uint32_t)RAD_U8, { 1, row }); /* host, INOUT */
return o.finish("kv_store_streamed", operand, out);
@@ -2120,8 +2116,10 @@ int ref_moe_gemm_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out)
/* The weight scale grid `dtype` names, as weight rows and K elements per scale. Block-fp8 experts
* (fp8a8) carry the checkpoint's one scale per 128x128 tile (`group` = 128). The 4-bit formats
* (docs/MOE-W4.md) carry one per row per K group: all of `group` for w4a8, w4a8h and w4nla8h, half
* for w4nl64a8h and w5nl64a8h, a quarter for w4nl32a8h. These are the served format names
* (arch/common/rad_block_moe_fp8.h, kServed). Any other dtype returns { 0, 0 } and the description
* for w4nl64a8h and w5nl64a8h, a quarter for w4nl32a8h. The `a8i8` names are the four-bit formats
* against an int8 activation and `i8a8` / `i8a8h` int8 experts against one, a scale per row per
* `group`. These are the served format names (arch/common/rad_block_moe_fp8.h, kServed and
* kServed8). Any other dtype returns { 0, 0 } and the description
* declines rather than guess a grid.
*
* The grid matters beyond extents: re-laid weights are inverted into the tensor described here
@@ -2134,10 +2132,25 @@ static MoeScaleGrid moe_scale_grid(const RadParam* p, int n_p, int64_t g) {
if (is("fp8a8") || is("fp8a8f32")) return { g, g };
if (is("mxfp4a8")) return { 1, 32 };
if (is("w4a8") || is("w4a8h") || is("w4nla8h")) return { 1, g };
if (is("w4nl64a8h") || is("w5nl64a8h")) return { 1, g / 2 };
if (is("w4nl64a8h") || is("w5nl64a8h") || is("w6nl64a8h")) return { 1, g / 2 };
if (is("w4nl32a8h")) return { 1, g / 4 };
if (is("i8a8") || is("i8a8h") || is("w4a8i8") || is("w4a8i8h")) return { 1, g };
if (is("w4nl64a8i8h")) return { 1, g / 2 };
if (is("w4nl32a8i8h")) return { 1, g / 4 };
return { 0, 0 };
}
/* The operands' code dtypes `dtype` names: an int8 activation for the `a8i8` and `i8a8` names and
* int8 experts for the latter, E4M3 otherwise. A four-bit expert is described at the E4M3 its
* logical values are exact in, whichever activation it meets. */
struct MoeCodes { uint32_t a, w; };
static MoeCodes moe_codes(const RadParam* p, int n_p) {
const char* d = gs(p, n_p, "dtype");
auto is = [&](const char* s) { return d && std::strcmp(d, s) == 0; };
const bool w8 = is("i8a8") || is("i8a8h");
const bool a8 = w8 || is("w4a8i8") || is("w4a8i8h") || is("w4nl64a8i8h") || is("w4nl32a8i8h");
return { a8 ? (uint32_t)RAD_I8 : (uint32_t)RAD_F8E4M3,
w8 ? (uint32_t)RAD_I8 : (uint32_t)RAD_F8E4M3 };
}
/* The quantised arm: the same planes plus two scale streams, the activation's per row per K group
* and the weight's one plane per expert on the grid above ([ceil(N/g), ceil(K/g)] for block fp8).
@@ -2169,16 +2182,19 @@ int ref_moe_gemm_q_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* ou
const char* kind = gs(p, n_p, "dtype");
const bool mx = kind && !std::strcmp(kind, "mxfp4a8");
const auto SD = kind && !std::strcmp(kind, "fp8a8f32") ? (uint32_t)RAD_F32 : D;
o.t((uint32_t)RAD_F8E4M3, { AR, K }); /* a -- E4M3 codes, see `a_order` */
o.t((uint32_t)RAD_F32, { AR, (K + g - 1) / g }); /* a_scale */
const MoeCodes cd = moe_codes(p, n_p);
/* The K one activation scale covers: `a_group` where stated, else `group`. */
const int64_t ag = gi(p, n_p, "a_group", g) > 0 ? gi(p, n_p, "a_group", g) : g;
o.t(cd.a, { AR, K }); /* a -- E4M3 or int8 codes, see `a_order` */
o.t((uint32_t)RAD_F32, { AR, (K + ag - 1) / ag }); /* a_scale */
/* w -- the even experts; mxfp4a8 carries e2m1 codes with an E8M0 byte per (row, 32 of K) */
o.t(mx ? (uint32_t)RAD_FP4E2M1 : (uint32_t)RAD_F8E4M3, { ne0, N0, K0 });
o.t(mx ? (uint32_t)RAD_FP4E2M1 : cd.w, { ne0, N0, K0 });
if (mx) o.t_idx_dt(RAD_U8, { ne0, N0, (K0 + 31) / 32 }, 0, 127, 0); /* w_scale */
else o.t(SD, { ne0, (N0 + sg.rows - 1) / sg.rows, (K0 + sg.k - 1) / sg.k });
o.t_idx({ M * k }, M * k, -1, (uint32_t)RAD_OPD_F_IDX_UNIQUE); /* sorted_tok */
o.t_idx({ ne + 1 }, M * k + 1, -1, (uint32_t)RAD_OPD_F_IDX_PREFIX); /* expert_offset */
/* w_odd -- the odd experts */
o.t(mx ? (uint32_t)RAD_FP4E2M1 : (uint32_t)RAD_F8E4M3, { ne1, N1, K1 });
o.t(mx ? (uint32_t)RAD_FP4E2M1 : cd.w, { ne1, N1, K1 });
if (mx) o.t_idx_dt(RAD_U8, { ne1, N1, (K1 + 31) / 32 }, 0, 127, 0); /* w_odd_scale */
else o.t(SD, { ne1, (N1 + sg.rows - 1) / sg.rows, (K1 + sg.k - 1) / sg.k });
o.t(D, { M * k, N }); /* y -- in sorted order */
@@ -2210,14 +2226,16 @@ int ref_moe_gemm_q_mod4_shape(const RadParam* p, int n_p, int operand, RadOpdDes
const int64_t AR = sorted_a_order(p, n_p) ? M * k : M;
const char* kind = gs(p, n_p, "dtype");
const bool mx = kind && !std::strcmp(kind, "mxfp4a8");
const MoeCodes cd = moe_codes(p, n_p);
const int64_t ag = gi(p, n_p, "a_group", g) > 0 ? gi(p, n_p, "a_group", g) : g;
auto cls = [&](int q) {
const int64_t nq = (ne + 3 - q) / 4;
o.t(mx ? (uint32_t)RAD_FP4E2M1 : (uint32_t)RAD_F8E4M3, { nq, Nq[q], Kq[q] });
o.t(mx ? (uint32_t)RAD_FP4E2M1 : cd.w, { nq, Nq[q], Kq[q] });
if (mx) o.t_idx_dt(RAD_U8, {nq, Nq[q], (Kq[q] + 31) / 32}, 0, 127, 0);
else o.t(D, { nq, (Nq[q] + sg.rows - 1) / sg.rows, (Kq[q] + sg.k - 1) / sg.k });
};
o.t((uint32_t)RAD_F8E4M3, { AR, K }); /* a -- E4M3 codes, see `a_order` */
o.t((uint32_t)RAD_F32, { AR, (K + g - 1) / g }); /* a_scale */
o.t(cd.a, { AR, K }); /* a -- E4M3 or int8 codes, see `a_order` */
o.t((uint32_t)RAD_F32, { AR, (K + ag - 1) / ag }); /* a_scale */
cls(0); /* w, w_scale -- class 0 */
o.t_idx({ M * k }, M * k, -1, (uint32_t)RAD_OPD_F_IDX_UNIQUE); /* sorted_tok */
o.t_idx({ ne + 1 }, M * k + 1, -1, (uint32_t)RAD_OPD_F_IDX_PREFIX); /* expert_offset */
@@ -3004,21 +3022,6 @@ int ref_ln_mod_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
o.t(D, { M, n }); /* y */
return o.finish("ln_mod", operand, out);
}
int ref_ln_mod_quant_fp8_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 ng = scale_groups(n, gi(p, n_p, "group", 0));
const uint32_t D = act_dt(p, n_p);
Opd o;
o.t(D, { M, n }); /* y */
o.t(D, { 1, n }); /* g: one sequence */
o.t(D, { 1, n }); /* s */
o.t_idx({ 2 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_seqlens */
o.t(D, { M, n }); /* x, INOUT */
o.t((uint32_t)RAD_F8E4M3, { M, n }); /* q */
o.t((uint32_t)RAD_F32, { M, ng }); /* scale */
o.t(D, { M, n }); /* z */
return o.finish("ln_mod_quant_fp8", operand, out);
}
/* rms_mod's branch and gate are passed when `gated`, and absent otherwise. */
int ref_rms_mod_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);
@@ -3042,30 +3045,6 @@ int ref_rms_mod_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out)
o.skip(); /* colmap: the sweep passes none */
return o.finish("rms_mod", operand, out);
}
int ref_rms_mod_quant_fp8_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 ng = scale_groups(n, gi(p, n_p, "group", 0));
const uint32_t D = act_dt(p, n_p);
Opd o;
if (gi(p, n_p, "gated", 0)) {
o.t(D, { M, n }); /* y */
o.t(D, { 1, n }); /* g */
} else {
o.skip();
o.skip();
}
o.t(D, { 1, 2 * n }); /* s */
const char* nk = gs(p, n_p, "norm");
if (nk && std::strcmp(nk, "layer") == 0) o.skip(); /* w: a LayerNorm without a gain */
else o.t(D, { n }); /* w */
o.t_idx({ 2 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_seqlens */
o.t(D, { M, n }); /* x, INOUT */
o.t((uint32_t)RAD_F8E4M3, { M, n }); /* q */
o.t((uint32_t)RAD_F32, { M, ng }); /* scale */
o.t(D, { M, n }); /* z */
o.skip(); /* colmap: the sweep passes none */
return o.finish("rms_mod_quant_fp8", operand, out);
}
/* The sampler's three scalars in (0, 1), the state f32. */
int ref_flow_x0_step_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);
@@ -3948,6 +3927,25 @@ int ref_resample_nearest_shape(const RadParam* p, int n_p, int operand, RadOpdDe
return o.finish("resample_nearest", operand, out);
}
int ref_elu_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);
if (M <= 0 || n <= 0) return RAD_E_UNSUPPORTED;
Opd o;
o.t(act_dt(p, n_p), {M, n});
o.t(act_dt(p, n_p), {M, n});
return o.finish("elu", operand, out);
}
int ref_vq_euclidean_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), bins = gi(p, n_p, "bins", 0);
if (M <= 0 || n <= 0 || bins <= 0) return RAD_E_UNSUPPORTED;
Opd o;
o.t(act_dt(p, n_p), {M, n});
o.t(act_dt(p, n_p), {bins, n});
o.t_idx({M}, bins, -1, 0);
return o.finish("vq_euclidean", operand, out);
}
int ref_fourier_embed_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);
if (M <= 0 || n <= 0 || (n & 1)) return RAD_E_UNSUPPORTED;