ops: attn_dense at head_dim 80 and grid_embed_cpe, for the C-RADIO tower

attn_dense at head_dim 80 without GQA (C-RADIO's ViT heads), and grid_embed_cpe, RADIO's cropped
position embedding: the table resampled half-pixel bilinear onto a square and cropped to the
grid, with the class and register rows ahead of each segment. libref, libavx and libr4d; ref_test,
avx_check_hand and selftest cases; docs/OPS.md.
This commit is contained in:
keptn42 committed 2026-11-04 22:08:53 +01:00
1 parent 2420b2b383
commit b466c91b26
17 files changed
+426 -2

No files matched your search

+9
View File
@@ -205,6 +205,7 @@ at once. Run it before adding a kernel plugin; the loader names only the first c
| `layernorm` | `M`(range) `n` `eps`:f64 `dtype` | `x`, `w`w, `b`w? → `y` |
| `grid_embed` | `M`(range) `n` `side` `dtype` | `x`:inout, `table`w, `coord` |
| `grid_embed_aa` | `M`(range) `n` `side` `dtype` | `x`:inout, `table`w, `coord` |
| `grid_embed_cpe` | `M`(range) `n` `side` `dtype` `n_prefix`/opt | `x`:inout, `table`w, `coord`, `prefix`w? |
| `add` | `M`(range) `n` `dtype` `div`:f64/opt | `a`, `b` → `y` |
| `mul` | `M`(range) `n` `dtype` | `a`, `b` → `y` |
| `silu_mul` | `M`(range) `n` `dtype` | `gate_up` → `y` (splits `[M,2n]` into gate·up) |
@@ -342,6 +343,14 @@ half-pixel centres, widened by the scale when the grid is smaller than the table
normalised to sum to one; separable, f32, rounded once. A different function from `grid_embed`'s,
so a different op rather than a mode a library could ignore.
**`grid_embed_cpe`** is RADIO's cropped position embedding: the table resampled with
`F.interpolate(mode="bilinear", align_corners=False)` and no antialias onto a square whose side is
the grid's larger one, of which the grid keeps the top-left `h x w`. Per axis two taps at
`(i + 0.5) * side / d - 0.5`, clamped at 0 and into the table, blended along the row first as torch's
kernel does; f32, rounded once before the add. A row whose row coordinate is negative is one of
`n_prefix` learned rows a segment carries ahead of its patches (RADIO's class and register tokens),
the column naming which: it gets `prefix[k]` instead.
### Hyper-connections
`hc_project` is the control vector's projection (core/cvec.h): `h[s] -= scale * (h[s] . v) * v`
+4
View File
@@ -674,6 +674,10 @@ std::vector<Case> build_cases() {
* avx_check's hand-built case. */
add("grid_embed_aa", { HI("M", 20), HI("n", 72), HI("side", 16), HS("dtype", dt) });
add("grid_embed_aa", { HI("M", 40), HI("n", 72), HI("side", 4), HS("dtype", dt) });
add("grid_embed_cpe", { HI("M", 20), HI("n", 72), HI("side", 16), HS("dtype", dt) });
add("grid_embed_cpe", { HI("M", 40), HI("n", 72), HI("side", 4), HS("dtype", dt) });
add("grid_embed_cpe", { HI("M", 24), HI("n", 72), HI("side", 8), HI("n_prefix", 3),
HS("dtype", dt) });
}
/* LiLiCorr's lattice ops, at its geometry (7 positions of 8 candidates, 8 heads) narrowed in
+12
View File
@@ -544,6 +544,18 @@ void shape_cases(std::vector<Hand>& hs) {
.pi("M", 6).pi("n", N).pi("side", 4).ps("dtype", "f32");
hs.push_back(std::move(ga));
/* RADIO's cropped resample: two prefix rows (row -1, the column naming which), three of a
* 3 x 5 grid upsampling the 4 x 4 table and one of a 2 x 2 grid shrinking it. */
static const int32_t kCpeCrd[4][6] = { { -1, -1, 0, 2, 1, 0 }, { 0, 2, 0, 4, 3, 1 },
{ 3, 3, 3, 3, 3, 2 }, { 5, 5, 5, 5, 5, 2 } };
Hand gc("prefix rows and a 4 x 4 table onto 3 x 5 and 2 x 2 grids", "grid_embed_cpe", 1e-6);
gc.dense(RAD_F32, { 6, N }, hfill(61), true)
.dense(RAD_F32, { 16, N }, hfill(62))
.dense(RAD_I32, { 4, 6 }, [](int64_t i) { return (float)kCpeCrd[i / 6][i % 6]; })
.dense(RAD_F32, { 3, N }, hfill(63))
.pi("M", 6).pi("n", N).pi("side", 4).pi("n_prefix", 3).ps("dtype", "f32");
hs.push_back(std::move(gc));
/* LiLiCorr's candidates over two ranks' sample_logprobs rows: a merge that interleaves the
* ranks, an equal value on both (the lower id first), a rank with an unfilled slot. Rows
* of (max, sum, 4 (id, logit) pairs descending) a rank, k = 4, steps 3, n = 24. */
+1
View File
@@ -85,6 +85,7 @@ int avx_par_force(int threads);
X(mla_attn) \
X(mla_attn_paged) \
X(add) X(grid_embed) X(grid_embed_aa) X(causal_conv1d) \
X(grid_embed_cpe) \
X(lili_cand) X(lili_attn) X(lili_factor) X(lili_walk) \
X(mul) X(silu_mul) X(gelu_mul) X(gelu) \
X(silu) X(sigmoid) X(logit_softcap) X(gather_rows) \
+67
View File
@@ -352,3 +352,70 @@ AVX_KERNEL(grid_embed_aa) {
}
return RAD_OK;
}
/* ------------------------------------------------------------------ grid_embed_cpe */
/* Adds the table resampled as torch's F.interpolate(bilinear, align_corners=False) does without
* antialias, onto a square of the grid's larger side and cropped to the grid (RADIO's cropped
* position embedding); matches libref's grid_embed_cpe operation for operation. */
static void cpe_taps(int64_t at, int64_t d, int64_t side, int64_t t[2], float w[2]) {
if (d < 1) d = 1;
at = at < 0 ? 0 : (at >= d ? d - 1 : at);
float src = (float)side / (float)d * ((float)at + 0.5f) - 0.5f;
if (src < 0.0f) src = 0.0f;
int64_t i0 = (int64_t)src;
if (i0 > side - 1) i0 = side - 1;
t[0] = i0;
t[1] = i0 < side - 1 ? i0 + 1 : i0;
w[1] = src - (float)i0;
w[0] = 1.0f - w[1];
}
AVX_KERNEL(grid_embed_cpe) {
if (!rad_args_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);
/* The prefix rows, when n_prefix names some; without it the operand is not read. */
const int64_t npre = p_int(a, "n_prefix", 0);
const RadTensor* pre = npre > 0 && a->n_t > 3 && a->t[3].data ? &a->t[3] : nullptr;
if (npre > 0 && (!pre || numel(pre) < npre * n)) return RAD_E_SHAPE;
AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN)
for (int64_t r = 0; r < rows; ++r) {
int64_t g[4];
for (int c = 0; c < 4; ++c) g[c] = ldi(crd, c * cs + r * ms);
if (g[0] < 0) {
/* A row ahead of its segment's patches: the learned row its column names. */
const int64_t k = g[1] < 0 ? 0 : (g[1] >= npre ? npre - 1 : g[1]);
const int64_t xb0 = rowoff(x, r, n), xs0 = laststride(x);
for (int64_t i = 0; npre > 0 && i < n; ++i) {
const float pe = round_act(x->dtype, ldt(pre, rowoff(pre, k, n) + i * laststride(pre)));
stt(x, xb0 + i * xs0, ldt(x, xb0 + i * xs0) + pe);
}
continue;
}
const int64_t d = g[2] > g[3] ? g[2] : g[3];
int64_t th[2], tw[2];
float wh[2], ww[2];
cpe_taps(g[0], d, side, th, wh);
cpe_taps(g[1], d, side, tw, ww);
const int64_t xb = rowoff(x, r, n), xs = laststride(x);
auto at = [&](int64_t y, int64_t c, int64_t i) {
return ldt(tab, rowoff(tab, y * side + c, n) + i * ts);
};
for (int64_t i = 0; i < n; ++i) {
const float r0 = ww[0] * at(th[0], tw[0], i) + ww[1] * at(th[0], tw[1], i);
const float r1 = ww[0] * at(th[1], tw[0], i) + ww[1] * at(th[1], tw[1], i);
const float pe = round_act(x->dtype, wh[0] * r0 + wh[1] * r1);
stt(x, xb + i * xs, ldt(x, xb + i * xs) + pe);
}
}
return RAD_OK;
}
+10
View File
@@ -144,6 +144,9 @@ static const RadParamSpec pLayernorm[] = { P_INT("M"), P_INT("n"), P_F64("eps"
static const RadOperandSpec oLayernorm[] = { OPD("x"), WGT("w"), WGT_O("b"), OUT("y") };
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") };
static const RadParamSpec pGridEmbedCpe[] = { P_INT("M"), P_INT("n"), P_INT("side"), P_STR("dtype"),
P_INTO("n_prefix") };
static const RadOperandSpec oGridEmbedCpe[] = { INOUT("x"), WGT("table"), OPD("coord"), WGT_O("prefix") };
/* LiLiCorr's correlator (avx_lili.cpp; libref/ref_lili.cpp has the contracts). */
static const RadParamSpec pLiliCand[] = { P_INT("M"), P_INT("k"), P_INT("world"), P_INT("steps"),
P_INT("n"), P_STR("dtype"), P_F64O("eps"),
@@ -1016,6 +1019,10 @@ static const RadOpSchema kSchemas[] = {
"[h | a | h * a] a lattice row, a its sequence's anchor." },
{ "lili_walk", ARR(pLiliWalk), ARR(oLiliWalk),
"LiLiCorr's normalised edge scores and their greedy walk." },
{ "grid_embed_cpe", ARR(pGridEmbedCpe), ARR(oGridEmbedCpe),
"x += the table resampled half-pixel bilinear (no antialias) onto a square of the grid's larger "
"side and cropped to the grid: RADIO's cropped position embedding. A row with a negative row "
"coordinate gets the learned prefix row its column names." },
{ "add", ARR(pAdd), ARR(oBinary),
"y = a + b; a `b` of exactly n elements against a taller output broadcasts along rows. With "
"`div`, y = rd(rd(a + b) / div), bit for bit libref's." },
@@ -1681,6 +1688,9 @@ SIMPLE("avx_grid_embed", "grid_embed", "elem",
SIMPLE("avx_grid_embed_aa", "grid_embed_aa", "elem",
"antialiased half-pixel bilinear resample of a position grid, added in", DT_FLOAT,
L(grid_embed_aa)),
SIMPLE("avx_grid_embed_cpe", "grid_embed_cpe", "elem",
"half-pixel bilinear resample of a position grid onto a square, cropped, added in", DT_FLOAT,
L(grid_embed_cpe)),
SIMPLE("avx_lili_cand", "lili_cand", "draft", "LiLiCorr candidates and their features", DT_FLOAT,
L(lili_cand)),
SIMPLE("avx_lili_attn", "lili_attn", "draft", "LiLiCorr lattice attention with slot biases",
+6 -1
View File
@@ -2,7 +2,7 @@
// an optional two-sided window, i - j < window behind and j - i < wright ahead (wright is
// `window_right`, or `window` for the symmetric |i - j| < window), or causal with an optional
// window behind (a codec's sliding layers, a text encoder's prompt). bf16 in and out, f16
// operands, f32 accumulate. Head widths 64, 256 and 512 are compiled; each (head_dim, gqa) pair
// operands, f32 accumulate. Head widths 64, 80, 256 and 512 are compiled; each (head_dim, gqa) pair
// is a row.
//
// Core from the vision kernel (r4d_attn_vit_h72_bf16.hip): S^T = K.Q^T, so the wave32
@@ -304,6 +304,7 @@ void r4d_attn_dense_kernel(const uint16_t* __restrict__ gq, const uint16_t* __re
// ---- launch ----------------------------------------------------------------------------------
// One instantiation per (head_dim, gqa), at a workgroup shape picked for it:
// h64 gqa1: 8 query blocks of 16, K/V tiles of 64 keys (the vision towers' heads)
// h80 gqa1: the same shape, five 16-wide k-tiles a head (C-RADIO's heads)
// h256 gqa1: 8 query blocks of 16, tiles of 32 (LDS: 37 KiB)
// h256 gqa2, 4, 8: 8, 4, 2 query blocks x the heads, tiles of 32 (LDS: 37 KiB)
// h512 gqa2, 4, 8: 4, 2, 1 query blocks x the heads x 2 head halves, tiles of 16 (LDS: 57 KiB)
@@ -353,6 +354,10 @@ extern "C" int r4d_attn_dense_bf16(const void* q, const void* k, const void* v,
return r4d_attn_dense_launch<64, 1, 8, 1, 64>(q, k, v, o, cu_seqlens, num_seqs, max_seqlen,
n_head_kv, scale, window, wright, block,
cdiv, causal, q_ld, k_ld, v_ld, o_ld, s);
if (head_dim == 80 && gqa == 1)
return r4d_attn_dense_launch<80, 1, 8, 1, 64>(q, k, v, o, cu_seqlens, num_seqs, max_seqlen,
n_head_kv, scale, window, wright, block,
cdiv, causal, q_ld, k_ld, v_ld, o_ld, s);
#define R4D_DENSE(HD, G, NQB, DS, T) \
return r4d_attn_dense_launch<HD, G, NQB, DS, T>(q, k, v, o, cu_seqlens, num_seqs, max_seqlen, \
n_head_kv, scale, window, wright, block, \
+2
View File
@@ -902,6 +902,7 @@ int r4d_rad_rope_rows (const RadArgs*, RadStream);
int r4d_rad_layernorm (const RadArgs*, RadStream);
int r4d_rad_grid_embed (const RadArgs*, RadStream);
int r4d_rad_grid_embed_aa (const RadArgs*, RadStream);
int r4d_rad_grid_embed_cpe (const RadArgs*, RadStream);
int r4d_rad_gemm_nt_bias (const RadArgs*, RadStream);
/* gemm_nt_bias at f32 (r4d_gemm_f32_nt_bias.hip). */
int r4d_rad_gemm_f32_nt_bias(const RadArgs*, RadStream);
@@ -969,6 +970,7 @@ int r4d_shape_mul_weight (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_scatter_rows_bf16(const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_layernorm (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_grid_embed (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_grid_embed_cpe (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_gemm_nt_bias (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_unary (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_fill (const RadParam*, int, int operand, RadOpdDesc*);
+39
View File
@@ -2203,6 +2203,16 @@ static const RadOperandSpec oGridEmbed[] = {
{ "table", RAD_OPD_WEIGHT, 0 },
{ "coord", RAD_OPD_IN, 0 },
};
static const RadParamSpec pGridEmbedCpe[] = {
P_INT("M"), P_INT("n"), P_INT("side"), P_STR("dtype"),
{ "n_prefix", RAD_P_INT, RAD_OPTIONAL },
};
static const RadOperandSpec oGridEmbedCpe[] = {
{ "x", RAD_OPD_INOUT, 0 },
{ "table", RAD_OPD_WEIGHT, 0 },
{ "coord", RAD_OPD_IN, 0 },
{ "prefix", RAD_OPD_WEIGHT, 1 },
};
static const RadParamSpec pGemmBias[] = {
P_INT("M"), P_INT("N"), P_INT("K"), P_STR("dtype"),
{ "act", RAD_P_STR, RAD_OPTIONAL },
@@ -3291,6 +3301,12 @@ static const RadOpSchema kSchemas[] = {
"position embedding: per axis a triangle filter on half-pixel centres, widened by the "
"scale when shrinking, its in-table taps normalised. Separable, f32, rounded once "
"before the add; coordinates clamp into their grid."),
SCHEMA("grid_embed_cpe", pGridEmbedCpe, oGridEmbedCpe,
"x += the side x side table resampled as torch's F.interpolate(bilinear, "
"align_corners=False) -- no antialias -- onto a square of side max(grid height, grid "
"width), of which the grid keeps the top-left part: RADIO's cropped position embedding. "
"Two taps an axis, the row blended first; f32, rounded once before the add. A row "
"whose row coordinate is negative gets the learned prefix row its column names."),
SCHEMA("gemm_nt_bias", pGemmBias, oGemmBias,
"y = res + act(a @ b^T + bias), rounded to bf16 after the biased product, after the "
"activation and after the residual -- the unfused chain's three tensors."),
@@ -4681,6 +4697,10 @@ static const RadConstraint cCastNarrow[] = {
static const RadConstraint cAttnDenseH64[] = {
C_EQ("head_dim", 64), C_EQ("gqa", 1), C_IN("dtype", "bf16"),
};
/* head_dim 80 without GQA: C-RADIO's ViT heads (Nemotron-3.5-Bolt's vision tower), bidirectional. */
static const RadConstraint cAttnDenseH80[] = {
C_EQ("head_dim", 80), C_EQ("gqa", 1), C_IN("dtype", "bf16"),
};
/* head_dim 256 without GQA, sequences past the small kernel's. */
static const RadConstraint cAttnDenseH256G1[] = {
C_EQ("head_dim", 256), C_EQ("gqa", 1), C_GE("max_seqlen", 33), C_IN("dtype", "bf16"),
@@ -6428,6 +6448,15 @@ static const RadKernelInfo kKernels[] = {
nullptr, nullptr, r4d_rad_grid_embed_aa, nullptr, nullptr, nullptr,
r4d_shape_grid_embed },
{ "grid_embed_cpe_bf16", "grid_embed_cpe", "elem",
"a learned position grid resampled half-pixel bilinear onto a square and cropped (RADIO's CPE)",
"any n and side; coord [4, M] dense; one workgroup a row",
"bf16 x, bf16 or f32 table, i32 coord, f32 taps",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cGridEmbed), NOTUNE,
nullptr, nullptr, r4d_rad_grid_embed_cpe, nullptr, nullptr, nullptr,
r4d_shape_grid_embed_cpe },
{ "gemm_bf16_nt_bias_tiled", "gemm_nt_bias", "gemm",
"biased GEMM C = res + act(A @ W^T + bias) over 64-deep K tiles, the K tail staged as zeros, "
"the activation and residual in the store: from 32 blocks of 128x128 the weight read straight "
@@ -7978,6 +8007,16 @@ R4D_WIN_TREE_PAIR(512, 4) R4D_WIN_TREE_PAIR(512, 8)
ROW(cAttnDenseH64), NOTUNE,
nullptr, nullptr, r4d_rad_attn_dense },
{ "attn_dense_h80_bf16", "attn_dense", "attn",
"dense varlen attention over cu_seqlens: bidirectional with an optional two-sided window or "
"blocks, or causal with an optional window behind",
"head_dim 80, multi-head (no GQA), q/k/v/o at their own token pitches (column slices of a "
"fused projection allowed)",
"bf16 query / key / value / out, f16 operands, fp32 accumulate",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cAttnDenseH80), NOTUNE,
nullptr, nullptr, r4d_rad_attn_dense },
{ "attn_dense_h256_bf16", "attn_dense", "attn",
"dense varlen attention over cu_seqlens: bidirectional with an optional two-sided window or "
"blocks, or causal with an optional window behind",
+35
View File
@@ -10108,6 +10108,40 @@ void attn_dense_gqa_cases(const Plugin& pl) {
}
}
/* attn_dense_h80_bf16: C-RADIO's tower, 16 heads of 80 over a fused [q|k|v] row, two images. */
void attn_dense_h80_cases(const Plugin& pl) {
const RadKernelInfo* r = find(pl, "attn_dense_h80_bf16");
if (!r) { ok("attn_dense_h80_bf16", false, "row absent"); return; }
const int64_t hd = 80, nh = 16, w = nh * hd, total = 333;
const std::vector<int32_t> cu = { 0, 197, 333 };
std::vector<float> qkv = randv((size_t)(total * 3 * w), 1.0f);
for (float& x : qkv) x = bfr(x);
void* d = up_bf16(qkv);
auto col = [&](int c) {
RadTensor t = T((char*)d + c * w * 2, RAD_BF16, { total, w });
t.stride[0] = 3 * w;
return t;
};
void* dout = dalloc((size_t)(total * w) * 2);
const int rc = launch(r, { col(0), col(1), col(2), T(up_i32(cu), RAD_I32, { 3 }),
T(dout, RAD_BF16, { total, w }) },
{ PI("M", total), PI("head_dim", hd), PI("gqa", 1), PI("causal", 0),
PS("dtype", "bf16"), PI("max_seqlen", 197) });
if (rc != RAD_OK) { ok("attn_dense_h80_bf16", false, "rc " + std::to_string(rc)); return; }
std::vector<float> q((size_t)(total * w)), k((size_t)(total * w)), v((size_t)(total * w));
for (int64_t i = 0; i < total; ++i)
for (int64_t t = 0; t < w; ++t) {
q[(size_t)(i * w + t)] = qkv[(size_t)(i * 3 * w + t)];
k[(size_t)(i * w + t)] = qkv[(size_t)(i * 3 * w + w + t)];
v[(size_t)(i * w + t)] = qkv[(size_t)(i * 3 * w + 2 * w + t)];
}
std::vector<float> want((size_t)(total * w));
for (int e = 0; e < 2; ++e)
host_attn(q, k, v, w, w, nh, nh, hd, cu[(size_t)e], cu[(size_t)e + 1], cu[(size_t)e],
cu[(size_t)e + 1], false, &want);
check("attn_dense_h80_bf16 16 heads over two images", down_bf16(dout, want.size()), want, 2e-2);
}
/* One wide head over every pixel, 384 and 512. */
void attn_wide_cases(const Plugin& pl) {
for (const int64_t hd : { 384, 512 }) {
@@ -32981,6 +33015,7 @@ static void device_phase(const Plugin& pl) {
if (sel("attn_cross_h128_bf16")) g3::attn_cross_cases(pl, 128);
if (sel("attn_cross_h64_bf16")) g3::attn_cross_cases(pl, 64);
if (sel("attn_dense_gqa")) g3::attn_dense_gqa_cases(pl);
if (sel("attn_dense_h80_bf16")) g3::attn_dense_h80_cases(pl);
if (sel("attn_dense_h384_bf16") || sel("attn_dense_h512_bf16")) g3::attn_wide_cases(pl);
if (sel("rms_mod_bf16") || sel("rms_mod_quant_fp8_bf16")) g3::rms_mod_forms(pl);
if (sel("timestep_embed_bf16")) g3::timestep_round_cases(pl);
+10
View File
@@ -372,6 +372,16 @@ extern "C" int r4d_shape_grid_embed(const RadParam* p, int n_p, int operand, Rad
R4D_PICK(l);
}
/* grid_embed's operands plus the prefix rows (RADIO's class and register tokens). */
extern "C" int r4d_shape_grid_embed_cpe(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n"), side = pi(p, n_p, "side");
const int64_t npre = rad_param_geti(p, n_p, "n_prefix", 1);
const uint32_t D = dt_act(p, n_p, "dtype");
const RadOpdDesc l[] = { opd(D, M, n), opd(D, side * side, n), opd_idx(4, M, side),
opd(D, npre > 0 ? npre : 1, n) };
R4D_PICK(l);
}
extern "C" int r4d_shape_gemm_nt_bias(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = pi(p, n_p, "M"), N = pi(p, n_p, "N"), K = pi(p, n_p, "K");
const uint32_t D = dt_act(p, n_p, "dtype");
+83
View File
@@ -170,6 +170,54 @@ __global__ __launch_bounds__(kThr) void grid_embed_aa_kernel(
}
}
// ---------------------------------------------------------------------------- grid_embed_cpe
// ref_grid_embed_cpe: RADIO's cropped position embedding, torch's half-pixel bilinear without
// antialias onto a square of the grid's larger side, cropped to the grid. Two taps an axis, the
// row blended first as libref does; rounded once before the add.
__device__ __forceinline__ void cpe_taps(int at, int d, int side, int* t, float* w) {
d = d < 1 ? 1 : d;
at = at < 0 ? 0 : (at >= d ? d - 1 : at);
float src = (float)side / (float)d * ((float)at + 0.5f) - 0.5f;
src = src < 0.0f ? 0.0f : src;
int i0 = (int)src;
i0 = i0 > side - 1 ? side - 1 : i0;
t[0] = i0;
t[1] = i0 < side - 1 ? i0 + 1 : i0;
w[1] = src - (float)i0;
w[0] = 1.0f - w[1];
}
template <bool TF32>
__global__ __launch_bounds__(kThr) void grid_embed_cpe_kernel(
unsigned short* __restrict__ x, const void* __restrict__ tab, const int32_t* __restrict__ crd,
uint32_t n, int side, uint32_t x_ld, uint32_t plane, const unsigned short* __restrict__ pre,
int npre) {
const uint32_t m = blockIdx.x;
const int g[4] = { crd[m], crd[plane + m], crd[2 * plane + m], crd[3 * plane + m] };
unsigned short* __restrict__ xr = x + (size_t)m * x_ld;
if (g[0] < 0) {
// A row ahead of its segment's patches: the learned bf16 row its column names.
if (!pre || npre <= 0) return;
const int k = g[1] < 0 ? 0 : (g[1] >= npre ? npre - 1 : g[1]);
for (uint32_t i = threadIdx.x; i < n; i += kThr)
xr[i] = f32_to_bf16(bf2f(xr[i]) + bf2f(pre[(size_t)k * n + i]));
return;
}
const int d = g[2] > g[3] ? g[2] : g[3];
int th[2], tw[2];
float wh[2], ww[2];
cpe_taps(g[0], d, side, th, wh);
cpe_taps(g[1], d, side, tw, ww);
for (uint32_t i = threadIdx.x; i < n; i += kThr) {
const float r0 = ww[0] * ldw<TF32>(tab, (uint32_t)(th[0] * side + tw[0]) * n + i) +
ww[1] * ldw<TF32>(tab, (uint32_t)(th[0] * side + tw[1]) * n + i);
const float r1 = ww[0] * ldw<TF32>(tab, (uint32_t)(th[1] * side + tw[0]) * n + i) +
ww[1] * ldw<TF32>(tab, (uint32_t)(th[1] * side + tw[1]) * n + i);
const float pe = bf2f(f32_to_bf16(wh[0] * r0 + wh[1] * r1));
xr[i] = f32_to_bf16(bf2f(xr[i]) + pe);
}
}
// ---------------------------------------------------------------------------- gemm_nt_bias
#define VB_BK 64
#define VB_PITCH (VB_BK + 8) // 144-byte LDS rows, as in gemm_bf16_nt_tiled (bank spread)
@@ -621,6 +669,41 @@ extern "C" int r4d_rad_grid_embed_aa(const RadArgs* a, RadStream stream) {
(uint32_t)n, (int)side, (uint32_t)x_ld, plane);
}
/* grid_embed_cpe: grid_embed's operands and checks, RADIO's cropped resample. */
extern "C" int r4d_rad_grid_embed_cpe(const RadArgs* a, RadStream stream) {
const RadTensor* x = r4d_opt(a, GE_X);
const RadTensor* tab = r4d_opt(a, GE_TAB);
const RadTensor* crd = r4d_opt(a, GE_CRD);
if (!x || !tab || !crd) return R4D_NO(RAD_E_INVAL);
if (x->dtype != RAD_BF16 || crd->dtype != RAD_I32) return R4D_NO(RAD_E_DTYPE);
if (tab->dtype != RAD_BF16 && tab->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE);
if (!r4d_contig(tab)) return R4D_NO(RAD_E_STRIDE);
const long long n = r4d_geti_or(a, "n", r4d_dim(tab, (int)tab->rank - 1));
const long long side = r4d_geti_or(a, "side", 0);
if (n <= 0 || side <= 0 || r4d_numel(tab) < side * side * n) return R4D_NO(RAD_E_SHAPE);
long long M = 0;
const long long x_ld = r4d_rows_pitch(x, n, &M);
if (x_ld < 0) return R4D_NO(RAD_E_STRIDE);
if (crd->rank != 2 || crd->shape[0] < 4 || crd->shape[1] < M || !r4d_contig(crd))
return R4D_NO(RAD_E_SHAPE);
if (M <= 0) return R4D_NO(RAD_E_SHAPE);
const uint32_t plane = (uint32_t)crd->shape[1];
/* The prefix rows: bf16, contiguous, n_prefix rows of n. */
const long long npre = r4d_geti_or(a, "n_prefix", 0);
const RadTensor* pre = npre > 0 ? r4d_opt(a, 3) : nullptr;
if (npre > 0 && (!pre || pre->dtype != RAD_BF16 || !r4d_contig(pre) ||
r4d_numel(pre) < npre * n))
return R4D_NO(pre && pre->dtype != RAD_BF16 ? RAD_E_DTYPE : RAD_E_SHAPE);
const unsigned short* pp = pre ? (const unsigned short*)r4d_p(pre) : nullptr;
if (tab->dtype == RAD_F32)
return R4D_EMIT(stream, grid_embed_cpe_kernel<true>, dim3((uint32_t)M), dim3(kThr), 0,
(unsigned short*)r4d_wp(x), r4d_p(tab), (const int32_t*)r4d_p(crd),
(uint32_t)n, (int)side, (uint32_t)x_ld, plane, pp, (int)npre);
return R4D_EMIT(stream, grid_embed_cpe_kernel<false>, dim3((uint32_t)M), dim3(kThr), 0,
(unsigned short*)r4d_wp(x), r4d_p(tab), (const int32_t*)r4d_p(crd),
(uint32_t)n, (int)side, (uint32_t)x_ld, plane, pp, (int)npre);
}
/* ------------------------------------------------------------------ gemm_nt_bias */
enum { GB_A = 0, GB_W, GB_BIAS, GB_RES, GB_Y };
+67
View File
@@ -249,6 +249,73 @@ int ref_grid_embed_aa(const RadArgs* a, RadStream) {
return RAD_OK;
}
/* grid_embed_cpe: RADIO's cropped position embedding (CPE). The table resampled as torch's
* F.interpolate(mode="bilinear", align_corners=False) -- without antialias -- onto a square of side
* d = max(grid height, grid width), of which the grid keeps the top-left h x w. Per axis two taps at
* src = (i + 0.5) * side / d - 0.5, clamped at 0, the upper tap clamped into the table, and blended
* along the row first as torch's bilinear kernel does. f32, rounded once before the add. */
static void cpe_taps(int64_t at, int64_t d, int64_t side, int64_t t[2], float w[2]) {
if (d < 1) d = 1;
at = at < 0 ? 0 : (at >= d ? d - 1 : at);
float src = (float)side / (float)d * ((float)at + 0.5f) - 0.5f;
if (src < 0.0f) src = 0.0f;
int64_t i0 = (int64_t)src;
if (i0 > side - 1) i0 = side - 1;
t[0] = i0;
t[1] = i0 < side - 1 ? i0 + 1 : i0;
w[1] = src - (float)i0;
w[0] = 1.0f - w[1];
}
int ref_grid_embed_cpe(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);
/* The prefix rows, when n_prefix names some; without it the operand is not read. */
const int64_t npre = p_int(a, "n_prefix", 0);
const RadTensor* pre = npre > 0 && a->n_t > 3 && a->t[3].data ? &a->t[3] : nullptr;
if (npre > 0 && (!pre || numel(pre) < npre * n)) return RAD_E_SHAPE;
REF_PAR_FOR(rows * n * 4)
for (int64_t r = 0; r < rows; ++r) {
int64_t g[4];
for (int c = 0; c < 4; ++c) g[c] = ld_int(crd->dtype, crd->data, c * cs + r * ms);
const int64_t xb0 = rowoff(x, r, n), xs0 = laststride(x);
if (g[0] < 0) {
/* A row ahead of its segment's patches: the learned row its column names. */
const int64_t k = g[1] < 0 ? 0 : (g[1] >= npre ? npre - 1 : g[1]);
for (int64_t i = 0; npre > 0 && i < n; ++i) {
const float pe = round_dt(x->dtype, ldt(pre, rowoff(pre, k, n) + i * laststride(pre)));
stt(x, xb0 + i * xs0, ldt(x, xb0 + i * xs0) + pe);
}
continue;
}
const int64_t d = g[2] > g[3] ? g[2] : g[3];
int64_t th[2], tw[2];
float wh[2], ww[2];
cpe_taps(g[0], d, side, th, wh);
cpe_taps(g[1], d, side, tw, ww);
const int64_t xb = rowoff(x, r, n), xs = laststride(x);
auto at = [&](int64_t y, int64_t c, int64_t i) {
return ldt(tab, rowoff(tab, y * side + c, n) + i * ts);
};
for (int64_t i = 0; i < n; ++i) {
const float r0 = ww[0] * at(th[0], tw[0], i) + ww[1] * at(th[0], tw[1], i);
const float r1 = ww[0] * at(th[1], tw[0], i) + ww[1] * at(th[1], tw[1], i);
const float pe = round_dt(x->dtype, wh[0] * r0 + wh[1] * r1);
stt(x, xb + i * xs, ldt(x, xb + i * xs) + pe);
}
}
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
+2
View File
@@ -73,6 +73,7 @@ int ref_mtp_enter (const RadArgs*, RadStream);
int ref_layernorm (const RadArgs*, RadStream);
int ref_grid_embed (const RadArgs*, RadStream);
int ref_grid_embed_aa (const RadArgs*, RadStream);
int ref_grid_embed_cpe (const RadArgs*, RadStream);
int ref_lili_cand (const RadArgs*, RadStream);
int ref_lili_attn (const RadArgs*, RadStream);
int ref_lili_factor (const RadArgs*, RadStream);
@@ -364,6 +365,7 @@ REF_SHAPE_FN(ref_mtp_enter);
REF_SHAPE_FN(ref_layernorm);
REF_SHAPE_FN(ref_grid_embed);
REF_SHAPE_FN(ref_grid_embed_aa);
REF_SHAPE_FN(ref_grid_embed_cpe);
REF_SHAPE_FN(ref_lili_cand);
REF_SHAPE_FN(ref_lili_attn);
REF_SHAPE_FN(ref_lili_factor);
+15
View File
@@ -172,6 +172,12 @@ 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") };
/* 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") };
static const RadOperandSpec oGridEmbedCpe[] = { INOUT("x"), WGT("table"), OPD("coord"),
WGT_O("prefix") };
/* LiLiCorr's correlator (ref_lili.cpp). */
static const RadParamSpec pLiliCand[] = { P_INT("M"), P_INT("k"), P_INT("world"), P_INT("steps"),
P_INT("n"), P_STR("dtype"), P_F64O("eps"),
@@ -1220,6 +1226,12 @@ static const RadOpSchema kSchemas[] = {
"antialias=True) resamples it to the row's grid -- SigLIP2's position embedding: per axis a "
"triangle filter on half-pixel centres, widened by the scale when shrinking, its in-table taps "
"normalised. Separable, f32, rounded once before the add; coordinates clamp into their grid." },
{ "grid_embed_cpe", ARR(pGridEmbedCpe), ARR(oGridEmbedCpe),
"x += the side x side table resampled as torch's F.interpolate(bilinear, align_corners=False) -- "
"no antialias -- onto a square of side max(grid height, grid width), of which the grid keeps the "
"top-left part: RADIO's cropped position embedding (CPE). Per axis two taps at (i + 0.5) * side / "
"d - 0.5, clamped at 0 and into the table, blended along the row first; f32, rounded once before "
"the add. A row whose coordinate row is negative is the k-th of `n_prefix` learned rows ahead of its segment (RADIO's class and register tokens), k its column: it gets `prefix[k]` instead, rounded the same way." },
{ "lili_cand", ARR(pLiliCand), ARR(oLiliCand),
"LiLiCorr's candidates. `stats` [M, world * (2 + 2k)] f32 is each rank's sample_logprobs row, "
"row-interleaved; the ranks merge to the log-normaliser and the k largest pairs by value, ties to "
@@ -2363,6 +2375,9 @@ SIMPLE("ref_grid_embed", "grid_embed", "elem",
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),
SIMPLE("ref_grid_embed_cpe", "grid_embed_cpe", "elem",
"half-pixel bilinear resample of a position grid onto a square, cropped, added in", DT_FLOAT,
ref_grid_embed_cpe),
SIMPLE("ref_lili_cand", "lili_cand", "draft", "LiLiCorr candidates and their features",
DT_FLOAT, ref_lili_cand),
SIMPLE("ref_lili_attn", "lili_attn", "draft", "LiLiCorr lattice attention with slot biases",
+14
View File
@@ -509,6 +509,20 @@ 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'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);
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0), side = gi(p, n_p, "side", 0);
const int64_t npre = gi(p, n_p, "n_prefix", 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);
o.t(D, { npre > 0 ? npre : 1, n }); /* prefix */
return o.finish("grid_embed_cpe", operand, out);
}
/* LiLiCorr's ops. lili_cand declines: its stats rows (sample_logprobs' sorted pairs and positive
* sums) are no draw; avx_check_hand.cpp builds them. The others draw freely. */
int ref_lili_cand_shape(const RadParam*, int, int, RadOpdDesc*) { return RAD_E_UNSUPPORTED; }
+50 -1
View File
@@ -1225,7 +1225,7 @@ TEST(op_vocabulary) {
"gemm_nt", "gemm_nt_bias", "gemm_nt_q", "gemm_nt_q_bias", "grid_embed",
/* Runtime LoRA's two halves, issued by the core beside a trunk GEMM. */
"lora_shrink", "lora_expand", "lora_expand_mm",
"grid_embed_aa",
"grid_embed_aa", "grid_embed_cpe",
"attn_paged", "attn_dense", "kv_store", "kv_store_streamed", "rope", "rope_table",
"attn_paged_sink",
"qk_norm_rope", "qsa_block_key",
@@ -2024,6 +2024,54 @@ TEST(op_grid_embed_aa_is_torchs_antialiased_bilinear) {
}
}
/* RADIO's cropped position embedding, against torch's F.interpolate(bilinear, align_corners=False)
* onto a d x d square cropped to the grid (values from torch 2.11). A 3 x 5 grid upsamples the
* 4 x 4 table to 5 x 5 and keeps three rows; a 2 x 2 grid downsamples it, which antialias would
* change, so the two cases tell this op from grid_embed_aa. */
TEST(op_grid_embed_cpe_is_torchs_bilinear_on_a_square_cropped) {
const int side = 4, n = 2;
T tab(RAD_F32, {side * side, n});
tab.f({ -5.0f, -1.75f, 2.0f, 5.25f, -2.0f, 1.25f, 5.0f, -2.75f, 1.0f, 4.25f, -3.0f, 0.25f,
4.0f, -3.75f, 0.0f, 3.25f, -4.0f, -0.75f, 3.0f, -4.75f, -1.0f, 2.25f, -5.0f, -1.75f,
2.0f, 5.25f, -2.0f, 1.25f, 5.0f, -2.75f, 1.0f, 4.25f });
struct G { int h, w; std::vector<float> want; };
const G cases[] = {
{ 3, 5, { -5.0f, -1.75f, -0.1f, 3.15f, 0.0f, 3.25f, 0.1f, 0.05f, 5.0f, -2.75f, -0.8f,
2.45f, -1.29f, 1.96f, 0.35f, -0.25f, 1.99f, -1.14f, 1.5f, 1.45f, -1.5f, 1.75f,
-0.45f, -1.05f, 0.75f, -1.5f, 0.3f, -0.3f, -2.5f, 0.75f } },
{ 2, 2, { -1.25f, 2.0f, 1.75f, -0.5f, -0.25f, 0.25f, 0.0f, 0.5f } },
};
for (const G& g : cases) {
const int M = g.h * g.w;
T x(RAD_F32, {M, n});
std::vector<float> zero((size_t)(M * n), 0.0f);
x.f(zero);
T crd(RAD_I32, {4, M});
std::vector<int64_t> c((size_t)(4 * M));
for (int r = 0; r < M; ++r) {
c[(size_t)r] = r / g.w;
c[(size_t)(M + r)] = r % g.w;
c[(size_t)(2 * M + r)] = g.h;
c[(size_t)(3 * M + r)] = g.w;
}
crd.n(c);
A a; a.t(x).t(tab).t(crd).i("M", M).i("n", n).i("side", side).s("dtype", "f32");
CHECK_OK(run("grid_embed_cpe", a));
for (int i = 0; i < M * n; ++i) CHECK_NEAR(x.at(i), g.want[(size_t)i], 2e-5);
}
/* The rows ahead of a segment's patches: row coordinate -1, the column naming the prefix row.
* Two of them, then the 2 x 2 grid's (1, 0), which still takes the resampled table. */
T pre(RAD_F32, {2, n}); pre.f({ 10.0f, 11.0f, 20.0f, 21.0f });
T x(RAD_F32, {3, n}); x.f({ 0.5f, 0.5f, 0.0f, 0.0f, 0.0f, 0.0f });
T crd(RAD_I32, {4, 3}); crd.n({ -1, -1, 1, 1, 0, 0, 2, 2, 2, 2, 2, 2 });
A a; a.t(x).t(tab).t(crd).t(pre).i("M", 3).i("n", n).i("side", side).i("n_prefix", 2)
.s("dtype", "f32");
CHECK_OK(run("grid_embed_cpe", a));
CHECK_NEAR(x.at(0), 20.5f, 1e-6); CHECK_NEAR(x.at(1), 21.5f, 1e-6); /* 0.5 + prefix row 1 */
CHECK_NEAR(x.at(2), 10.0f, 1e-6); CHECK_NEAR(x.at(3), 11.0f, 1e-6); /* prefix row 0 */
CHECK_NEAR(x.at(4), -0.25f, 2e-5); CHECK_NEAR(x.at(5), 0.25f, 2e-5); /* torch's (1, 0) */
}
/* LFM2's short convolution: ple_conv's window at dilation one, with no activation. */
TEST(op_causal_conv1d) {
const int n = 1, wid = 3;
@@ -10244,6 +10292,7 @@ std::vector<Geo> geometries() {
G("mtp_enter", "M", 2, a.i("M", R).i("n", 8).i("hc", 2).d("eps", 1e-6).s("dtype", "f32")),
G("grid_embed", "M", 3, a.i("M", R).i("n", 8).i("side", 4).s("dtype", "f32")),
G("grid_embed_aa", "M", 3, a.i("M", R).i("n", 8).i("side", 4).s("dtype", "f32")),
G("grid_embed_cpe", "M", 3, a.i("M", R).i("n", 8).i("side", 4).s("dtype", "f32")),
G("lili_cand", "M", 3, a.i("M", R).i("k", 4).i("world", 1).i("steps", 3).i("n", 8)
.s("dtype", "f32")),
G("lili_attn", "M", 8, a.i("M", R).i("steps", 2).i("k", 2).i("n_head", 2).i("head_dim", 4)