Archived
radiance 1.11.0
New models: - GLM-5.3-Flash reads pictures: its vision tower and processor (--image-tokens sets the budget), with decode kernels for a few rows and the DSA indexer split over the ranks - Sage-A1.5 (fp8 and MXFP4) with its vision tower and a DFlash2 drafter - Unlimited-OCR (bf16) - Gemma 4 31B with z-lab's DFlash and RedHatAI's DFlash2 drafters; at four cards its all-reduces are fused with the junctions, overlapped with the compute and sent compressed - Ornith-1.5-35B-A3B w4a8 compose files Speed: - Block drafters (DFlash, DFlash2) accept their drafts on the card, and the next step is issued ahead - The four-rank all-reduce is faster for every --tp 4 model - qwen35_w8a8: the norms and SiLU write the int8 linears' operands directly - --attn-prefill-fp8 off|qk|pv|both: fp8 QK and PV legs for the h256 prefill attention (about +20% prefill on a 221K-token prompt for the 27B MXFP4 at TP2); lossy, off by default Features: - Control vectors: --control-vector off|on|disabled (disabled by default), a per-request switch, and the published Qwen3.8-Flash-Next refusal-direction vector (its license is in NOTICE) - Krea 2: the `rebalance` request field, as ComfyUI's ConditioningKrea2Rebalance - Cards with a small PCI BAR run, with kernel arguments kept in host memory - Dashboard: live acceptance figures; statsdump rotates its file at a size cap - KV caches every rank holds whole (GLM-5.3's latent and index caches) take one host-tier slot Fixes: - Long conversations taking turns no longer fall back to an early snapshot: a host-tier restore makes room as memory pressure does and waits a step for the previous turn's release (two conversations of 142K and 147K tokens sent back to back: 31.3 s per turn before, 2.8 s now) - Kernels before Linux 6.16 (amdgpu below 3.64) no longer hang at startup: virtual memory management is turned off there, with a warning - Gemma 4 dense scales its token embeddings as Hugging Face does (bf16), which changes its output - The four-rank all-reduce fences prefill-sized messages, for a rare divergence after a fresh start - GLM-5.3: every refusal names the setting and the reason; its template keeps string content - Several pictures in one request no longer refuse processors that take one image at a time Changes: Plugin ABI 26: out-of-tree plugins must be rebuilt. The environment switches the PRs added are fixed rules or flags now (R4D_ATTN_FP8 is --attn-prefill-fp8).
This commit is contained in:
commit
9eaf10da6e
210 files changed
+14363
-2138
No files matched your search
@@ -386,8 +386,8 @@ int ref_act_mul(const RadArgs* a, RadStream) {
|
||||
if (n <= 0) return RAD_E_SHAPE;
|
||||
const int64_t rows = rows_of(Y, n);
|
||||
if (rows <= 0 || numel(A) < rows * n || numel(B) < rows * n) return RAD_E_SHAPE;
|
||||
static const char* kActs[] = { "silu", "gelu", "gelu_tanh", "sigmoid" };
|
||||
const int act = p_enum(a, "act", kActs, 4, -1);
|
||||
static const char* kActs[] = { "silu", "gelu", "gelu_tanh", "sigmoid", "quick_gelu" };
|
||||
const int act = p_enum(a, "act", kActs, 5, -1);
|
||||
if (act < 0) return RAD_E_INVAL;
|
||||
|
||||
REF_PAR_FOR(rows * n)
|
||||
@@ -396,8 +396,13 @@ int ref_act_mul(const RadArgs* a, RadStream) {
|
||||
const int64_t as = laststride(A), bs = laststride(B), ys = laststride(Y);
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
const float g = ldt(A, ab + i * as);
|
||||
/* quick_gelu is x * sigmoid(1.702 x) with the scaled value rounded to y's dtype
|
||||
* first, exactly the unfused mul-then-act_mul pair this replaces. */
|
||||
const float v = act == 0 ? act_silu(g) : act == 1 ? act_gelu(g)
|
||||
: act == 2 ? act_gelu_tanh(g) : act_sigmoid(g);
|
||||
: act == 2 ? act_gelu_tanh(g)
|
||||
: act == 3 ? act_sigmoid(g)
|
||||
: act_sigmoid(round_dt(Y->dtype,
|
||||
g * round_dt(RAD_BF16, 1.702f)));
|
||||
stt(Y, yb + i * ys, round_dt(Y->dtype, v) * ldt(B, bb + i * bs));
|
||||
}
|
||||
}
|
||||
|
||||
+3
-33
@@ -327,8 +327,8 @@ int ref_s2d3d(const RadArgs* a, RadStream) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ pix_patch / patch_pix8 */
|
||||
/* LTX-2's patchifier, both ways, over dense 2-D operands whose shapes give the sizes. A patch of
|
||||
/* ------------------------------------------------------------------ pix_patch */
|
||||
/* LTX-2's patchifier over dense 2-D operands whose shapes give the sizes. A patch of
|
||||
* p x p pixels of C channels is one row of C p p values, channel c's offset (ph, pw) at
|
||||
* c p p + pw p + ph with `order` wh (LTX-2's: the column offset outer) or c p p + ph p + pw with
|
||||
* hw.
|
||||
@@ -358,36 +358,6 @@ int ref_pix_patch(const RadArgs* a, RadStream) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* patch_pix8: patch rows x [R, w C p p] (R a frame's patch rows times its frames) to RGB bytes
|
||||
* y [R p, w p C], each byte round(255 clamp(rd(rd(clamp(v, -1, 1) / 2) + 0.5), 0, 1)) with rd
|
||||
* x's dtype, to_rgba8's rule. */
|
||||
int ref_patch_pix8(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 2)) return RAD_E_INVAL;
|
||||
const RadTensor *X = &a->t[0], *Y = &a->t[1];
|
||||
const int64_t p = p_int(a, "p", 0), C = p_int(a, "C", 0);
|
||||
const bool wh = std::strcmp(p_str(a, "order", "wh"), "hw") != 0;
|
||||
if (p <= 0 || C <= 0 || X->rank != 2 || Y->rank != 2 || Y->dtype != RAD_U8 ||
|
||||
X->shape[1] % (C * p * p))
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t R = X->shape[0], w = X->shape[1] / (C * p * p);
|
||||
if (R <= 0 || w <= 0 || Y->shape[0] != R * p || Y->shape[1] != w * p * C) return RAD_E_SHAPE;
|
||||
const int64_t xr = X->stride[0], yr = Y->stride[0];
|
||||
const uint32_t dt = X->dtype;
|
||||
uint8_t* yb = (uint8_t*)Y->data;
|
||||
REF_PAR_FOR(R * p * w * p * C)
|
||||
for (int64_t y = 0; y < R * p; ++y)
|
||||
for (int64_t x = 0; x < w * p; ++x)
|
||||
for (int64_t c = 0; c < C; ++c) {
|
||||
const float v = ldt(X, (y / p) * xr + (x / p) * C * p * p +
|
||||
patch_col(c, y % p, x % p, p, wh));
|
||||
const float cl = std::min(std::max(v, -1.0f), 1.0f);
|
||||
float u = round_dt(dt, round_dt(dt, cl / 2.0f) + 0.5f);
|
||||
u = std::min(std::max(u, 0.0f), 1.0f);
|
||||
yb[y * yr + x * C + c] = (uint8_t)std::nearbyint(u * 255.0f);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ vol_index */
|
||||
/* A volume's voxel coordinates, the rotary positions of attention over it: geom = (T, H, W), i32
|
||||
* on the device; y i32 [3, n] component-major (at its own row pitch), voxel m = (t H + i) W + j's
|
||||
@@ -522,7 +492,7 @@ int ref_tile_crop(const RadArgs* a, RadStream) {
|
||||
*
|
||||
* and across time blend_t: frame f of band kt, f < et = min(F of band kt-1, F of band kt,
|
||||
* (tile_t - stride_t) scale_t), is mix(S_{kt-1}[F_{kt-1} - et + f], S_kt[f], f, et). The byte is
|
||||
* patch_pix8's, round(255 clamp(rd(rd(clamp(v, -1, 1) / 2) + 0.5), 0, 1)). y is u8
|
||||
* to_rgba8's, round(255 clamp(rd(rd(clamp(v, -1, 1) / 2) + 0.5), 0, 1)). y is u8
|
||||
* [n (H scale p), (W scale p) C], frames first .. first + n - 1. A tile above, to the left or
|
||||
* before is never short enough for its own blends to reach the margin read here (a tile not last
|
||||
* on its axis spans more than `stride`), so these are the reference's values exactly. */
|
||||
|
||||
@@ -147,6 +147,83 @@ int ref_moe_scatter(const RadArgs* a, RadStream) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ router_topk_scatter */
|
||||
/* The pair as one op, and the reference is the pair: the fused device kernel must be
|
||||
* byte-identical to these two launches, in order, over the operands the fused op carries. The
|
||||
* selection runs over the whole router's `n_expert` logits; the sort runs over this rank's slice,
|
||||
* the fused op's `n_local` standing where `moe_scatter`'s `n_expert` names the slice it owns. */
|
||||
int ref_router_topk_scatter(const RadArgs* a, RadStream s) {
|
||||
if (!have(a, 6)) return RAD_E_INVAL;
|
||||
const int64_t ne = p_int(a, "n_expert", 0);
|
||||
const int64_t nl = p_int(a, "n_local", ne);
|
||||
const int64_t k = p_int(a, "top_k", 1);
|
||||
if (ne <= 0 || k <= 0 || k > ne || nl <= 0 || nl > ne) return RAD_E_SHAPE;
|
||||
|
||||
const RadParam rp[] = { RAD_INT("n_expert", ne), RAD_INT("top_k", k),
|
||||
RAD_INT("norm", p_int(a, "norm", 0)),
|
||||
RAD_STR("dtype", p_str(a, "dtype", "bf16")) };
|
||||
const RadArgs ra{ a->t, 3, rp, 4, nullptr, 0, nullptr, a->rank, a->world_size };
|
||||
const int rc = ref_router_topk(&ra, s);
|
||||
if (rc != RAD_OK) return rc;
|
||||
|
||||
/* The fused op's operands with `expert_w` removed -- the sort's input is the selection's
|
||||
* output, named once, and `moe_scatter` takes it in operand slot 0. RadArgs reads a
|
||||
* contiguous tensor array, so the four descriptors are laid out here, by value. */
|
||||
const RadTensor t2[] = { a->t[1], a->t[3], a->t[4], a->t[5] };
|
||||
const RadParam sp[] = { RAD_INT("n_expert", nl), RAD_INT("top_k", k),
|
||||
RAD_INT("expert_base", p_int(a, "expert_base", 0)),
|
||||
RAD_STR("protect", p_str(a, "protect", nullptr)) };
|
||||
const RadArgs sa{ t2, 4, sp, 4, nullptr, 0, nullptr, a->rank, a->world_size };
|
||||
return ref_moe_scatter(&sa, s);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ router_gemm_topk_scatter */
|
||||
/* The router GEMM in front of the pair, and with `gate_b`/`gate` present the shared expert's
|
||||
* one-column gate over the same input. The reference is the launches it stands in for, and the
|
||||
* fused kernel must be byte-identical to them: the router's `gemm_nt`, the gate's `gemm_nt` at
|
||||
* N = 1, then `router_topk_scatter` over the logits. `gate_b` and `gate` come together or not at
|
||||
* all, and the operand count says which. */
|
||||
int ref_router_gemm_topk_scatter(const RadArgs* a, RadStream s) {
|
||||
/* NOT `have`: the required operands are not a prefix -- `gate_b` sits between the router's
|
||||
* weight and the outputs, and it and `gate` are null slots in the gate-absent form. The nine
|
||||
* required slots are checked by name; the pair is checked to come together or not at all. */
|
||||
if (!a || !a->t || a->n_t < 9) return RAD_E_INVAL;
|
||||
const bool gate_b = a->n_t > 2 && a->t[2].data != nullptr;
|
||||
const bool gate = a->n_t > 9 && a->t[9].data != nullptr;
|
||||
if (gate_b != gate) return RAD_E_INVAL;
|
||||
for (int i : {0, 1, 3, 4, 5, 6, 7, 8})
|
||||
if (!a->t[i].data) return RAD_E_INVAL;
|
||||
const int64_t ne = p_int(a, "n_expert", 0);
|
||||
const int64_t nl = p_int(a, "n_local", ne);
|
||||
const int64_t k = p_int(a, "top_k", 1);
|
||||
const int64_t K = p_int(a, "K", 0);
|
||||
if (ne <= 0 || k <= 0 || k > ne || nl <= 0 || nl > ne || K <= 0) return RAD_E_SHAPE;
|
||||
const char* dt = p_str(a, "dtype", "bf16");
|
||||
|
||||
/* The router: a [M, K] x b [n_expert, K]^T -> logits. gemm_nt takes a, b, y contiguously. */
|
||||
const RadTensor g3[] = { a->t[0], a->t[1], a->t[3] };
|
||||
const RadParam gp[] = { RAD_INT("N", ne), RAD_INT("K", K), RAD_STR("dtype", dt) };
|
||||
const RadArgs ga{ g3, 3, gp, 3, nullptr, 0, nullptr, a->rank, a->world_size };
|
||||
const int gc = ref_gemm_nt(&ga, s);
|
||||
if (gc != RAD_OK) return gc;
|
||||
|
||||
/* The shared expert's gate: the same arithmetic at N = 1, beside the router, over the same
|
||||
* `a`. The pair was checked to come together. */
|
||||
if (gate) {
|
||||
const RadTensor p3[] = { a->t[0], a->t[2], a->t[9] };
|
||||
const RadParam pp[] = { RAD_INT("N", 1), RAD_INT("K", K), RAD_STR("dtype", dt) };
|
||||
const RadArgs pa{ p3, 3, pp, 3, nullptr, 0, nullptr, a->rank, a->world_size };
|
||||
const int pc = ref_gemm_nt(&pa, s);
|
||||
if (pc != RAD_OK) return pc;
|
||||
}
|
||||
|
||||
/* The pair over the logits the GEMM just wrote. Every parameter the pair reads is a parameter
|
||||
* of this op, under the same name -- the fused lists are unions, so `a`'s list passes through. */
|
||||
const RadTensor t6[] = { a->t[3], a->t[4], a->t[5], a->t[6], a->t[7], a->t[8] };
|
||||
const RadArgs fa{ t6, 6, a->p, a->n_p, nullptr, 0, nullptr, a->rank, a->world_size };
|
||||
return ref_router_topk_scatter(&fa, s);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ moe_gemm, moe_gemm_q */
|
||||
/* y[i, :] = a[row(i), :] @ w[e]^T, e the expert whose offset range contains i. `a_order` picks
|
||||
* row(i): `sorted_tok[i] / top_k` for one activation row per token, i itself for one per
|
||||
|
||||
+9
-2
@@ -150,6 +150,8 @@ int ref_attn_cross (const RadArgs*, RadStream);
|
||||
int ref_table_add (const RadArgs*, RadStream);
|
||||
int ref_mix_rows (const RadArgs*, RadStream);
|
||||
int ref_chan_stats (const RadArgs*, RadStream);
|
||||
/* Unlimited-OCR's SAM tower: windowed attention with decomposed relative position (ref_sam_attn.cpp). */
|
||||
int ref_sam_attn (const RadArgs*, RadStream);
|
||||
int ref_kv_store (const RadArgs*, RadStream);
|
||||
int ref_rope (const RadArgs*, RadStream);
|
||||
int ref_rope_table (const RadArgs*, RadStream);
|
||||
@@ -188,7 +190,6 @@ int ref_pixel_norm(const RadArgs*, RadStream);
|
||||
int ref_d2s3d(const RadArgs*, RadStream);
|
||||
int ref_s2d3d(const RadArgs*, RadStream);
|
||||
int ref_pix_patch(const RadArgs*, RadStream);
|
||||
int ref_patch_pix8(const RadArgs*, RadStream);
|
||||
int ref_vol_index(const RadArgs*, RadStream);
|
||||
int ref_attn_na3d(const RadArgs*, RadStream);
|
||||
int ref_tile_grid(const RadArgs*, RadStream);
|
||||
@@ -243,6 +244,8 @@ int ref_dflash_conv (const RadArgs*, RadStream);
|
||||
/* ---- mixture of experts */
|
||||
int ref_router_topk (const RadArgs*, RadStream);
|
||||
int ref_moe_scatter (const RadArgs*, RadStream);
|
||||
int ref_router_topk_scatter(const RadArgs*, RadStream);
|
||||
int ref_router_gemm_topk_scatter(const RadArgs*, RadStream);
|
||||
int ref_moe_gemm (const RadArgs*, RadStream);
|
||||
int ref_moe_gemm_q (const RadArgs*, RadStream);
|
||||
int ref_moe_gemm_q_mod4 (const RadArgs*, RadStream);
|
||||
@@ -280,6 +283,7 @@ void ref_collective_fini(void*);
|
||||
/* ---- sampling */
|
||||
int ref_sample_penalties (const RadArgs*, RadStream);
|
||||
int ref_sample_dry (const RadArgs*, RadStream);
|
||||
int ref_sample_ngram_ban (const RadArgs*, RadStream);
|
||||
int ref_sample_temp (const RadArgs*, RadStream);
|
||||
int ref_sample_topk (const RadArgs*, RadStream);
|
||||
int ref_sample_topp (const RadArgs*, RadStream);
|
||||
@@ -397,6 +401,7 @@ REF_SHAPE_FN(ref_attn_cross);
|
||||
REF_SHAPE_FN(ref_table_add);
|
||||
REF_SHAPE_FN(ref_mix_rows);
|
||||
REF_SHAPE_FN(ref_chan_stats);
|
||||
REF_SHAPE_FN(ref_sam_attn);
|
||||
REF_SHAPE_FN(ref_kv_store);
|
||||
REF_SHAPE_FN(ref_rope);
|
||||
REF_SHAPE_FN(ref_rope_table);
|
||||
@@ -432,7 +437,6 @@ REF_SHAPE_FN(ref_pixel_norm);
|
||||
REF_SHAPE_FN(ref_d2s3d);
|
||||
REF_SHAPE_FN(ref_s2d3d);
|
||||
REF_SHAPE_FN(ref_pix_patch);
|
||||
REF_SHAPE_FN(ref_patch_pix8);
|
||||
REF_SHAPE_FN(ref_vol_index);
|
||||
REF_SHAPE_FN(ref_attn_na3d);
|
||||
REF_SHAPE_FN(ref_tile_grid);
|
||||
@@ -481,6 +485,8 @@ REF_SHAPE_FN(ref_dflash_conv);
|
||||
|
||||
REF_SHAPE_FN(ref_router_topk);
|
||||
REF_SHAPE_FN(ref_moe_scatter);
|
||||
REF_SHAPE_FN(ref_router_topk_scatter);
|
||||
REF_SHAPE_FN(ref_router_gemm_topk_scatter);
|
||||
REF_SHAPE_FN(ref_moe_gemm);
|
||||
REF_SHAPE_FN(ref_moe_gemm_q);
|
||||
REF_SHAPE_FN(ref_moe_gemm_q_mod4);
|
||||
@@ -504,6 +510,7 @@ REF_SHAPE_FN(ref_all_gather);
|
||||
|
||||
REF_SHAPE_FN(ref_sample_penalties);
|
||||
REF_SHAPE_FN(ref_sample_dry);
|
||||
REF_SHAPE_FN(ref_sample_ngram_ban);
|
||||
REF_SHAPE_FN(ref_sample_temp);
|
||||
REF_SHAPE_FN(ref_sample_topk);
|
||||
REF_SHAPE_FN(ref_sample_topp);
|
||||
|
||||
+83
-6
@@ -357,7 +357,10 @@ static const RadParamSpec pAttnPaged[] = {
|
||||
/* For libr4d's scratch hook, which sizes its split-KV partial buffer at declare
|
||||
* (num_seqs * q_len * q_heads * splits rows; gqa is only the head ratio). Ref ignores them;
|
||||
* they are here because both plugins must agree on the parameter list. */
|
||||
P_INTO("n_head"), P_INTO("max_seqs")
|
||||
P_INTO("n_head"), P_INTO("max_seqs"),
|
||||
/* The e4m3 products a caller accepts (docs/OPS.md). A permission, not a request: ref computes
|
||||
* the exact form whatever it says. */
|
||||
P_INTO("prefill_fp8")
|
||||
};
|
||||
static const RadOperandSpec oAttnPaged[] = {
|
||||
OPD("q"), OPD("kv_cache"), OPD("block_table"), OPD("seqused"),
|
||||
@@ -383,6 +386,16 @@ static const RadParamSpec pAttnNa3d[] = { P_INT("M"), P_INT("head_dim"), P_INT("
|
||||
P_INT("kw"), P_STR("dtype"), P_F64O("scale") };
|
||||
static const RadOperandSpec oAttnNa3d[] = { OPD("q"), OPD("k"), OPD("v"), OPD("geom"), OUT("out") };
|
||||
|
||||
/* The SAM tower's attention. `q`, `k` and `v` are the three column slices of one fused projection,
|
||||
* so each is read at its own row pitch. The two rel_pos tables are weights: [2*L-1, head_dim] with
|
||||
* L the window (or the grid for a global layer), resampled along dim 0 when a geometry needs it.
|
||||
* `grid_h` x `grid_w` rows a segment, `window` 0 for a whole-segment tile. */
|
||||
static const RadParamSpec pSamAttn[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_head"),
|
||||
P_INT("grid_h"), P_INT("grid_w"), P_INT("window"),
|
||||
P_F64("scale"), P_STR("dtype") };
|
||||
static const RadOperandSpec oSamAttn[] = { OPD("q"), OPD("k"), OPD("v"), OPD("cu_seqlens"),
|
||||
OUT("out"), WGT("rel_pos_h"), WGT("rel_pos_w") };
|
||||
|
||||
/* `k_scale` and `v_scale` are the descales an fp8 cache is read back with, so a store divides by
|
||||
* them; optional because a bf16 cache has none. */
|
||||
static const RadParamSpec pKvStore[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_head_kv"),
|
||||
@@ -480,6 +493,29 @@ static const RadParamSpec pScatter[] = { P_INT("M"), P_INT("n_expert"), P_INT("t
|
||||
static const RadOperandSpec oScatter[] = { OPD("expert_ids"), OUT("sorted_tok"),
|
||||
OUT("expert_offset"), OUT("expert_count") };
|
||||
|
||||
/* The pair as one op: the union of the two parameter lists, and their operands with the shared
|
||||
* `expert_ids` named once, as an output. Same schema as libr4d's fused row. */
|
||||
static const RadParamSpec pRouterTopkScatter[] = { P_INT("M"), P_INT("n_expert"),
|
||||
P_INTO("n_local"), P_INT("top_k"),
|
||||
P_INT("norm"), P_STR("dtype"),
|
||||
P_INTO("expert_base"),
|
||||
P_STRO("protect") };
|
||||
static const RadOperandSpec oRouterTopkScatter[] = { OPD("logits"), OUT("expert_ids"),
|
||||
OUT("expert_w"), OUT("sorted_tok"),
|
||||
OUT("expert_offset"),
|
||||
OUT("expert_count") };
|
||||
|
||||
/* The router GEMM in front of the pair, and the gate's one-column GEMM beside it: the union of
|
||||
* the three operand lists with `logits` named once, as the GEMM's output. */
|
||||
static const RadParamSpec pRouterGemmTopkScatter[] = { P_INT("M"), P_INT("K"),
|
||||
P_INT("n_expert"), P_INTO("n_local"),
|
||||
P_INT("top_k"), P_INT("norm"),
|
||||
P_STR("dtype"), P_INTO("expert_base"),
|
||||
P_STRO("protect") };
|
||||
static const RadOperandSpec oRouterGemmTopkScatter[] = {
|
||||
OPD("a"), WGT("b"), WGT_O("gate_b"), OUT("logits"), OUT("expert_ids"), OUT("expert_w"),
|
||||
OUT("sorted_tok"), OUT("expert_offset"), OUT("expert_count"), OUT_O("gate") };
|
||||
|
||||
/* `a_order` says which rows the activation has; a routed block's two grouped GEMMs differ. gate_up
|
||||
* reads the block input, one row per token, so sorted row i gathers `a[sorted_tok[i] / top_k]`.
|
||||
* down reads gate_up's output, already one row per (token, slot) in scatter order, so row i is row
|
||||
@@ -679,6 +715,13 @@ static const RadOperandSpec oPenalties[] = { INOUT("logits"), OPD("params"), OPD
|
||||
* is a whole DRY sequence breaker and never penalised. Absent, no token is exempt. */
|
||||
static const RadOperandSpec oDry[] = { INOUT("logits"), OPD("params"), OPD("history"),
|
||||
OPD_O("breakers") };
|
||||
/* The windowed n-gram ban: penalties' operands plus a {n, window} pair a row.
|
||||
* `whitelist` is optional: a bitmask plane [M, ceil(n_vocab/32)] like sample_mask's, a SET bit
|
||||
* marking a token exempt from the ban (the reference's whitelist, removed from the banned set
|
||||
* before the -inf writes). Absent, nothing is exempt. Rows are indexed by the sampled position,
|
||||
* not by mask_row: every row the op bans reads its own words. */
|
||||
static const RadOperandSpec oNgramBan[] = { INOUT("logits"), OPD("params"), OPD("history"),
|
||||
OPD("ngram"), OPD_O("whitelist") };
|
||||
static const RadOperandSpec oTemp[] = { INOUT("logits"), OPD("params") };
|
||||
/* `bitmask` is [rows, ceil(n_vocab/32)] uint32, addressed by the row's mask_row -- which is -1 for
|
||||
* an unconstrained sequence, so the plane is shared and shorter than M. */
|
||||
@@ -1317,6 +1360,14 @@ static const RadOpSchema kSchemas[] = {
|
||||
{ "attn_na3d", ARR(pAttnNa3d), ARR(oAttnNa3d),
|
||||
"3-D neighborhood attention (NATTEN's na3d) over the voxels of geom = (T, H, W): a query sees the "
|
||||
"kt x kh x kw window centred on it, shifted inward at the border, each extent at most its axis." },
|
||||
{ "sam_attn", ARR(pSamAttn), ARR(oSamAttn),
|
||||
"Unlimited-OCR's SAM tower attention: per cu segment of grid_h*grid_w rows in raster grid order, "
|
||||
"pad to multiples of `window` with ZERO rows (window_partition, after norm1), cut into window x "
|
||||
"window tiles and attend each tile to all of its rows; `window` 0 is one tile over the segment. "
|
||||
"logits = scale*q.k + q.Rh[i_h,j_h] + q.Rw[i_w,j_w], dotted over the head's whole head_dim, "
|
||||
"softmax in f32 over the tile's keys (pad keys included), out = sum p*v, written back in segment "
|
||||
"row order with pad rows dropped. The tables are [2*L-1, head_dim], linearly resampled along "
|
||||
"dim 0 when a geometry's axes need it (get_rel_pos)." },
|
||||
{ "kv_store", ARR(pKvStore), ARR(oKvStore),
|
||||
"Writes k and v into the paged cache at slot_mapping; a negative slot is skipped. The cache is "
|
||||
"INOUT rather than the OUT docs/OPS.md draws, because the op touches only the mapped slots." },
|
||||
@@ -1388,6 +1439,16 @@ static const RadOpSchema kSchemas[] = {
|
||||
"sorts only its own slice, and the slots that went elsewhere simply contribute nothing to this "
|
||||
"rank's partial -- which the block's end-of-block all-reduce then sums. `expert_base` absent "
|
||||
"or 0 with n_expert the model's count is the whole-model case." },
|
||||
{ "router_topk_scatter", ARR(pRouterTopkScatter), ARR(oRouterTopkScatter),
|
||||
"`router_topk` then `moe_scatter`, in one launch: exactly those two and in that order, over "
|
||||
"the operands they share. The reference IS the pair -- the fused device kernel claims to be "
|
||||
"byte-identical to these two launches, and this is what it is measured against. The sort's "
|
||||
"outputs are sized by `n_local`, this rank's slice; absent it is the router's count." },
|
||||
{ "router_gemm_topk_scatter", ARR(pRouterGemmTopkScatter), ARR(oRouterGemmTopkScatter),
|
||||
"`gemm_nt` of `a` against the router `b`, then `router_topk_scatter` over those logits, and "
|
||||
"with `gate_b`/`gate` present the shared expert's `gemm_nt` at N = 1 over the same `a`. As "
|
||||
"with the pair, the reference IS the launches: the gate weight and output come together or not "
|
||||
"at all, and the operand count says which." },
|
||||
{ "moe_gemm", ARR(pMoeGemm), ARR(oMoeGemm),
|
||||
"y[i] = a[row(i)] @ w[e]^T in SORTED order, e being the expert whose offset range contains i. "
|
||||
"`a_order` picks row(i): \"token\" gathers a[sorted_tok[i] / top_k] from an activation with one "
|
||||
@@ -1514,6 +1575,15 @@ static const RadOpSchema kSchemas[] = {
|
||||
"repeats capped at the row's dry_rep_limit. Only lengths at or above allowed_length count, and "
|
||||
"a token the optional `breakers` plane marks is never penalised. dry_penalty_last_n windows the "
|
||||
"TAIL of the history; 0 turns the stage off for the row. Columns are ids less vocab_off." },
|
||||
{ "sample_ngram_ban", ARR(pPenal), ARR(oNgramBan),
|
||||
"The windowed no-repeat-ngram ban (Unlimited-OCR's SlidingWindowNoRepeatNgramProcessor): bans, "
|
||||
"by setting -infinity, every token that would complete an n-gram the last `window` tokens of "
|
||||
"the row's history already contain. `ngram` is one i32 {n, window} pair a row; the window "
|
||||
"bounds the n-gram's START index, as in the reference, window <= 0 searches the whole span and "
|
||||
"n 0 is off. The optional `whitelist` bitmask (a SET bit, word w bit b covering column 32w + b, "
|
||||
"the row's own plane row) exempts a token from the ban, as the reference's "
|
||||
"`banned.difference_update(whitelist)` does; absent, nothing is exempt. Columns are ids less "
|
||||
"vocab_off." },
|
||||
{ "sample_temp", ARR(pMVocab), ARR(oTemp),
|
||||
"logits /= temp, per row. temp <= 0 leaves the row untouched -- greedy decoding is "
|
||||
"sample_argmax, and a temperature of zero silently meaning something else is how a sampler "
|
||||
@@ -1723,9 +1793,6 @@ static const RadOpSchema kSchemas[] = {
|
||||
{ "pix_patch", ARR(pPixPatch), ARR(oPixPatch),
|
||||
"an image [H, W C] to patch rows [H/p, (W/p) C p p], channel c's (ph, pw) at c p p + pw p + ph "
|
||||
"(order wh) or c p p + ph p + pw (hw)." },
|
||||
{ "patch_pix8", ARR(pPixPatch), ARR(oPixPatch),
|
||||
"patch rows [R, w C p p] to RGB bytes [R p, w p C] by to_rgba8's rule, pix_patch's channel "
|
||||
"order." },
|
||||
{ "vol_index", ARR(pVolIndex), ARR(oVolIndex),
|
||||
"a volume's voxel coordinates (t, i, j), component-major: attention's rotary positions." },
|
||||
{ "tile_grid", ARR(pTileGrid), ARR(oTileGrid),
|
||||
@@ -1738,7 +1805,7 @@ static const RadOpSchema kSchemas[] = {
|
||||
{ "tile_stitch", ARR(pTileStitch), ARR(oTileStitch),
|
||||
"decoded tiles to RGB bytes: diffusers' in-place blend_v then blend_h of each tile with the one "
|
||||
"above and the one to its left, then blend_t of each time band with the one before, each kept to "
|
||||
"its stride, then patch_pix8's bytes." },
|
||||
"its stride, then to_rgba8's bytes." },
|
||||
{ "stft_logmel", ARR(pStftMel), ARR(oStftMel),
|
||||
"each channel's causal log-mel spectrogram from a windowed DFT basis and a mel filterbank, every "
|
||||
"stored tensor rounded to y's dtype: frames S / hop, columns h n_mel + m." },
|
||||
@@ -2139,6 +2206,9 @@ SIMPLE("ref_attn_cross", "attn_cross", "attn",
|
||||
ref_attn_cross),
|
||||
SIMPLE("ref_attn_na3d", "attn_na3d", "attn", "3-D neighborhood attention over a volume", DT_FLOAT,
|
||||
ref_attn_na3d),
|
||||
SIMPLE("ref_sam_attn", "sam_attn", "attn",
|
||||
"SAM tower attention: windowed tiles with decomposed relative position", DT_FLOAT,
|
||||
ref_sam_attn),
|
||||
ROW("ref_kv_store", "kv_store", "attn", "scatter k and v into the paged cache", DT_ANY,
|
||||
cPagedBlock, (int)(sizeof(cPagedBlock) / sizeof(cPagedBlock[0])),
|
||||
nullptr, nullptr, ref_kv_store, nullptr),
|
||||
@@ -2154,6 +2224,12 @@ SIMPLE("ref_router_topk", "router_topk", "moe", "softmax then exact top-k routin
|
||||
ref_router_topk),
|
||||
SIMPLE("ref_moe_scatter", "moe_scatter", "moe", "stable counting sort of routing slots by expert",
|
||||
"i32 indices", ref_moe_scatter),
|
||||
SIMPLE("ref_router_topk_scatter", "router_topk_scatter", "moe",
|
||||
"the selection and the sort in one op, run as exactly the pair", DT_FLOAT,
|
||||
ref_router_topk_scatter),
|
||||
SIMPLE("ref_router_gemm_topk_scatter", "router_gemm_topk_scatter", "moe",
|
||||
"the router GEMM, the selection and the sort in one op, run as exactly the launches",
|
||||
DT_FLOAT, ref_router_gemm_topk_scatter),
|
||||
SIMPLE("ref_moe_gemm", "moe_gemm", "moe", "grouped GEMM over the expert-sorted rows", DT_FLOAT,
|
||||
ref_moe_gemm),
|
||||
ROW_CB("ref_moe_gemm_q", "moe_gemm_q", "moe",
|
||||
@@ -2238,6 +2314,8 @@ SIMPLE("ref_sample_logprobs", "sample_logprobs", "sample", "the raw distribution
|
||||
DT_FLOAT, ref_sample_logprobs),
|
||||
SIMPLE("ref_sample_dry", "sample_dry", "sample", "DRY repetition-suffix penalty", DT_FLOAT,
|
||||
ref_sample_dry),
|
||||
SIMPLE("ref_sample_ngram_ban", "sample_ngram_ban", "sample",
|
||||
"windowed no-repeat-ngram ban", DT_FLOAT, ref_sample_ngram_ban),
|
||||
SIMPLE("ref_sample_typical", "sample_typical", "sample", "locally typical narrowing in place",
|
||||
DT_FLOAT, ref_sample_typical),
|
||||
SIMPLE("ref_sample_xtc", "sample_xtc", "sample", "exclude-top-choices narrowing in place",
|
||||
@@ -2332,7 +2410,6 @@ SIMPLE("ref_pixel_norm", "pixel_norm", "norm", "an RMS norm as bf16 tensors comp
|
||||
SIMPLE("ref_d2s3d", "d2s3d", "elem", "depth to space over voxel rows", DT_FLOAT, ref_d2s3d),
|
||||
SIMPLE("ref_s2d3d", "s2d3d", "elem", "space to depth over voxel rows", DT_FLOAT, ref_s2d3d),
|
||||
SIMPLE("ref_pix_patch", "pix_patch", "elem", "an image to patch rows", DT_FLOAT, ref_pix_patch),
|
||||
SIMPLE("ref_patch_pix8", "patch_pix8", "elem", "patch rows to RGB bytes", DT_FLOAT, ref_patch_pix8),
|
||||
SIMPLE("ref_vol_index", "vol_index", "elem", "a volume's voxel coordinates", DT_ANY, ref_vol_index),
|
||||
SIMPLE("ref_tile_grid", "tile_grid", "elem", "a tiled decode's boxes", DT_ANY, ref_tile_grid),
|
||||
SIMPLE("ref_tile_crop", "tile_crop", "elem", "a tile out of a volume", DT_FLOAT, ref_tile_crop),
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
/* ref_sam_attn.cpp -- Unlimited-OCR's DeepEncoder (SAM ViT-B/16) attention with decomposed relative
|
||||
* position (arch/common/rad_block_sam.h).
|
||||
*
|
||||
* The reference is the checkpoint's own deepencoder.py (Attention.forward and
|
||||
* add_decomposed_rel_pos), whose logits are
|
||||
*
|
||||
* scale * q.k + q.Rh[i_h, j_h] + q.Rw[i_w, j_w]
|
||||
*
|
||||
* where Rh = get_rel_pos(rel_pos_h, q_h, k_h) indexes the table at (i_h - j_h + len - 1) and the dot
|
||||
* runs over the whole head_dim of the head's own q (deepencoder computes r_q of shape
|
||||
* (B*heads, q_h, q_w, head_dim) and einsums "bhwc,hkc->bhwk"). So the per-pair term folds into
|
||||
* neither q, k nor v: no plain attention op can carry it, which is why this op exists.
|
||||
*
|
||||
* ============================== Windows ==============================
|
||||
*
|
||||
* Each cu segment is grid_h * grid_w rows in row-major grid order. With `window` > 0 the segment is
|
||||
* padded to multiples of `window` with ZERO rows and cut into window x window tiles, exactly as
|
||||
* window_partition does after norm1: the pad rows are keys AND values of their tile, so their
|
||||
* logits (which carry the rel terms even though q.k is 0) take part in the softmax, and their v is
|
||||
* zero. `window` 0 is one tile over the whole segment (the reference's global blocks).
|
||||
*
|
||||
* ============================== Table resizing ==============================
|
||||
*
|
||||
* get_rel_pos linearly interpolates the table along dim 0 when its length is not
|
||||
* 2*max(q,k) - 1 (F.interpolate, mode linear, align_corners False). Every geometry the tower
|
||||
* declares matches exactly, but a non-square global grid has axes of different extents, so the
|
||||
* resampling is implemented here rather than assumed away.
|
||||
*
|
||||
* ============================== Numerics ==============================
|
||||
*
|
||||
* f32 throughout: q, k, v and the tables are widened once, every dot and softmax accumulates in
|
||||
* f32 with the max subtracted, and the output is rounded once to the operand's dtype. Summation
|
||||
* order is fixed (increasing channel, then key), so two runs agree bit for bit at any thread count.
|
||||
*/
|
||||
#include "ref_common.h"
|
||||
#include "ref_ops.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <vector>
|
||||
|
||||
using namespace ref;
|
||||
|
||||
namespace {
|
||||
|
||||
/* A rel_pos table as f32 rows of `hd`, resampled to `want` rows when its own length differs.
|
||||
* F.interpolate(..., size=want, mode="linear") with align_corners False: output d samples the input
|
||||
* at (d + 0.5) * rows / want - 0.5, clamped to the ends, linearly between the neighbours. */
|
||||
static std::vector<float> table_rows(const RadTensor* t, int64_t hd, int64_t want) {
|
||||
const int64_t rows = hd > 0 ? numel(t) / hd : 0;
|
||||
std::vector<float> raw((size_t)(rows * hd), 0.0f);
|
||||
const int64_t st = laststride(t);
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
const int64_t base = rowoff(t, r, hd);
|
||||
for (int64_t c = 0; c < hd; ++c) raw[(size_t)(r * hd + c)] = ldt(t, base + c * st);
|
||||
}
|
||||
if (rows == want || rows <= 0 || want <= 0) return raw;
|
||||
std::vector<float> out((size_t)(want * hd), 0.0f);
|
||||
const double span = (double)rows / (double)want;
|
||||
for (int64_t d = 0; d < want; ++d) {
|
||||
double src = ((double)d + 0.5) * span - 0.5;
|
||||
if (src < 0.0) src = 0.0;
|
||||
if (src > (double)(rows - 1)) src = (double)(rows - 1);
|
||||
const int64_t i0 = (int64_t)src;
|
||||
const int64_t i1 = i0 + 1 < rows ? i0 + 1 : i0;
|
||||
const float f = (float)(src - (double)i0);
|
||||
for (int64_t c = 0; c < hd; ++c) {
|
||||
const float a = raw[(size_t)(i0 * hd + c)], b = raw[(size_t)(i1 * hd + c)];
|
||||
out[(size_t)(d * hd + c)] = a + (b - a) * f;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* See the file header for the semantics. `cu_seqlens` absent is one segment of every row: the
|
||||
* reference's single-view form. */
|
||||
int ref_sam_attn(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 7)) return RAD_E_INVAL;
|
||||
const RadTensor *q = &a->t[0], *k = &a->t[1], *v = &a->t[2], *cu = &a->t[3];
|
||||
const RadTensor *o = &a->t[4], *th_tab = &a->t[5], *tw_tab = &a->t[6];
|
||||
|
||||
const int64_t hd = p_int(a, "head_dim", 0);
|
||||
const int64_t nh = p_int(a, "n_head", 0);
|
||||
const int64_t gh = p_int(a, "grid_h", 0);
|
||||
const int64_t gw = p_int(a, "grid_w", 0);
|
||||
const int64_t win = p_int(a, "window", 0);
|
||||
if (hd <= 0 || nh <= 0 || gh <= 0 || gw <= 0 || win < 0) return RAD_E_SHAPE;
|
||||
const int64_t W = nh * hd, R = gh * gw;
|
||||
if (!q->data || !k->data || !v->data || !o->data || !th_tab->data || !tw_tab->data)
|
||||
return RAD_E_INVAL;
|
||||
for (const RadTensor* t : { q, k, v, o })
|
||||
if (t->rank < 2 || t->shape[t->rank - 1] != W) return RAD_E_SHAPE;
|
||||
const int64_t M = numel(q) / W;
|
||||
if (M <= 0) return RAD_E_SHAPE;
|
||||
if (numel(k) != M * W || numel(v) != M * W || numel(o) < M * W) return RAD_E_SHAPE;
|
||||
|
||||
/* Segments: cu[s]..cu[s+1], each exactly one grid. */
|
||||
int64_t nseq = 1;
|
||||
if (cu->data) {
|
||||
if (cu->rank == 0 || numel(cu) < 2) return RAD_E_SHAPE;
|
||||
nseq = numel(cu) - 1;
|
||||
if (cu_at(cu, 0) != 0 || cu_at(cu, nseq) != M) return RAD_E_SHAPE;
|
||||
for (int64_t s = 0; s < nseq; ++s)
|
||||
if (cu_at(cu, s + 1) - cu_at(cu, s) != R) return RAD_E_SHAPE;
|
||||
} else if (M != R) {
|
||||
return RAD_E_SHAPE;
|
||||
}
|
||||
|
||||
const float scale = p_f32(a, "scale", (float)(1.0 / std::sqrt((double)hd)));
|
||||
|
||||
/* The tile geometry: window x window, or the whole grid. Table lengths follow the tile axes. */
|
||||
const int64_t th = win > 0 ? win : gh, tw = win > 0 ? win : gw;
|
||||
const int64_t keys = th * tw;
|
||||
if (numel(th_tab) < hd || numel(tw_tab) < hd) return RAD_E_SHAPE;
|
||||
std::vector<float> Rh = table_rows(th_tab, hd, 2 * th - 1);
|
||||
std::vector<float> Rw = table_rows(tw_tab, hd, 2 * tw - 1);
|
||||
|
||||
/* Every (channel-ordered) dot is written out in one place so the order is explicit: q[c] times
|
||||
* the row's element c, increasing c. */
|
||||
auto dot = [hd](const float* x, const float* y) {
|
||||
float s = 0.0f;
|
||||
for (int64_t c = 0; c < hd; ++c) s += x[c] * y[c];
|
||||
return s;
|
||||
};
|
||||
|
||||
/* One thread owns one output row; the work unit is about keys * head_dim per head. */
|
||||
REF_PAR_FOR(nseq * R * nh * keys * hd)
|
||||
for (int64_t work = 0; work < nseq * R; ++work) {
|
||||
const int64_t s = work / R, r = work % R;
|
||||
const int64_t ih = r / gw, iw = r % gw;
|
||||
const int64_t ty = win > 0 ? ih / win : 0, tx = win > 0 ? iw / win : 0;
|
||||
const int64_t lh = ih - ty * th, lw = iw - tx * tw;
|
||||
const int64_t base = cu->data ? cu_at(cu, s) : 0;
|
||||
const int64_t out_row = base + r;
|
||||
|
||||
/* logits[keys], qt[hd], acc[hd]. */
|
||||
float* buf = ws_get(keys + 2 * hd);
|
||||
float* logits = buf;
|
||||
float* qt = buf + keys;
|
||||
float* acc = qt + hd;
|
||||
|
||||
for (int64_t h = 0; h < nh; ++h) {
|
||||
const int64_t qbase = rowoff(q, out_row, W) + h * hd;
|
||||
const int64_t qst = laststride(q);
|
||||
for (int64_t c = 0; c < hd; ++c) qt[c] = ldt(q, qbase + c * qst);
|
||||
|
||||
for (int64_t jh = 0; jh < th; ++jh) {
|
||||
const float hr = dot(qt, &Rh[(size_t)((lh - jh + th - 1) * hd)]);
|
||||
for (int64_t jw = 0; jw < tw; ++jw) {
|
||||
float lgt = hr + dot(qt, &Rw[(size_t)((lw - jw + tw - 1) * hd)]);
|
||||
const int64_t kh = ty * th + jh, kw = tx * tw + jw;
|
||||
if (kh < gh && kw < gw) {
|
||||
const int64_t krow = base + kh * gw + kw;
|
||||
const int64_t kb = rowoff(k, krow, W) + h * hd;
|
||||
const int64_t ks = laststride(k);
|
||||
float s_ = 0.0f;
|
||||
for (int64_t c = 0; c < hd; ++c) s_ += qt[c] * ldt(k, kb + c * ks);
|
||||
lgt += scale * s_;
|
||||
}
|
||||
logits[jh * tw + jw] = lgt;
|
||||
}
|
||||
}
|
||||
|
||||
/* Softmax in f32 with the max subtracted, then the weighted sum of v. */
|
||||
float m = -INFINITY;
|
||||
for (int64_t j = 0; j < keys; ++j) m = logits[j] > m ? logits[j] : m;
|
||||
float sum = 0.0f;
|
||||
for (int64_t j = 0; j < keys; ++j) {
|
||||
logits[j] = ref_exp(logits[j] - m);
|
||||
sum += logits[j];
|
||||
}
|
||||
for (int64_t c = 0; c < hd; ++c) acc[c] = 0.0f;
|
||||
const float inv = sum > 0.0f ? 1.0f / sum : 0.0f;
|
||||
for (int64_t jh = 0; jh < th; ++jh) {
|
||||
const int64_t kh = ty * th + jh;
|
||||
if (kh >= gh) continue; /* pad rows carry v = 0 */
|
||||
for (int64_t jw = 0; jw < tw; ++jw) {
|
||||
const int64_t kw = tx * tw + jw;
|
||||
if (kw >= gw) continue;
|
||||
const float p = logits[jh * tw + jw] * inv;
|
||||
if (p == 0.0f) continue;
|
||||
const int64_t krow = base + kh * gw + kw;
|
||||
const int64_t vb = rowoff(v, krow, W) + h * hd;
|
||||
const int64_t vs = laststride(v);
|
||||
for (int64_t c = 0; c < hd; ++c) acc[c] += p * ldt(v, vb + c * vs);
|
||||
}
|
||||
}
|
||||
|
||||
const int64_t ob = rowoff(o, out_row, W) + h * hd;
|
||||
const int64_t os = laststride(o);
|
||||
for (int64_t c = 0; c < hd; ++c) stt(o, ob + c * os, acc[c]);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -35,6 +35,7 @@
|
||||
#include <algorithm>
|
||||
#include <cfloat>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
using namespace ref;
|
||||
|
||||
@@ -235,6 +236,109 @@ int ref_sample_dry(const RadArgs* a, RadStream) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ sample_ngram_ban */
|
||||
/* The windowed no-repeat-ngram ban: Unlimited-OCR's `SlidingWindowNoRepeatNgramProcessor`
|
||||
* (modeling_unlimitedocr.py:353-383), which SGLang ships as
|
||||
* DeepseekOCRNoRepeatNGramLogitProcessor. With the row's history `s[0, hl)` (oldest first, `hl`
|
||||
* committed tokens including the one just emitted), `n` and `w` from the `ngram` plane (an i32
|
||||
* pair a row, {n-gram length, window}):
|
||||
*
|
||||
* search_start = max(0, hl - w) (w <= 0: the whole span)
|
||||
* search_end = hl - n + 1
|
||||
* prefix = s[hl - n + 1, hl) (empty at n == 1)
|
||||
* for idx in [search_start, search_end):
|
||||
* if s[idx, idx + n - 1) == prefix: ban s[idx + n - 1]
|
||||
*
|
||||
* A banned token's logit becomes -infinity, exactly as the reference writes it, so the argmax and
|
||||
* every later stage see the same distribution. The n-gram that spans the window boundary is one
|
||||
* of the searched ones, as in the reference: the window is applied to the START index, not to the
|
||||
* n-gram's end.
|
||||
*
|
||||
* Ids are global and columns are global less `vocab_off`; a banned token on another rank's shard
|
||||
* is that rank's to mask. Rows whose n is 0 (the default) are untouched, so a request without the
|
||||
* ban leaves the logits bit for bit as they were. The scan is O(w * n) a row and compares
|
||||
* integers, so every implementation (this one, libavx, libr4d) agrees by construction.
|
||||
*
|
||||
* The optional `whitelist` bitmask is the reference's whitelist: a token whose column bit is set
|
||||
* in the row's own plane row is removed from the banned set before the -inf writes
|
||||
* (`banned.difference_update(self.whitelist)`, modeling_unlimitedocr.py:379), so it is never
|
||||
* banned. Absent, nothing is exempt -- the default serving form, bit-identical to the ban
|
||||
* without the operand. */
|
||||
int ref_sample_ngram_ban(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 4)) return RAD_E_INVAL;
|
||||
const RadTensor *lg = &a->t[0], *pr = &a->t[1], *hist = &a->t[2], *ng = &a->t[3];
|
||||
const RadTensor* wl = a->n_t > 4 && a->t[4].data ? &a->t[4] : nullptr;
|
||||
const int64_t n_vocab = p_int(a, "n_vocab", lg->rank >= 2 ? lg->shape[lg->rank - 1] : 0);
|
||||
if (n_vocab <= 0) return RAD_E_SHAPE;
|
||||
const int64_t M = numel(lg) / n_vocab;
|
||||
if (M <= 0) return RAD_E_SHAPE;
|
||||
Rows R;
|
||||
RAD_REF_TRY(param_rows(pr, M, &R));
|
||||
const int64_t hmax = numel(hist) / M;
|
||||
if (hmax <= 0) return RAD_E_SHAPE;
|
||||
/* One {n, window} pair a row. At least M pairs, so a plane shared by sparser row sets is not
|
||||
* read past its end. */
|
||||
if (numel(ng) < 2 * M) return RAD_E_SHAPE;
|
||||
const int64_t voff = p_int(a, "vocab_off", 0);
|
||||
const int64_t wwords = (n_vocab + 31) / 32;
|
||||
if (wl && wl->dtype != RAD_I32 && wl->dtype != RAD_U32) return RAD_E_DTYPE;
|
||||
if (wl && numel(wl) < M * wwords) return RAD_E_SHAPE;
|
||||
|
||||
REF_PAR_FOR(M * hmax)
|
||||
for (int64_t m = 0; m < M; ++m) {
|
||||
const RadSampleParams& sp = R.p[m];
|
||||
const int64_t nb = rowoff(ng, m, 2), ns = laststride(ng);
|
||||
const int64_t n = ld_int(ng->dtype, ng->data, nb);
|
||||
const int64_t win_req = ld_int(ng->dtype, ng->data, nb + ns);
|
||||
if (n <= 0) continue;
|
||||
|
||||
/* The whole staged span; the window below keeps its tail. last_n -1 is hist_window's
|
||||
* "the whole span". */
|
||||
int64_t ho = 0, hl = 0;
|
||||
if (!hist_window(sp, -1, hmax, &ho, &hl)) continue;
|
||||
if (hl < n) continue;
|
||||
const int64_t win = win_req > 0 && win_req < hl ? win_req : hl;
|
||||
const int64_t search_start = hl - win;
|
||||
const int64_t search_end = hl - n + 1;
|
||||
if (search_end <= search_start) continue;
|
||||
|
||||
const int64_t hb = rowoff(hist, m, hmax) + ho * laststride(hist);
|
||||
const int64_t hs = laststride(hist);
|
||||
const int64_t lb = rowoff(lg, m, n_vocab), ls = laststride(lg);
|
||||
const int64_t wb = wl ? rowoff(wl, m, wwords) : 0, ws = wl ? laststride(wl) : 0;
|
||||
auto tok_at = [&](int64_t i) {
|
||||
return ld_int(hist->dtype, hist->data, hb + i * hs);
|
||||
};
|
||||
/* The reference removes the whitelist from the banned set before it writes; a column
|
||||
* whose bit is set in the row's whitelist words is therefore never written. */
|
||||
auto exempt = [&](int64_t col) {
|
||||
if (!wl) return false;
|
||||
const uint32_t word = (uint32_t)ld_int(wl->dtype, wl->data, wb + (col / 32) * ws);
|
||||
return ((word >> (uint32_t)(col % 32)) & 1u) != 0u;
|
||||
};
|
||||
/* n == 1 bans every token in the window: the prefix is empty, as in the reference.
|
||||
* The prefix is read once, not per search position: it is the same n-1 tokens
|
||||
* compared at every idx, and the row's history is short (the staged span). */
|
||||
const int64_t plen = n - 1, p0 = hl - plen;
|
||||
std::vector<int64_t> pref((size_t)plen);
|
||||
for (int64_t j = 0; j < plen; ++j) pref[(size_t)j] = tok_at(p0 + j);
|
||||
|
||||
for (int64_t idx = search_start; idx < search_end; ++idx) {
|
||||
bool match = true;
|
||||
for (int64_t j = 0; j < plen; ++j) {
|
||||
if (tok_at(idx + j) != pref[(size_t)j]) { match = false; break; }
|
||||
}
|
||||
if (!match) continue;
|
||||
const int64_t tok = tok_at(idx + plen);
|
||||
const int64_t col = tok - voff;
|
||||
if (tok < 0 || col < 0 || col >= n_vocab) continue;
|
||||
if (exempt(col)) continue;
|
||||
stt(lg, lb + col * ls, -INFINITY);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ sample_temp */
|
||||
/* temp <= 0 leaves the row untouched; greedy decoding is `sample_argmax`. */
|
||||
int ref_sample_temp(const RadArgs* a, RadStream) {
|
||||
|
||||
+105
-12
@@ -1398,6 +1398,40 @@ int ref_chan_stats_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* ou
|
||||
return o.finish("chan_stats", operand, out);
|
||||
}
|
||||
|
||||
/* The SAM tower's attention (ref_sam_attn.cpp): a row of `n_head * head_dim`, one raster
|
||||
* grid_h x grid_w segment a cu entry, and the two rel_pos tables. Their length follows the contract
|
||||
* in arch/common/rad_block_sam.h: 2*maxdist-1 rows with maxdist the window, or the longer grid axis
|
||||
* for a global layer (which is the length a resampled table needs; the op resamples along dim 0
|
||||
* either way). */
|
||||
int ref_sam_attn_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const int64_t M = gi(p, n_p, "M", 0);
|
||||
const int64_t hd = gi(p, n_p, "head_dim", 0);
|
||||
const int64_t nh = gi(p, n_p, "n_head", 0);
|
||||
const int64_t gh = gi(p, n_p, "grid_h", 0);
|
||||
const int64_t gw = gi(p, n_p, "grid_w", 0);
|
||||
const int64_t win = gi(p, n_p, "window", 0);
|
||||
if (M <= 0 || hd <= 0 || nh <= 0 || gh <= 0 || gw <= 0 || win < 0) return RAD_E_UNSUPPORTED;
|
||||
/* A shape hook answers "describe this geometry", so an unbuildable one spells E_UNSUPPORTED
|
||||
* (the harness convention); the kernels' own launch checks report E_SHAPE for the same
|
||||
* inputs. */
|
||||
const int64_t W = nh * hd;
|
||||
const int64_t S = n_seq_of(p, n_p);
|
||||
const int64_t maxd = win > 0 ? win : (gh > gw ? gh : gw);
|
||||
const int64_t tab = 2 * maxd - 1;
|
||||
const uint32_t D = act_dt(p, n_p);
|
||||
|
||||
Opd o;
|
||||
o.t(D, { M, W }); /* q */
|
||||
o.t(D, { M, W }); /* k */
|
||||
o.t(D, { M, W }); /* v */
|
||||
/* [0, ..., M], the batch's shape, not a draw. */
|
||||
o.t_idx({ S + 1 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_seqlens */
|
||||
o.t(D, { M, W }); /* out */
|
||||
o.t(D, { tab, hd }); /* rel_pos_h */
|
||||
o.t(D, { tab, hd }); /* rel_pos_w */
|
||||
return o.finish("sam_attn", operand, out);
|
||||
}
|
||||
|
||||
int ref_kv_store_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const int64_t M = gi(p, n_p, "M", 0);
|
||||
const int64_t hd = gi(p, n_p, "head_dim", 0);
|
||||
@@ -1669,8 +1703,55 @@ int ref_moe_scatter_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* o
|
||||
return o.finish("moe_scatter", operand, out);
|
||||
}
|
||||
|
||||
/* `a_order` decides the activation's row count: one per token, or one per (token, slot) in
|
||||
* scatter order. */
|
||||
/* The two shape lists concatenated, with `expert_ids` named ONCE as an output -- it is what the
|
||||
* selection writes and what the sort reads. The sort's three outputs are sized by THIS RANK'S
|
||||
* SLICE (`n_local`, absent means the slice is the router), exactly as in libr4d's shape. */
|
||||
int ref_router_topk_scatter_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const int64_t M = gi(p, n_p, "M", 0);
|
||||
const int64_t ne = gi(p, n_p, "n_expert", 0);
|
||||
const int64_t k = gi(p, n_p, "top_k", 0);
|
||||
const int64_t nl = gi(p, n_p, "n_local", ne);
|
||||
if (M <= 0 || ne <= 0 || k <= 0 || k > ne || nl <= 0 || nl > ne) return RAD_E_UNSUPPORTED;
|
||||
const uint32_t D = act_dt(p, n_p);
|
||||
Opd o;
|
||||
o.t(D, { M, ne }); /* logits */
|
||||
o.t((uint32_t)RAD_I32, { M, k }); /* expert_ids */
|
||||
o.t(D, { M, k }); /* expert_w */
|
||||
o.t((uint32_t)RAD_I32, { M * k }); /* sorted_tok */
|
||||
o.t((uint32_t)RAD_I32, { nl + 1 }); /* expert_offset */
|
||||
o.t((uint32_t)RAD_I32, { nl }); /* expert_count */
|
||||
return o.finish("router_topk_scatter", operand, out);
|
||||
}
|
||||
|
||||
/* The router GEMM's list, the pair's list, and -- with the gate present -- the gate's one-column
|
||||
* list, with `logits` named once as the GEMM's output. `gate_b`/`gate` come together or not: the
|
||||
* operand count carries it, as in libr4d's shape. */
|
||||
int ref_router_gemm_topk_scatter_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const int64_t M = gi(p, n_p, "M", 0);
|
||||
const int64_t K = gi(p, n_p, "K", 0);
|
||||
const int64_t ne = gi(p, n_p, "n_expert", 0);
|
||||
const int64_t k = gi(p, n_p, "top_k", 0);
|
||||
const int64_t nl = gi(p, n_p, "n_local", ne);
|
||||
if (M <= 0 || K <= 0 || ne <= 0 || k <= 0 || k > ne || nl <= 0 || nl > ne)
|
||||
return RAD_E_UNSUPPORTED;
|
||||
const uint32_t D = act_dt(p, n_p);
|
||||
Opd o;
|
||||
o.t(D, { M, K }); /* a */
|
||||
o.t(D, { ne, K }); /* b: the router */
|
||||
o.t(D, { 1, K }); /* gate_b: the shared expert's gate */
|
||||
o.t(D, { M, ne }); /* logits */
|
||||
o.t((uint32_t)RAD_I32, { M, k }); /* expert_ids */
|
||||
o.t(D, { M, k }); /* expert_w */
|
||||
o.t((uint32_t)RAD_I32, { M * k }); /* sorted_tok */
|
||||
o.t((uint32_t)RAD_I32, { nl + 1 }); /* expert_offset */
|
||||
o.t((uint32_t)RAD_I32, { nl }); /* expert_count */
|
||||
o.t(D, { M, 1 }); /* gate */
|
||||
return o.finish("router_gemm_topk_scatter", operand, out);
|
||||
}
|
||||
|
||||
/* `a_order` decides the activation's row count: one per token, or one per (token, slot) already
|
||||
* in the scatter's order. A described case that got this wrong would build the operand at the
|
||||
* extent the WRONG reading wants, and the fault it names would go unseen. */
|
||||
static inline bool sorted_a_order(const RadParam* p, int n_p) {
|
||||
const char* s = gs(p, n_p, "a_order");
|
||||
return s && std::strcmp(s, "sorted") == 0;
|
||||
@@ -2321,6 +2402,28 @@ int ref_sample_dry_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* ou
|
||||
return penalty_shape(p, n_p, operand, "sample_dry", true, out);
|
||||
}
|
||||
|
||||
/* The n-gram ban reads the same history the two penalty stages do and writes the logits in place,
|
||||
* and adds one small plane beside them: `ngram`, an i32 {n-gram length, window} pair a row. It is
|
||||
* a plane of its own rather than fields in `params` because the params row is a fixed 24-word wire
|
||||
* format shared by every sampler op (and recorded in the kbench fixtures). Drawn in 0..63 so both
|
||||
* a length inside the 64-token history and the 0 (= off) and whole-window forms occur.
|
||||
*
|
||||
* The optional `whitelist` bitmask is sample_mask's plane shape (word w bit b covers column
|
||||
* 32w + b, a SET bit marking an exempt token), addressed by the sampled row itself; a random draw
|
||||
* fills it with random bits, so a sweep exercises exemptions as often as plain bans. */
|
||||
int ref_sample_ngram_ban_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
int64_t M = 0, nv = 0;
|
||||
if (sample_vocab(p, n_p, &M, &nv) < 0) return RAD_E_UNSUPPORTED;
|
||||
Opd o;
|
||||
o.t((uint32_t)RAD_F32, { M, nv }); /* logits, INOUT */
|
||||
sample_params(o, M, REF_SAMPLE_HIST, 0); /* params */
|
||||
o.t_idx({ M, (int64_t)REF_SAMPLE_HIST }, nv, -1,
|
||||
(uint32_t)RAD_OPD_F_IDX_HISTORY); /* history */
|
||||
o.t_idx({ M, 2 }, 64, -1, 0); /* ngram: {n, window} */
|
||||
o.t((uint32_t)RAD_I32, { M, (nv + 31) / 32 }); /* whitelist, optional */
|
||||
return o.finish("sample_ngram_ban", operand, out);
|
||||
}
|
||||
|
||||
int ref_sample_temp_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
int64_t M = 0, nv = 0;
|
||||
if (sample_vocab(p, n_p, &M, &nv) < 0) return RAD_E_UNSUPPORTED;
|
||||
@@ -3534,16 +3637,6 @@ int ref_tile_stitch_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* o
|
||||
return o.finish("tile_stitch", operand, out);
|
||||
}
|
||||
|
||||
int ref_patch_pix8_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const int64_t M = gi(p, n_p, "M", 0), pp = gi(p, n_p, "p", 0), C = gi(p, n_p, "C", 0);
|
||||
const int64_t w = cols_for(M, 1), R = w ? M / w : 0;
|
||||
if (!w || pp <= 0 || C <= 0) return RAD_E_UNSUPPORTED;
|
||||
Opd o;
|
||||
o.t(act_dt(p, n_p), { R, w * C * pp * pp }); /* x: patch rows */
|
||||
o.t((uint32_t)RAD_U8, { R * pp, w * pp * C }); /* y: bytes */
|
||||
return o.finish("patch_pix8", operand, out);
|
||||
}
|
||||
|
||||
int ref_stft_logmel_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const int64_t M = gi(p, n_p, "M", 0), hop = gi(p, n_p, "hop", 0), nfft = gi(p, n_p, "nfft", 0);
|
||||
const int64_t nm = gi(p, n_p, "n_mel", 0), ch = gi(p, n_p, "ch", 0), F = nfft / 2 + 1;
|
||||
|
||||
Reference in new issue
Block a user