diff --git a/docs/OPS.md b/docs/OPS.md index 259aa2e6..2599c162 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -272,6 +272,7 @@ libr4d's `swiglu_clamped_bf16` serves bf16 in and out at any width, pitched rows SiLU is taken first and its value clipped above, so a gate far past `limit` gives exactly `limit` where `swiglu_clamped` gives `silu(limit)` (3.93 at a limit of 4). HF's reference model for Ling-3.0 ignores the clamp; the served form is the one checkpoints are evaluated with. +libr4d's `swiglu_step_bf16` serves it as `swiglu_clamped_bf16` does. **`add` and `mul`** broadcast a `b` of exactly `n` elements along the rows of a taller output (a bias add). Nothing else broadcasts, in these or any other elementwise op. `add`'s `div` divides @@ -2215,6 +2216,10 @@ groups of at least two; a group's rank is the sum of its two largest `p + bias`; best groups are kept, ties to the lower group; the selection is `router_sigmoid_topk`'s over the kept groups' experts only, and the weights are the same. `top_k` is at most the kept experts. +libr4d's `router_sigmoid_group_topk_f32` is `router_sigmoid_topk_f32`'s wave with the groups ranked +first, a lane a group: up to 512 experts in up to 32 groups, `top_k` up to 32, pitched rows, `M` up +to 65535. + **`router_sigmoid_topk_scatter`** (device-only) is `router_sigmoid_topk` and `moe_scatter` over its `ids` in one launch, and with `gate` `[M, 1]` also the `fill` of an ungated shared arm's gate with 1 (GLM-5.3's shared expert has no gate, and the gather reads one). `n_expert`, `n_local`, @@ -3322,6 +3327,11 @@ With `gate` `[M, >= heads]` (a head's gate logit) the output is `bf16(bf16(out) * bf16(sigmoid(gate)))`, Ling's head-wise attention gate taken on the latent, ahead of the expansion. The softmax is f32 and `out` rounded once before the gate. +libr4d's `mla_attn_paged_bf16` serves `latent_dim` 512 and `rope_dim` 64, up to 64 heads, pages of +up to 256 tokens: a wave a (query row, head), its lanes holding 16 latent and 2 rotary columns each, +so a score is one wave sum. A short batch splits each row's history over waves and joins the f32 +partials. + `mla_project` moves a query into the latent and a latent result out of it, through the bf16 weight `b` `[heads*2*head_dim, latent_dim]` that stores each head's key rows, then its value rows. `mode=absorb` multiplies `a` `[M, heads, head_dim]` by the head's key block as stored, @@ -3331,10 +3341,10 @@ accumulate in f32 and round once to bf16. The KV cache stays latent; only this w per-head width. Its rows are head-major, so a tensor-parallel slice of whole heads is a row range. `a` and `y` may also be `[M, heads*width]`, heads contiguous, with their own token pitch. -libr4d's `mla_project_bf16` serves `head_dim` 256 and `latent_dim` 512, up to 64 heads, pitched -tensors. It takes up to eight rows a thread (`absorb`) or a wave (`expand`), loading each weight -element once for them, with every row's sum in the same order whatever the group, so a row's bytes -do not depend on the batch. +libr4d's `mla_project_bf16` serves `head_dim` 128 or 256 and `latent_dim` 512, up to 64 heads, +pitched tensors. It takes up to eight rows a thread (`absorb`) or a wave (`expand`), loading each +weight element once for them, with every row's sum in the same order whatever the group, so a row's +bytes do not depend on the batch. ## Draft heads diff --git a/libr4d/r4d_glm.hip b/libr4d/r4d_glm.hip index f4e0440d..0fa85cd8 100644 --- a/libr4d/r4d_glm.hip +++ b/libr4d/r4d_glm.hip @@ -183,6 +183,93 @@ __device__ __forceinline__ int router_sigmoid_row(const float* logits, const flo } return e; } +// router_sigmoid_group_topk in one wave per row: router_sigmoid_row's keys, but only the experts of +// the `kg` best of `ng` equal groups are selectable. A group ranks by the sum of its two highest +// ranks; lane g holds group g's sum (ng <= 32), and the groups are taken as the experts are, the +// largest first, equal sums to the lower group, a group with no finite pair never. Then the +// selection, the weights and the stores are router_sigmoid_row's. +template +__global__ void __launch_bounds__(128) + router_group_wave_kernel(const float* logits, const float* bias, int* ids, float* weights, + long lp, long bp, long ip, long wp, int m, int ne, int k, int ng, + int kg, int norm, float factor) { + const int lane = threadIdx.x & 31, r = blockIdx.x * 4 + (threadIdx.x >> 5); + if (r >= m) return; + const int gs = ne / ng; + float p[OWN], rank[OWN]; +#pragma unroll + for (int i = 0; i < OWN; ++i) { + const int e = lane + 32 * i, s = e < ne ? e : 0; + p[i] = 1.0f / (1.0f + expf(-logits[(long)r * lp + s])); + rank[i] = e < ne ? p[i] + bias[(long)s * bp] : -INFINITY; + } + float group = -INFINITY; + for (int g = 0; g < ng; ++g) { + float t0 = -INFINITY, t1 = -INFINITY; +#pragma unroll + for (int i = 0; i < OWN; ++i) { + const int e = lane + 32 * i; + if (e < ne && e / gs == g) { + const float v = rank[i]; + if (v > t0) { + t1 = t0; + t0 = v; + } else if (v > t1) + t1 = v; + } + } +#pragma unroll + for (int mask = 16; mask; mask >>= 1) { + const float o0 = __shfl_xor(t0, mask, 32), o1 = __shfl_xor(t1, mask, 32); + const float hi = fmaxf(t0, o0), lo = fmaxf(fminf(t0, o0), fmaxf(t1, o1)); + t0 = hi; + t1 = lo; + } + if (lane == g) group = t0 + t1; + } + unsigned long long gkey = lane < ng && group > -INFINITY ? router_rank_key(group, lane) : 0ull; + unsigned kept = 0; // bit g: group g is kept + unsigned long long below = ~0ull; + for (int j = 0; j < kg; ++j) { + const unsigned long long best = router_wave_max(gkey < below ? gkey : 0ull); + if (best) kept |= 1u << (int)~(uint32_t)best; + below = best; + } + unsigned long long key[OWN]; +#pragma unroll + for (int i = 0; i < OWN; ++i) { + const int e = lane + 32 * i; + key[i] = e < ne && ((kept >> (e / gs)) & 1u) ? router_rank_key(rank[i], e) : 0ull; + } + unsigned long long mine = 0; + below = ~0ull; + for (int j = 0; j < k; ++j) { + unsigned long long best = 0; +#pragma unroll + for (int i = 0; i < OWN; ++i) { + const unsigned long long c = key[i] < below ? key[i] : 0ull; + best = c > best ? c : best; + } + best = router_wave_max(best); + if (lane == j) mine = best; + below = best; + } + const int e = mine ? (int)~(uint32_t)mine : 0; + float chosen = 0; +#pragma unroll + for (int i = 0; i < OWN; ++i) { + const float v = __shfl(p[i], e & 31, 32); + if ((e >> 5) == i) chosen = v; + } + float total = 0; + for (int j = 0; j < k; ++j) + total += __int_as_float(__builtin_amdgcn_readlane(__float_as_int(chosen), j)); + const float mult = norm ? factor / (total + 1e-20f) : factor; + if (lane < k) { + ids[(long)r * ip + lane] = e; + weights[(long)r * wp + lane] = chosen * mult; + } +} template __global__ void __launch_bounds__(128) router_sigmoid_wave_kernel(const float* logits, const float* bias, int* ids, float* weights, @@ -248,6 +335,35 @@ int router_body(const RadArgs* a, RadStream stream) { lg.stride[0], bias.stride[0], ids.stride[0], w.stride[0], (int)lg.shape[0], (int)ne, (int)k, norm, factor); } +int router_group_body(const RadArgs* a, RadStream stream) { + if (!a || a->n_t < 4) return RAD_E_INVAL; + const auto &lg = a->t[0], &bias = a->t[1], &ids = a->t[2], &w = a->t[3]; + const long ne = r4d_geti_or(a, "n_expert", 0), k = r4d_geti_or(a, "top_k", 0), + ng = r4d_geti_or(a, "n_group", 0), kg = r4d_geti_or(a, "topk_group", 0); + const float factor = (float)r4d_getf(a, "route_scale", 0); + if (lg.dtype != RAD_F32 || bias.dtype != RAD_F32 || ids.dtype != RAD_I32 || w.dtype != RAD_F32) + return RAD_E_DTYPE; + if (ne < 1 || ne > 512 || k < 1 || k > 32 || ng < 1 || ng > 32 || ne % ng || ne / ng < 2 || + kg < 1 || kg > ng || k > kg * (ne / ng) || !std::isfinite(factor) || factor <= 0 || + !lg.data || !bias.data || !ids.data || !w.data || lg.rank != 2 || lg.shape[0] < 1 || + lg.shape[0] > 65535 || lg.shape[1] != ne || bias.rank != 1 || bias.shape[0] != ne || + ids.rank != 2 || w.rank != 2 || ids.shape[0] != lg.shape[0] || w.shape[0] != lg.shape[0] || + ids.shape[1] != k || w.shape[1] != k || lg.stride[1] != 1 || ids.stride[1] != 1 || + w.stride[1] != 1 || lg.stride[0] < ne || ids.stride[0] < k || w.stride[0] < k || + bias.stride[0] < 1) + return RAD_E_SHAPE; + const int norm = (int)(r4d_geti_or(a, "norm", 0) != 0); + const dim3 grid((unsigned)((lg.shape[0] + 3) / 4)); + if (ne <= 9 * 32) + return R4D_EMIT(stream, router_group_wave_kernel<9>, grid, dim3(128), 0, + (const float*)lg.data, (const float*)bias.data, (int*)ids.data, + (float*)w.data, lg.stride[0], bias.stride[0], ids.stride[0], w.stride[0], + (int)lg.shape[0], (int)ne, (int)k, (int)ng, (int)kg, norm, factor); + return R4D_EMIT(stream, router_group_wave_kernel<16>, grid, dim3(128), 0, + (const float*)lg.data, (const float*)bias.data, (int*)ids.data, (float*)w.data, + lg.stride[0], bias.stride[0], ids.stride[0], w.stride[0], (int)lg.shape[0], + (int)ne, (int)k, (int)ng, (int)kg, norm, factor); +} /* Operands: router_sigmoid_topk's four, moe_scatter's three outputs, then the optional gate and the * optional inverse. The sort is the single-workgroup form, so M * top_k must fit it; a larger pass * is refused rather than served at another cost. */ @@ -321,7 +437,18 @@ __global__ void swiglu_clamped_kernel(const uint16_t* gu, uint16_t* y, long gp, const float u = fminf(fmaxf(bf16_to_f32(gu[r * gp + n + i]), -limit), limit); y[r * yp + i] = f32_to_bf16((g / (1.0f + expf(-g))) * u); } -int clamped_body(const RadArgs* a, RadStream stream) { +// swiglu_step: the SiLU first, its value clipped above (Ling-3.0; vLLM's SwigluStepAndMul). +__global__ void swiglu_step_kernel(const uint16_t* gu, uint16_t* y, long gp, long yp, int n, + float limit) { + const long r = blockIdx.x; + const int i = blockIdx.y * 256 + threadIdx.x; + if (i >= n) return; + const float x = bf16_to_f32(gu[r * gp + i]); + const float g = fminf(x / (1.0f + expf(-x)), limit); + const float u = fminf(fmaxf(bf16_to_f32(gu[r * gp + n + i]), -limit), limit); + y[r * yp + i] = f32_to_bf16(g * u); +} +int clamped_body(const RadArgs* a, RadStream stream, bool step = false) { if (!a || a->n_t < 2) return RAD_E_INVAL; const auto &gu = a->t[0], &y = a->t[1]; const long n = r4d_geti_or(a, "n", 0); @@ -332,6 +459,10 @@ int clamped_body(const RadArgs* a, RadStream stream) { gu.shape[0] != y.shape[0] || gu.shape[1] != 2 * n || y.shape[1] != n || gu.stride[1] != 1 || y.stride[1] != 1 || gu.stride[0] < 2 * n || y.stride[0] < n) return RAD_E_SHAPE; + if (step) + return R4D_EMIT(stream, swiglu_step_kernel, dim3(y.shape[0], (n + 255) / 256), dim3(256), 0, + (const uint16_t*)gu.data, (uint16_t*)y.data, gu.stride[0], y.stride[0], + (int)n, limit); return R4D_EMIT(stream, swiglu_clamped_kernel, dim3(y.shape[0], (n + 255) / 256), dim3(256), 0, (const uint16_t*)gu.data, (uint16_t*)y.data, gu.stride[0], y.stride[0], (int)n, limit); @@ -405,6 +536,12 @@ int clamped_quant_body(const RadArgs* a, RadStream stream) { extern "C" int r4d_rad_swiglu_clamped(const RadArgs* a, RadStream stream) { return clamped_body(a, stream); } +extern "C" int r4d_rad_swiglu_step(const RadArgs* a, RadStream stream) { + return clamped_body(a, stream, true); +} +extern "C" int r4d_rad_router_sigmoid_group_topk(const RadArgs* a, RadStream stream) { + return router_group_body(a, stream); +} extern "C" int r4d_rad_swiglu_clamped_quant_fp8(const RadArgs* a, RadStream stream) { return clamped_quant_body(a, stream); } diff --git a/libr4d/r4d_mla.hip b/libr4d/r4d_mla.hip index 06f56fa0..2c6da49a 100644 --- a/libr4d/r4d_mla.hip +++ b/libr4d/r4d_mla.hip @@ -24,7 +24,7 @@ struct ProjectMeta { * sum runs over j in the same order whatever R is (expand: each lane's share in ascending j, then * r4d_xor_sum<32>), so a row's bytes do not depend on the batch it is in. A tail group past the * last row reads that row again and stores nothing for it. */ -template +template __global__ void project_absorb_rows(const uint16_t* x, const uint16_t* w, uint16_t* y, ProjectMeta m) { const int col = blockIdx.x * 128 + threadIdx.x, head = blockIdx.y, r0 = blockIdx.z * R; @@ -35,8 +35,8 @@ __global__ void project_absorb_rows(const uint16_t* x, const uint16_t* w, uint16 float sum[R]; #pragma unroll for (int r = 0; r < R; ++r) sum[r] = 0; - for (int j = 0; j < 256; ++j) { - const float wv = bf16_to_f32(w[((long)head * 512 + j) * m.wp + col]); + for (int j = 0; j < HD; ++j) { + const float wv = bf16_to_f32(w[((long)head * 2 * HD + j) * m.wp + col]); #pragma unroll for (int r = 0; r < R; ++r) sum[r] = fmaf(bf16_to_f32(xr[r][j]), wv, sum[r]); } @@ -44,7 +44,7 @@ __global__ void project_absorb_rows(const uint16_t* x, const uint16_t* w, uint16 for (int r = 0; r < R; ++r) if (r0 + r < m.rows) y[(long)(r0 + r) * m.yr + head * m.yh + col] = f32_to_bf16(sum[r]); } -template +template __global__ void project_expand_rows(const uint16_t* x, const uint16_t* w, uint16_t* y, ProjectMeta m) { const int lane = threadIdx.x & 31, col = blockIdx.x * 4 + (threadIdx.x >> 5), head = blockIdx.y, @@ -52,7 +52,7 @@ __global__ void project_expand_rows(const uint16_t* x, const uint16_t* w, uint16 const uint16_t* xr[R]; #pragma unroll for (int r = 0; r < R; ++r) xr[r] = x + (long)min(r0 + r, m.rows - 1) * m.xr + head * m.xh; - const uint16_t* const wr = w + ((long)head * 512 + 256 + col) * m.wp; + const uint16_t* const wr = w + ((long)head * 2 * HD + HD + col) * m.wp; float sum[R]; #pragma unroll for (int r = 0; r < R; ++r) sum[r] = 0; @@ -77,7 +77,7 @@ int project_body(const RadArgs* a, RadStream stream) { const char* mode = r4d_gets(a, "mode"); const bool absorb = mode && !std::strcmp(mode, "absorb"), expand = mode && !std::strcmp(mode, "expand"); - const long h = r4d_geti_or(a, "heads", 0); + const long h = r4d_geti_or(a, "heads", 0), hd = r4d_geti_or(a, "head_dim", 0); auto heads_view = [&](RadTensor& t, long width) { if (h > 0 && t.rank == 2 && t.shape[1] == h * width) { t.rank = 3; @@ -87,15 +87,15 @@ int project_body(const RadArgs* a, RadStream stream) { t.stride[1] *= width; } }; - heads_view(x, absorb ? 256 : 512); - heads_view(y, absorb ? 512 : 256); + heads_view(x, absorb ? hd : 512); + heads_view(y, absorb ? 512 : hd); if (x.dtype != RAD_BF16 || w.dtype != RAD_BF16 || y.dtype != RAD_BF16) return RAD_E_DTYPE; if (!x.data || !w.data || !y.data) return RAD_E_INVAL; - if ((!absorb && !expand) || h < 1 || h > 64 || r4d_geti_or(a, "head_dim", 0) != 256 || + if ((!absorb && !expand) || h < 1 || h > 64 || (hd != 128 && hd != 256) || r4d_geti_or(a, "latent_dim", 0) != 512 || x.rank != 3 || w.rank != 2 || y.rank != 3 || x.shape[0] < 1 || x.shape[0] > 65535 || x.shape[1] != h || - x.shape[2] != (absorb ? 256 : 512) || w.shape[0] != h * 512 || w.shape[1] != 512 || - y.shape[0] != x.shape[0] || y.shape[1] != h || y.shape[2] != (absorb ? 512 : 256) || + x.shape[2] != (absorb ? hd : 512) || w.shape[0] != h * 2 * hd || w.shape[1] != 512 || + y.shape[0] != x.shape[0] || y.shape[1] != h || y.shape[2] != (absorb ? 512 : hd) || x.stride[2] != 1 || w.stride[1] != 1 || y.stride[2] != 1 || x.stride[1] < x.shape[2] || x.stride[0] < h * x.stride[1] || w.stride[0] < 512 || y.stride[1] < y.shape[2] || y.stride[0] < h * y.stride[1]) @@ -107,20 +107,26 @@ int project_body(const RadArgs* a, RadStream stream) { auto* yp = (uint16_t*)y.data; /* The largest of 8, 4, 2 and 1 rows a group that the batch fills. */ const int R = m.rows >= 8 ? 8 : m.rows >= 4 ? 4 : m.rows >= 2 ? 2 : 1; -#define MLA_PROJECT_ROWS(RR) \ +#define MLA_PROJECT_HD(RR, HD) \ do { \ const unsigned groups = (unsigned)((m.rows + RR - 1) / RR); \ if (absorb) \ - return R4D_EMIT(stream, (project_absorb_rows), dim3(4, h, groups), dim3(128), 0, \ - xp, wp, yp, m); \ - return R4D_EMIT(stream, (project_expand_rows), dim3(64, h, groups), dim3(128), 0, xp, \ - wp, yp, m); \ + return R4D_EMIT(stream, (project_absorb_rows), dim3(4, h, groups), dim3(128), \ + 0, xp, wp, yp, m); \ + return R4D_EMIT(stream, (project_expand_rows), dim3(HD / 4, h, groups), dim3(128), \ + 0, xp, wp, yp, m); \ + } while (0) +#define MLA_PROJECT_ROWS(RR) \ + do { \ + if (hd == 128) MLA_PROJECT_HD(RR, 128); \ + MLA_PROJECT_HD(RR, 256); \ } while (0) if (R == 8) MLA_PROJECT_ROWS(8); if (R == 4) MLA_PROJECT_ROWS(4); if (R == 2) MLA_PROJECT_ROWS(2); MLA_PROJECT_ROWS(1); #undef MLA_PROJECT_ROWS +#undef MLA_PROJECT_HD } constexpr int D = 512, PART = D + 2; constexpr int64_t scratch_bytes = 512ll * PART * 4; @@ -219,6 +225,171 @@ __global__ __launch_bounds__(128) void merge(const float* scratch, uint16_t* out out[(long)r * m.orr + (long)head * m.oh + lane * 16 + j] = f32_to_bf16(den > 0 ? value[j] / den : 0); } +/* mla_attn_paged: dense causal latent attention over a cache row of [latent 512 | rope 64], one + * page table a sequence (Ling-3.0's MLA). A wave a (query row, head) as `attend`: lane l holds + * latent columns 16l..16l+15 and rotary columns 2l, 2l+1, so a score is one wave sum. A row's + * sequence, position and causal bound come from cu_seqlens and seqused as attn_paged reads them. + * A short batch splits its history over waves and `merge_paged` joins the f32 partials; the + * optional head gate multiplies the rounded output by the rounded sigmoid of the head's logit. */ +constexpr int RD = 64; +struct PagedMeta { + long qr, qh, rr, rh, kp, kt, bp, bc, orr, oh, gr; + int rows, heads, seqs, blocks, bs, pages, splits; + float scale; +}; +__device__ __forceinline__ int paged_seq(const int* cu, int seqs, int r) { + int s = 0; + while (s + 1 < seqs && cu[s + 1] <= r) ++s; + return s; +} +__device__ __forceinline__ void paged_store(uint16_t* out, const uint16_t* gate, const PagedMeta& m, + int r, int head, int lane, const float (&value)[16], + float den) { + float g = 1.0f; + if (gate) g = bf16_to_f32(f32_to_bf16(1.0f / (1.0f + expf(-bf16_to_f32(gate[(long)r * m.gr + head]))))); +#pragma unroll + for (int j = 0; j < 16; ++j) { + float v = den > 0 ? value[j] / den : 0; + if (gate) v = bf16_to_f32(f32_to_bf16(v)) * g; + out[(long)r * m.orr + (long)head * m.oh + lane * 16 + j] = f32_to_bf16(v); + } +} +__global__ __launch_bounds__(128) void attend_paged(const uint16_t* q, const uint16_t* qrot, + const uint16_t* kv, const int* bt, + const int* used, const int* cu, + const uint16_t* gate, uint16_t* out, + float* scratch, PagedMeta m) { + const int lane = threadIdx.x & 31, head = blockIdx.y * 4 + (threadIdx.x >> 5), r = blockIdx.x, + split = blockIdx.z; + if (head >= m.heads) return; + const int s = paged_seq(cu, m.seqs, r); + const int qlen = cu[s + 1] - cu[s], i = r - cu[s]; + const int live = min(max(used[s] - qlen + i + 1, 0), m.blocks * m.bs); + const int begin = (int)((long)live * split / m.splits), + end = (int)((long)live * (split + 1) / m.splits); + float query[16], value[16] = {}; + load_latent(q + (long)r * m.qr + (long)head * m.qh + lane * 16, query); + const uint16_t* const qp = qrot + (long)r * m.rr + (long)head * m.rh + lane * 2; + const float rq0 = bf16_to_f32(qp[0]), rq1 = bf16_to_f32(qp[1]); + float max_score = -INFINITY, den = 0; + for (int token = begin; token < end; ++token) { + const int page = bt[(long)s * m.bp + (token / m.bs) * m.bc]; + if (page < 0 || page >= m.pages) continue; + const uint16_t* const row = kv + (long)page * m.kp + (token % m.bs) * m.kt; + float key[16]; + load_latent(row + lane * 16, key); + float score = rq0 * bf16_to_f32(row[D + lane * 2]) + rq1 * bf16_to_f32(row[D + lane * 2 + 1]); +#pragma unroll + for (int j = 0; j < 16; ++j) score += query[j] * key[j]; + score = r4d_wave_sum(score) * m.scale; + const bool higher = score > max_score; + const float weight = expf(higher ? max_score - score : score - max_score); + if (higher) { +#pragma unroll + for (int j = 0; j < 16; ++j) value[j] = value[j] * weight + key[j]; + den = den * weight + 1; + max_score = score; + } else { +#pragma unroll + for (int j = 0; j < 16; ++j) value[j] += key[j] * weight; + den += weight; + } + } + if (m.splits == 1) { + paged_store(out, gate, m, r, head, lane, value, den); + } else { + float* dst = scratch + (((long)r * m.heads + head) * m.splits + split) * PART; +#pragma unroll + for (int j = 0; j < 16; ++j) dst[lane * 16 + j] = value[j]; + if (!lane) { + dst[D] = max_score; + dst[D + 1] = den; + } + } +} +__global__ __launch_bounds__(128) void merge_paged(const float* scratch, const uint16_t* gate, + uint16_t* out, PagedMeta m) { + const int lane = threadIdx.x & 31, head = blockIdx.y * 4 + (threadIdx.x >> 5), r = blockIdx.x; + if (head >= m.heads) return; + const float* src = scratch + ((long)r * m.heads + head) * m.splits * PART; + float max_score = -INFINITY; + for (int s = 0; s < m.splits; ++s) + if (src[s * PART + D + 1] > 0) max_score = fmaxf(max_score, src[s * PART + D]); + float value[16] = {}, den = 0; + for (int s = 0; s < m.splits; ++s) { + const float part_den = src[s * PART + D + 1]; + if (!(part_den > 0)) continue; + const float w = expf(src[s * PART + D] - max_score); + den += part_den * w; +#pragma unroll + for (int j = 0; j < 16; ++j) value[j] += src[s * PART + lane * 16 + j] * w; + } + paged_store(out, gate, m, r, head, lane, value, den); +} +/* Operands: q [M, heads, 512], q_rope [M, heads, 64], kv [pages, 1, bs, >= 576], block_table + * [seqs, blocks], seqused [seqs], cu_seqlens [seqs + 1], gate [M, >= heads] (optional), out + * [M, heads, 512]. */ +int paged_body(const RadArgs* a, RadStream stream) { + if (!a || a->n_t < 8) return RAD_E_INVAL; + RadTensor q = a->t[0], qr = a->t[1], o = a->t[7]; + const auto &kv = a->t[2], &bt = a->t[3], &su = a->t[4], &cu = a->t[5]; + const RadTensor* gate = r4d_opt(a, 6); + const long heads = r4d_geti_or(a, "heads", 0), bs = r4d_geti_or(a, "block_size", 0); + const float scale = (float)r4d_getf(a, "scale", 0); + auto heads_view = [&](RadTensor& t, long width) { + if (heads > 0 && t.rank == 2 && t.shape[1] == heads * width) { + t.rank = 3; + t.shape[1] = heads; + t.shape[2] = width; + t.stride[2] = t.stride[1]; + t.stride[1] *= width; + } + }; + heads_view(q, D); + heads_view(qr, RD); + heads_view(o, D); + if (q.dtype != RAD_BF16 || qr.dtype != RAD_BF16 || kv.dtype != RAD_BF16 || + o.dtype != RAD_BF16 || bt.dtype != RAD_I32 || su.dtype != RAD_I32 || cu.dtype != RAD_I32 || + (gate && gate->dtype != RAD_BF16)) + return RAD_E_DTYPE; + if (!q.data || !qr.data || !kv.data || !bt.data || !su.data || !cu.data || !o.data) + return RAD_E_INVAL; + if (r4d_geti_or(a, "latent_dim", 0) != D || r4d_geti_or(a, "rope_dim", 0) != RD || heads < 1 || + heads > 64 || bs < 1 || bs > 256 || !std::isfinite(scale) || scale <= 0 || q.rank != 3 || + q.shape[0] < 1 || q.shape[0] > 65535 || q.shape[1] != heads || q.shape[2] != D || + q.stride[2] != 1 || q.stride[1] < D || q.stride[0] < heads * q.stride[1] || qr.rank != 3 || + qr.shape[0] != q.shape[0] || qr.shape[1] != heads || qr.shape[2] != RD || + qr.stride[2] != 1 || qr.stride[1] < RD || qr.stride[0] < heads * qr.stride[1] || + kv.rank != 4 || kv.shape[0] < 1 || kv.shape[0] > INT_MAX || kv.shape[1] != 1 || + kv.shape[2] != bs || kv.shape[3] < D + RD || kv.stride[3] != 1 || kv.stride[2] < D + RD || + kv.stride[0] < bs * kv.stride[2] || bt.rank != 2 || bt.shape[1] < 1 || + bt.shape[1] > INT_MAX / bs || bt.stride[1] < 1 || bt.stride[0] < bt.shape[1] * bt.stride[1] || + su.rank != 1 || su.shape[0] < 1 || bt.shape[0] < su.shape[0] || !r4d_contig(&su) || + !r4d_contig(&cu) || r4d_numel(&cu) != su.shape[0] + 1 || o.rank != 3 || + o.shape[0] != q.shape[0] || o.shape[1] != heads || o.shape[2] != D || o.stride[2] != 1 || + o.stride[1] < D || o.stride[0] < heads * o.stride[1] || + (gate && (gate->rank != 2 || gate->shape[0] != q.shape[0] || gate->shape[1] < heads || + gate->stride[1] != 1))) + return RAD_E_SHAPE; + const long jobs = q.shape[0] * heads; + int splits = (int)std::min(16l, (256 + jobs - 1) / jobs); + splits = (int)std::max(1l, std::min((long)splits, (bt.shape[1] * bs + 63) / 64)); + if (!a->scratch || a->scratch_bytes < scratch_bytes) splits = 1; + const PagedMeta m{ q.stride[0], q.stride[1], qr.stride[0], qr.stride[1], + kv.stride[0], kv.stride[2], bt.stride[0], bt.stride[1], + o.stride[0], o.stride[1], gate ? (long)gate->stride[0] : 0L, + (int)q.shape[0], (int)heads, (int)su.shape[0], (int)bt.shape[1], + (int)bs, (int)kv.shape[0], splits, scale }; + const uint16_t* gp = gate ? (const uint16_t*)gate->data : nullptr; + int rc = R4D_EMIT(stream, attend_paged, dim3(m.rows, (m.heads + 3) / 4, m.splits), dim3(128), 0, + (const uint16_t*)q.data, (const uint16_t*)qr.data, (const uint16_t*)kv.data, + (const int*)bt.data, (const int*)su.data, (const int*)cu.data, gp, + (uint16_t*)o.data, (float*)a->scratch, m); + if (rc == RAD_OK && splits > 1) + rc = R4D_EMIT(stream, merge_paged, dim3(m.rows, (m.heads + 3) / 4), dim3(128), 0, + (const float*)a->scratch, gp, (uint16_t*)o.data, m); + return rc; +} /* Heads are the matrix rows, so all sixteen share each latent load even when * each query selected different pages. Splitting P into BF16 high/low parts * preserves FP32 softmax precision without a materialized per-head KV cache. @@ -896,6 +1067,9 @@ extern "C" int r4d_rad_mla_attn_rows(const RadArgs* a, RadStream stream) { extern "C" int r4d_rad_mla_project(const RadArgs* a, RadStream stream) { return project_body(a, stream); } +extern "C" int r4d_rad_mla_attn_paged(const RadArgs* a, RadStream stream) { + return paged_body(a, stream); +} extern "C" int64_t r4d_rad_mla_attn_scratch(const RadArgs*) { return scratch_bytes; } extern "C" int64_t r4d_rad_mla_attn_matrix_scratch(const RadArgs*) { return matrix_scratch_bytes; } extern "C" void r4d_mla_matrix_pin_form(int form) { g_mla_matrix_form = form; } diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index 615a4f48..d64a748a 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -812,6 +812,7 @@ int r4d_rad_logit_softcap (const RadArgs*, RadStream); int r4d_rad_scale (const RadArgs*, RadStream); int r4d_rad_silu_mul (const RadArgs*, RadStream); int r4d_rad_swiglu_clamped(const RadArgs*, RadStream); +int r4d_rad_swiglu_step(const RadArgs*, RadStream); int r4d_rad_swiglu_clamped_quant_fp8(const RadArgs*, RadStream); int r4d_rad_dsa_pool(const RadArgs*, RadStream); int r4d_shape_dsa_pool(const RadParam*, int, int, RadOpdDesc*); @@ -828,12 +829,16 @@ int r4d_shape_mla_project(const RadParam*, int, int, RadOpdDesc*); int r4d_rad_dsa_score(const RadArgs*, RadStream); int r4d_shape_dsa_score(const RadParam*, int, int, RadOpdDesc*); int r4d_rad_mla_attn(const RadArgs*, RadStream); +int r4d_rad_mla_attn_paged(const RadArgs*, RadStream); +int r4d_shape_mla_attn_paged(const RadParam*, int, int, RadOpdDesc*); int64_t r4d_rad_mla_attn_scratch(const RadArgs*); int r4d_rad_mla_attn_matrix(const RadArgs*, RadStream); int64_t r4d_rad_mla_attn_matrix_scratch(const RadArgs*); int r4d_rad_mla_attn_rows(const RadArgs*, RadStream); int r4d_shape_mla_attn(const RadParam*, int, int, RadOpdDesc*); int r4d_rad_router_sigmoid_topk(const RadArgs*, RadStream); +int r4d_rad_router_sigmoid_group_topk(const RadArgs*, RadStream); +int r4d_shape_router_sigmoid_group_topk(const RadParam*, int, int, RadOpdDesc*); int r4d_shape_router_sigmoid_topk(const RadParam*, int, int, RadOpdDesc*); int r4d_rad_router_sigmoid_topk_scatter(const RadArgs*, RadStream); int r4d_rad_moe_scatter_inv(const RadArgs*, RadStream); diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index b87c4bb8..7125a9c7 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -1875,6 +1875,17 @@ static const RadParamSpec pMlaAttn[] = { P_INT("M"), P_INT("latent_dim"), P P_STR("dtype") }; static const RadParamSpec pMlaProject[] = { P_INT("M"), P_INT("heads"), P_INT("head_dim"), P_INT("latent_dim"), P_STR("mode"), P_STR("dtype") }; +static const RadParamSpec pMlaAttnPaged[] = { P_INT("M"), P_INT("heads"), P_INT("latent_dim"), + P_INT("rope_dim"), P_INT("block_size"), P_F64("scale"), + P_STR("dtype") }; +static const RadOperandSpec oMlaAttnPaged[] = { { "q", RAD_OPD_IN, 0 }, + { "q_rope", RAD_OPD_IN, 1 }, + { "kv", RAD_OPD_IN, 0 }, + { "block_table", RAD_OPD_IN, 0 }, + { "seqused", RAD_OPD_IN, 0 }, + { "cu_seqlens", RAD_OPD_IN, 0 }, + { "gate", RAD_OPD_IN, 1 }, + { "out", RAD_OPD_OUT, 0 } }; static const RadOperandSpec oMlaAttn[] = { { "q", RAD_OPD_IN, 0 }, { "kv", RAD_OPD_IN, 0 }, { "bt", RAD_OPD_IN, 0 }, @@ -1895,6 +1906,8 @@ static const RadOperandSpec oDsaPool[] = { }; static const RadParamSpec pRouterSigmoid[] = { P_INT("M"), P_INT("n_expert"), P_INT("top_k"), P_INT("norm"), P_F64("route_scale"), P_STR("dtype") }; +static const RadParamSpec pRouterSigmoidGroup[] = { P_INT("M"), P_INT("n_expert"), P_INT("top_k"), + P_INT("n_group"), P_INT("topk_group"), P_INT("norm"), P_F64("route_scale"), P_STR("dtype") }; static const RadOperandSpec oRouterSigmoid[] = { { "logits", RAD_OPD_IN, 0 }, { "bias", RAD_OPD_WEIGHT, 0 }, { "ids", RAD_OPD_OUT, 0 }, { "weights", RAD_OPD_OUT, 0 } @@ -3003,6 +3016,10 @@ static const RadOpSchema kSchemas[] = { "(broadcast down the rows): a learned gain on an activation. f32 product, rounded once."), SCHEMA("mla_attn", pMlaAttn, oMlaAttn, "Softmax over selected latent vectors used as both key and value; per-query page tables and visible lengths."), + SCHEMA("mla_attn_paged", pMlaAttnPaged, oMlaAttnPaged, + "Dense causal latent attention over a paged cache whose token row is the latent then the " + "rotated key part: score = scale * (q . latent + q_rope . rope), value = the latent; " + "sequences as in attn_paged. With `gate`, out = bf16(bf16(out) * bf16(sigmoid(gate[head])))."), SCHEMA("mla_project", pMlaProject, oGemmNt, "Per-head query absorption or value expansion through the shared [head,(K|V),latent] BF16 matrix."), SCHEMA("dsa_score", pDsaScore, oDsaScore, @@ -3013,6 +3030,8 @@ static const RadOpSchema kSchemas[] = { "Normalized Hadamard, BF16 boundary and power-of-two E4M3 quantization per query head."), SCHEMA("gemm_nt_f32", pGemmNt, oGemmNt, "BF16 activations times F32 weights, F32 accumulation and output; preserves routing and index gate precision."), + SCHEMA("swiglu_step", pSwigluClamped, oGateUp, + "min(silu(gate),limit)*clamp(up,-limit,limit); gate is the first half."), SCHEMA("swiglu_clamped", pSwigluClamped, oGateUp, "silu(min(gate,limit))*clamp(up,-limit,limit); gate is the first half."), SCHEMA("swiglu_clamped_quant_fp8", pSwigluClampedQuant, oGatedQuantFp8, @@ -3399,6 +3418,10 @@ static const RadOpSchema kSchemas[] = { "With `add` present the form is y = bf16(x * act(s)) + add: the product is NARROWED " "before the sum, which is what makes the fused form bit-identical to the two ops it " "stands in for rather than merely close to them."), + SCHEMA("router_sigmoid_group_topk", pRouterSigmoidGroup, oRouterSigmoid, + "Group-limited sigmoid routing: groups rank by the sum of their two best p + bias, " + "selection runs over the topk_group best groups; correction bias selects, original " + "scores weight."), SCHEMA("router_sigmoid_topk", pRouterSigmoid, oRouterSigmoid, "Single-group sigmoid routing; correction bias selects experts, original scores weight them."), SCHEMA("router_sigmoid_topk_scatter", pRouterSigmoidScatter, oRouterSigmoidScatter, @@ -4719,11 +4742,16 @@ static const RadConstraint cMlaAttn[] = { C_GE("M", 1), C_LE("M", 65535), C_EQ("latent_dim", 512), C_GE("heads", 1), C_LE("heads", 64), C_GE("blocks", 1), C_EQ("block_size", 4), C_IN("dtype", "bf16") }; +static const RadConstraint cMlaAttnPaged[] = { + C_GE("M", 1), C_LE("M", 65535), C_EQ("latent_dim", 512), C_EQ("rope_dim", 64), + C_GE("heads", 1), C_LE("heads", 64), C_GE("block_size", 1), C_LE("block_size", 256), + C_IN("dtype", "bf16") +}; static const RadConstraint cMlaProject[] = { C_GE("M", 1), C_LE("M", 65535), C_GE("heads", 1), C_LE("heads", 64), - C_EQ("head_dim", 256), + C_IN("head_dim", "128 256"), C_EQ("latent_dim", 512), C_IN("mode", "absorb expand"), C_IN("dtype", "bf16") }; @@ -4773,6 +4801,11 @@ static const RadConstraint cRouterSigmoid[] = { C_GE("M", 1), C_LE("M", 6 C_GE("n_expert", 1), C_LE("n_expert", 512), C_GE("top_k", 1), C_LE("top_k", 32), C_IN("dtype", "f32") }; +static const RadConstraint cRouterSigmoidGroup[] = { C_GE("M", 1), C_LE("M", 65535), + C_GE("n_expert", 1), C_LE("n_expert", 512), + C_GE("top_k", 1), C_LE("top_k", 32), + C_GE("n_group", 1), C_LE("n_group", 32), + C_IN("dtype", "f32") }; /* The sort's single-workgroup form bounds M * top_k at 1024, which the shim checks. */ static const RadConstraint cRouterSigmoidScatter[] = { C_GE("M", 1), C_LE("M", 1024), C_GE("n_expert", 1), C_LE("n_expert", 512), @@ -6276,8 +6309,15 @@ static const RadKernelInfo kKernels[] = { RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cDsaScore), NOTUNE, nullptr, nullptr, r4d_rad_dsa_score, nullptr, nullptr, nullptr, r4d_shape_dsa_score }, +{ "mla_attn_paged_bf16", "mla_attn_paged", "attn", + "dense causal latent attention with a rotary part, a wave a (row, head), split history", + "latent_dim=512, rope_dim=64, heads<=64, block_size<=256; one page table a sequence", + "bf16 Q/rotary/cache/gate/output, f32 softmax and partials", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cMlaAttnPaged), NOTUNE, + nullptr, nullptr, r4d_rad_mla_attn_paged, r4d_rad_mla_attn_scratch, nullptr, nullptr, + r4d_shape_mla_attn_paged }, { "mla_project_bf16", "mla_project", "attn", "per-head absorbed MLA projections", - "head_dim=256, latent_dim=512; pitched tensors", "bf16 input, weights and output; fp32 arithmetic", + "head_dim 128 or 256, latent_dim=512; pitched tensors", "bf16 input, weights and output; fp32 arithmetic", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cMlaProject), NOTUNE, nullptr, nullptr, r4d_rad_mla_project, nullptr, nullptr, nullptr, r4d_shape_mla_project }, @@ -6296,6 +6336,12 @@ static const RadKernelInfo kKernels[] = { RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cDsaPool), NOTUNE, nullptr, nullptr, r4d_rad_dsa_pool, nullptr, nullptr, nullptr, r4d_shape_dsa_pool }, +{ "swiglu_step_bf16", "swiglu_step", "elem", + "SwiGLU clipped after the SiLU", "positive finite limit; pitched rows", + "bf16 in and out, fp32 arithmetic", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cBf16Row), NOTUNE, + nullptr, nullptr, r4d_rad_swiglu_step, nullptr, nullptr, nullptr, + r4d_shape_silu_mul }, { "swiglu_clamped_bf16", "swiglu_clamped", "elem", "asymmetrically clipped SwiGLU", "positive finite limit; pitched rows", "bf16 in and out, fp32 arithmetic", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, @@ -8512,6 +8558,12 @@ R4D_WIN_TREE_PAIR(512, 4) R4D_WIN_TREE_PAIR(512, 8) nullptr, nullptr, r4d_rad_scale_rows, nullptr, nullptr, nullptr, r4d_shape_scale_rows }, +{ "router_sigmoid_group_topk_f32", "router_sigmoid_group_topk", "moe", + "group-limited sigmoid correction-bias routing, one wave a row", "experts <=512, groups <=32, top_k<=32", + "f32 logits, bias and weights; i32 ids", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cRouterSigmoidGroup), NOTUNE, + nullptr, nullptr, r4d_rad_router_sigmoid_group_topk, nullptr, nullptr, nullptr, + r4d_shape_router_sigmoid_group_topk }, { "router_sigmoid_topk_f32", "router_sigmoid_topk", "moe", "sigmoid correction-bias routing", "single group, experts <=512, top_k<=32", "f32 logits, bias and weights; i32 ids", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 38b862a2..0c97253f 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -16828,8 +16828,10 @@ static void mhc_check(const Plugin& pl, const char* name, int64_t rows, int64_t dlclose(ref); return; } - const bool clipped = !std::strcmp(row->op, "swiglu_clamped"); - const bool routed = !std::strcmp(row->op, "router_sigmoid_topk"); + const bool clipped = + !std::strcmp(row->op, "swiglu_clamped") || !std::strcmp(row->op, "swiglu_step"); + const bool grouped = !std::strcmp(row->op, "router_sigmoid_group_topk"); + const bool routed = grouped || !std::strcmp(row->op, "router_sigmoid_topk"); const bool pooled = !std::strcmp(row->op, "dsa_pool"); const bool query = !std::strcmp(row->op, "dsa_query"); const bool projection = !std::strcmp(row->op, "gemm_nt_f32"); @@ -16839,6 +16841,10 @@ static void mhc_check(const Plugin& pl, const char* name, int64_t rows, int64_t ps.push_back(PI("top_k", 8)); ps.push_back(PI("norm", hc)); ps.push_back(PF("route_scale", 2.5)); + if (grouped) { /* Ling's grouping: 8 groups, the best 4 by their top-2 sums */ + ps.push_back(PI("n_group", 8)); + ps.push_back(PI("topk_group", 4)); + } } else if (projection) { ps.push_back(PI("N", n)); ps.push_back(PI("K", hc)); @@ -17428,7 +17434,7 @@ static void dsa_score_check(const Plugin& pl, int64_t rows, int64_t blocks, bool } static void mla_project_check(const Plugin& pl, int64_t rows, int64_t heads, const char* mode, - bool flat = false) { + bool flat = false, int64_t head_dim = 256) { const auto* row = find(pl, "mla_project_bf16"); if (!row || !g_plugin) { ok("MLA projection", false, "kernel missing"); @@ -17452,7 +17458,7 @@ static void mla_project_check(const Plugin& pl, int64_t rows, int64_t heads, con dlclose(ref); return; } - std::vector ps = { PI("M", rows + 7), PI("heads", heads), PI("head_dim", 256), + std::vector ps = { PI("M", rows + 7), PI("heads", heads), PI("head_dim", head_dim), PI("latent_dim", 512), PS("mode", mode), PS("dtype", "bf16") }; std::vector host, device; std::vector> bytes(3); @@ -17536,8 +17542,8 @@ static void mla_project_check(const Plugin& pl, int64_t rows, int64_t heads, con } for (size_t j = 0; j < got.size(); ++j) if (!written[j]) guards = guards && got[j] == 0xa5; - ok(fmt("MLA %s M=%lld H=%lld max error %.8g", mode, (long long)rows, (long long)heads, - max_error) + ok(fmt("MLA %s M=%lld H=%lld D=%lld max error %.8g", mode, (long long)rows, + (long long)heads, (long long)head_dim, max_error) .c_str(), matches); ok("MLA projection pitched tensors and guards", guards); @@ -17547,6 +17553,158 @@ static void mla_project_check(const Plugin& pl, int64_t rows, int64_t heads, con dlclose(ref); } +/* mla_attn_paged against libref: several sequences with deeper contexts than their queries, an + * unmapped page, the rotary query as a column view of a wider projection, an optional head gate, + * pitched rows and poisoned margins. */ +static void mla_paged_check(const Plugin& pl, std::vector qlen, std::vector ctx, + int64_t heads, bool gated) { + const char* what = "mla_attn_paged_bf16"; + const auto* row = find(pl, what); + if (!row || !g_plugin) { + ok(what, false, "kernel missing"); + return; + } + std::string path(g_plugin); + path = path.substr(0, path.find_last_of('/') + 1) + "libref.so"; + void* ref = dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL); + if (!ref) { + ok(what, false, "oracle missing"); + return; + } + auto count = (int (*)())dlsym(ref, "rad_kernel_count"); + auto at = (const RadKernelInfo* (*)(int))dlsym(ref, "rad_kernel_at"); + const RadKernelInfo* oracle = nullptr; + if (count && at) + for (int i = 0; i < count(); ++i) + if (!std::strcmp(at(i)->op, "mla_attn_paged")) oracle = at(i); + if (!oracle) { + ok(what, false, "oracle row missing"); + dlclose(ref); + return; + } + const int64_t L = 512, R = 64, bs = 16, S = (int64_t)qlen.size(); + int64_t M = 0, bmax = 0, pages = 0; + for (int64_t s = 0; s < S; ++s) { + M += qlen[(size_t)s]; + bmax = std::max(bmax, (ctx[(size_t)s] + bs - 1) / bs); + pages += (ctx[(size_t)s] + bs - 1) / bs; + } + std::vector ps = { PI("M", M + 5), PI("heads", heads), + PI("latent_dim", L), PI("rope_dim", R), + PI("block_size", bs), PF("scale", 1 / std::sqrt(192.0)), + PS("dtype", "bf16") }; + /* Operands: q, q_rope (a column view at 192 a head), kv, block_table, seqused, cu_seqlens, + * gate, out. */ + std::vector host(8); + host[0] = T(nullptr, RAD_BF16, { M, heads, L }); + host[0].stride[1] = L + 3; + host[0].stride[0] = heads * (L + 3) + 11; + host[1] = T(nullptr, RAD_BF16, { M, heads, R }); + host[1].stride[1] = 192; + host[1].stride[0] = heads * 192 + 4; + host[2] = T(nullptr, RAD_BF16, { pages, 1, bs, L + R }); + host[3] = T(nullptr, RAD_I32, { S, bmax }); + host[3].stride[0] = bmax + 2; + host[4] = T(nullptr, RAD_I32, { S }); + host[5] = T(nullptr, RAD_I32, { S + 1 }); + if (gated) { + host[6] = T(nullptr, RAD_BF16, { M, heads + 3 }); + host[6].stride[0] = heads + 9; + } + host[7] = T(nullptr, RAD_BF16, { M, heads, L }); + host[7].stride[1] = L + 5; + host[7].stride[0] = heads * (L + 5) + 7; + std::vector> bytes(8); + std::vector allocations(8, nullptr); + std::vector device(8); + bool allocated = true; + for (int i = 0; i < 8 && allocated; ++i) { + RadTensor& t = host[(size_t)i]; + if (!t.rank) continue; + int64_t elements = t.shape[0] * t.stride[0]; + bytes[(size_t)i].assign((size_t)elements * esz(t.dtype) + 256, 0xa5); + t.data = bytes[(size_t)i].data() + 128; + const bool bf = t.dtype == RAD_BF16 && i != 7; + if (bf) + for (int64_t e = 0; e < elements; ++e) { + const float v = + (float)((int)(st_mix32((uint32_t)(e * 7 + i * 7919)) % 2001) - 1000) / + (i == 2 ? 1000.0f : i == 6 ? 300.0f : 250.0f); + ((uint16_t*)t.data)[e] = h_to_bf16(v); + } + if (i == 3) { + /* Pages in a scrambled order; the second page of the deepest sequence unmapped. */ + int next = 0; + for (int64_t s = 0; s < S; ++s) + for (int64_t b = 0; b < bmax; ++b) { + int v = -1; + if (b < (ctx[(size_t)s] + bs - 1) / bs) v = (int)((next++ * 5 + 3) % pages); + if (s == S - 1 && b == 1 && ctx[(size_t)s] > 2 * bs) v = -1; + ((int*)t.data)[s * t.stride[0] + b] = v; + } + } + if (i == 4) + for (int64_t s = 0; s < S; ++s) ((int*)t.data)[s] = (int)ctx[(size_t)s]; + if (i == 5) { + int c = 0; + for (int64_t s = 0; s <= S; ++s) { + ((int*)t.data)[s] = c; + if (s < S) c += (int)qlen[(size_t)s]; + } + } + allocations[(size_t)i] = dalloc(bytes[(size_t)i].size()); + if (!allocations[(size_t)i]) { + allocated = false; + break; + } + st_memcpy(allocations[(size_t)i], bytes[(size_t)i].data(), bytes[(size_t)i].size(), + hipMemcpyHostToDevice); + device[(size_t)i] = t; + device[(size_t)i].data = (char*)allocations[(size_t)i] + 128; + } + std::string label = fmt("mla_attn_paged S=%lld M=%lld H=%lld%s", (long long)S, (long long)M, + (long long)heads, gated ? " gated" : ""); + if (!allocated) { + ok(label.c_str(), false, "allocation failed"); + dlclose(ref); + return; + } + RadArgs args{}; + args.t = host.data(); + args.n_t = 8; + args.p = ps.data(); + args.n_p = (int)ps.size(); + args.world_size = 1; + const int rc = oracle->launch(&args, nullptr); + ok(fmt("%s host oracle", label.c_str()).c_str(), rc == RAD_OK); + if (rc == RAD_OK) { + run_case(row, device, ps); + std::vector got(bytes[7].size()); + st_memcpy(got.data(), allocations[7], got.size(), hipMemcpyDeviceToHost); + std::vector written(got.size(), false); + bool matches = true, guards = true; + float max_error = 0; + const auto& t = host[7]; + for (int64_t r = 0; r < M; ++r) + for (int64_t h = 0; h < heads; ++h) + for (int64_t d = 0; d < L; ++d) { + const long off = r * t.stride[0] + h * t.stride[1] + d; + const float want = h_bf16(((uint16_t*)t.data)[off]), + actual = h_bf16(((uint16_t*)(got.data() + 128))[off]); + const float error = std::fabs(actual - want); + max_error = std::max(max_error, error); + matches = matches && std::isfinite(actual) && + error <= 0.002f + 0.008f * std::fabs(want); + written[128 + off * 2] = written[129 + off * 2] = true; + } + for (size_t j = 0; j < got.size(); ++j) + if (!written[j]) guards = guards && got[j] == 0xa5; + ok(fmt("%s max error %.6g", label.c_str(), max_error).c_str(), matches); + ok(fmt("%s pitched rows and guards", label.c_str()).c_str(), guards); + } + dlclose(ref); +} + /* An environment variable set (or, with a null value, cleared) for one scope and restored after * it: the MLA launcher reads its counting switch at every call. */ struct ScopedEnv { @@ -32173,6 +32331,16 @@ static void device_phase(const Plugin& pl) { for (int64_t rows : { 1, 7, 33 }) for (int64_t n : { 31, 259, 4096 }) mhc_check(pl, "swiglu_clamped_bf16", rows, n, 0); } + if (sel("swiglu_step_bf16")) { + for (int64_t rows : { 1, 7, 33 }) + for (int64_t n : { 31, 259, 768 }) mhc_check(pl, "swiglu_step_bf16", rows, n, 0); + } + if (sel("router_sigmoid_group_topk_f32")) { + for (int64_t rows : { 1, 7, 33, 300 }) + for (int64_t ne : { 64, 512 }) + for (int norm : { 0, 1 }) + mhc_check(pl, "router_sigmoid_group_topk_f32", rows, ne, norm); + } if (sel("router_sigmoid_topk_f32")) { for (int64_t rows : { 1, 7, 33 }) for (int64_t ne : { 32, 288, 512 }) @@ -32255,8 +32423,22 @@ static void device_phase(const Plugin& pl) { mla_project_check(pl, 1, 64, mode); for (int64_t rows : { 1, 4, 33 }) for (int64_t heads : { 8, 16 }) mla_project_check(pl, rows, heads, mode, true); + /* Ling-3.0's 128-wide heads, 8 a rank under TP4 and 32 unsplit. */ + for (int64_t rows : { 1, 3, 33, 130 }) + for (int64_t heads : { 8, 32 }) + mla_project_check(pl, rows, heads, mode, false, 128); } } + if (sel("mla_attn_paged_bf16")) { + for (int64_t heads : { 8, 32 }) + for (bool gated : { false, true }) { + mla_paged_check(pl, { 1 }, { 1 }, heads, gated); + mla_paged_check(pl, { 7 }, { 7 }, heads, gated); + mla_paged_check(pl, { 1, 1, 1 }, { 40, 300, 1025 }, heads, gated); + mla_paged_check(pl, { 33, 5 }, { 33, 900 }, heads, gated); + mla_paged_check(pl, { 130 }, { 130 }, heads, gated); + } + } if (sel("mla_attn_rows_bf16")) { /* A rank's run of rows with all 64 heads (GLM's prefill split by rows), against the matrix * row on the same operands. Under 32 rows the rule runs the matrix kernel, so the rows diff --git a/libr4d/r4d_shapes.cpp b/libr4d/r4d_shapes.cpp index a66a28fb..2567e7a2 100644 --- a/libr4d/r4d_shapes.cpp +++ b/libr4d/r4d_shapes.cpp @@ -617,6 +617,18 @@ extern "C" int r4d_shape_router_sigmoid_topk(const RadParam* p, int n_p, int ope opd(D, M, k) }; R4D_PICK(l); } +extern "C" int r4d_shape_router_sigmoid_group_topk(const RadParam* p, int n_p, int operand, + RadOpdDesc* out) { + const int64_t M = pi(p, n_p, "M"), ne = pi(p, n_p, "n_expert"), k = pi(p, n_p, "top_k"); + const int64_t ng = pi(p, n_p, "n_group"), kg = pi(p, n_p, "topk_group"); + if (ne <= 0 || ne > 512 || k <= 0 || ng <= 0 || ng > 32 || ne % ng || ne / ng < 2 || kg <= 0 || + kg > ng || k > kg * (ne / ng)) + return RAD_E_UNSUPPORTED; + const uint32_t D = dt_act(p, n_p, "dtype"); + const RadOpdDesc l[] = { opd(D, M, ne), opd((uint32_t)RAD_F32, ne), opd_idx(M, k, ne), + opd(D, M, k) }; + R4D_PICK(l); +} extern "C" int r4d_shape_router_sigmoid_topk_scatter(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = pi(p, n_p, "M"), ne = pi(p, n_p, "n_expert"), k = pi(p, n_p, "top_k"); @@ -663,6 +675,24 @@ extern "C" int r4d_shape_mla_project(const RadParam* p, int n_p, int operand, Ra opd((uint32_t)RAD_BF16, M, h, absorb ? l : d) }; R4D_PICK(list); } +/* One sequence whose context is its query, as libref describes the op; a harness passes `ctx`. */ +extern "C" int r4d_shape_mla_attn_paged(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = pi(p, n_p, "M"), h = pi(p, n_p, "heads"), L = pi(p, n_p, "latent_dim"), + R = pi(p, n_p, "rope_dim"), bs = pi(p, n_p, "block_size"); + if (M <= 0 || h <= 0 || L <= 0 || R <= 0 || bs <= 0) return RAD_E_UNSUPPORTED; + int64_t ctx = pi(p, n_p, "ctx", 0); + if (ctx < M) ctx = M; + const int64_t blocks = (ctx + bs - 1) / bs; + const RadOpdDesc list[] = { opd((uint32_t)RAD_BF16, M, h, L), + opd((uint32_t)RAD_BF16, M, h, R), + opd((uint32_t)RAD_BF16, blocks, 1, bs, L + R), + opd_idx(1, blocks, blocks), + opd_idx(1, 0, 0, ctx), + opd_idx(2, 0, M + 1, -1, (uint32_t)RAD_OPD_F_IDX_CU), + opd_none(), + opd((uint32_t)RAD_BF16, M, h, L) }; + R4D_PICK(list); +} extern "C" int r4d_shape_dsa_score(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"), H = pi(p, n_p, "heads"); const int64_t B = pi(p, n_p, "blocks"), S = pi(p, n_p, "seqs"), pages = S * B;