diff --git a/libavx/avx_cases.cpp b/libavx/avx_cases.cpp index 50d5777c..d543323b 100644 --- a/libavx/avx_cases.cpp +++ b/libavx/avx_cases.cpp @@ -139,6 +139,7 @@ std::vector build_cases() { for (const char* dt : { "f32", "bf16" }) { add("hc_enter", { HI("M", 5), HI("n", 128), HI("hc", 4), HS("dtype", dt) }); add("swiglu_clamped", { HI("M", 5), HI("n", 259), HF("limit", 0.5), HS("dtype", dt) }); + add("swiglu_step", { HI("M", 5), HI("n", 259), HF("limit", 0.5), HS("dtype", dt) }); if (!std::strcmp(dt, "bf16")) add("dsa_pool", { HI("M", 7), HI("n", 128), HI("ratio", 4), HS("dtype", "bf16") }); if (!std::strcmp(dt, "bf16")) @@ -165,6 +166,13 @@ std::vector build_cases() { HF("hc_eps", 1e-6), HI("chunk", 129), HS("dtype", dt) }); add("mhc_post", { HI("M", 3), HI("n", 129), HI("hc", 4), HS("dtype", dt) }); add("mhc_contract", { HI("M", 3), HI("n", 129), HI("hc", 4), HS("dtype", dt) }); + for (int norm : { 0, 1 }) + add("router_sigmoid_group_topk", + { HI("M", 5), HI("n_expert", 512), HI("top_k", 8), HI("n_group", 8), + HI("topk_group", 4), HI("norm", norm), HF("route_scale", 2.5), HS("dtype", dt) }); + add("mla_attn_paged", { HI("M", 5), HI("heads", 3), HI("latent_dim", 64), HI("rope_dim", 16), + HI("block_size", 4), HF("scale", 0.0721687836), HI("ctx", 23), + HS("dtype", dt) }); add("mla_attn", { HI("M", 3), HI("latent_dim", 32), HI("heads", 2), HI("blocks", 7), HI("block_size", 4), HF("scale", 0.125), HS("dtype", dt) }); for (const char* mode : { "prefill", "verify" }) diff --git a/libavx/avx_glm.cpp b/libavx/avx_glm.cpp index 5c7d9b5f..783fd8c9 100644 --- a/libavx/avx_glm.cpp +++ b/libavx/avx_glm.cpp @@ -140,6 +140,87 @@ AVX_KERNEL(swiglu_clamped) { return RAD_OK; } +AVX_KERNEL(swiglu_step) { + if (!rad_args_have(a, 2)) return RAD_E_INVAL; + const auto &gu = a->t[0], &y = a->t[1]; + const int64_t n = p_int(a, "n", 0); + const float limit = p_f32(a, "limit", 0); + if (n < 1 || !std::isfinite(limit) || limit <= 0 || gu.rank != 2 || y.rank != 2 || !gu.data || + !y.data || y.shape[0] < 1 || gu.shape[0] != y.shape[0] || gu.shape[1] != 2 * n || + y.shape[1] != n) + return RAD_E_SHAPE; + AVX_PARALLEL_FOR_IF(y.shape[0] * n >= AVX_PAR_MIN) + for (int64_t r = 0; r < y.shape[0]; ++r) { + for (int64_t i = 0; i < n; ++i) { + const int64_t b = rowoff(&gu, r, 2 * n), s = laststride(&gu); + const float x = ldt(&gu, b + i * s); + const float g = std::min(x / (1.0f + std::exp(-x)), limit); + const float u = std::clamp(ldt(&gu, b + (n + i) * s), -limit, limit); + stt(&y, rowoff(&y, r, n) + i * laststride(&y), g * u); + } + } + return RAD_OK; +} + +AVX_KERNEL(router_sigmoid_group_topk) { + if (!rad_args_have(a, 4)) return RAD_E_INVAL; + const auto &lg = a->t[0], &bias = a->t[1], &ids = a->t[2], &w = a->t[3]; + const int64_t ne = p_int(a, "n_expert", 0), k = p_int(a, "top_k", 0), + ng = p_int(a, "n_group", 0), kg = p_int(a, "topk_group", 0); + const float factor = p_f32(a, "route_scale", 0); + if (ne < 1 || ne > 512 || k < 1 || ng < 1 || ne % ng || ne / ng < 2 || kg < 1 || kg > ng || + k > kg * (ne / ng) || !std::isfinite(factor) || factor <= 0 || lg.rank != 2 || + lg.shape[0] < 1 || lg.shape[1] != ne || bias.rank != 1 || bias.shape[0] != ne || + bias.dtype != RAD_F32 || ids.dtype != RAD_I32 || !matrix(ids, lg.shape[0], k) || + !matrix(w, lg.shape[0], k) || !lg.data || !bias.data) + return RAD_E_SHAPE; + const int64_t gs = ne / ng; + for (int64_t r = 0; r < lg.shape[0]; ++r) { + float prob[512], ranked[512], chosen[512], group[512]; + int index[512]; + bool kept[512] = {}; + for (int64_t e = 0; e < ne; ++e) { + prob[e] = 1.0f / (1.0f + std::exp(-ldt(&lg, rowoff(&lg, r, ne) + e * laststride(&lg)))); + ranked[e] = prob[e] + ldt(&bias, e * laststride(&bias)); + } + for (int64_t gi = 0; gi < ng; ++gi) { + float t0 = -INFINITY, t1 = -INFINITY; + for (int64_t e = gi * gs; e < (gi + 1) * gs; ++e) { + if (ranked[e] > t0) { t1 = t0; t0 = ranked[e]; } + else if (ranked[e] > t1) t1 = ranked[e]; + } + group[gi] = t0 + t1; + } + for (int64_t j = 0; j < kg; ++j) { + int winner = -1; + for (int64_t gi = 0; gi < ng; ++gi) + if (group[gi] > -INFINITY && (winner < 0 || group[gi] > group[winner])) + winner = (int)gi; + if (winner < 0) return RAD_E_SHAPE; + for (int64_t e = winner * gs; e < (winner + 1) * gs; ++e) kept[e] = true; + group[winner] = -INFINITY; + } + float total = 0; + for (int64_t j = 0; j < k; ++j) { + int winner = -1; + for (int64_t e = 0; e < ne; ++e) + if (kept[e] && ranked[e] > -INFINITY && (winner < 0 || ranked[e] > ranked[winner])) + winner = (int)e; + if (winner < 0) return RAD_E_SHAPE; + index[j] = winner; + chosen[j] = prob[winner]; + total += chosen[j]; + ranked[winner] = -INFINITY; + } + const float mult = p_int(a, "norm", 0) ? factor / (total + 1e-20f) : factor; + for (int64_t j = 0; j < k; ++j) { + st_int_dt(ids.dtype, ids.data, rowoff(&ids, r, k) + j * laststride(&ids), index[j]); + stt(&w, rowoff(&w, r, k) + j * laststride(&w), chosen[j] * mult); + } + } + return RAD_OK; +} + namespace { int64_t part_stride(int64_t hc) { return (hc * (hc + 2) + 1 + 3) / 4 * 4; } bool pre_params(const RadArgs* a, int64_t* n, int64_t* hc, int64_t* iters, float* eps, diff --git a/libavx/avx_isa.h b/libavx/avx_isa.h index a6eb6c6e..877f61fd 100644 --- a/libavx/avx_isa.h +++ b/libavx/avx_isa.h @@ -74,13 +74,16 @@ int avx_par_force(int threads); X(layernorm) X(mhc_pre) X(mhc_post) X(mhc_contract) \ X(kda_update) X(mhc_pre_partial) X(mhc_pre_finish) \ X(swiglu_clamped) \ + X(swiglu_step) \ X(router_sigmoid_topk) \ + X(router_sigmoid_group_topk) \ X(dsa_pool) \ X(dsa_query) \ X(gemm_nt_f32) \ X(mla_project) \ X(dsa_score) \ X(mla_attn) \ + X(mla_attn_paged) \ X(add) X(grid_embed) X(grid_embed_aa) X(causal_conv1d) \ X(mul) X(silu_mul) X(gelu_mul) X(gelu) \ X(silu) X(sigmoid) X(logit_softcap) X(gather_rows) \ diff --git a/libavx/avx_mla.cpp b/libavx/avx_mla.cpp index 94c82558..0bade3b5 100644 --- a/libavx/avx_mla.cpp +++ b/libavx/avx_mla.cpp @@ -55,6 +55,98 @@ AVX_KERNEL(mla_project) { return RAD_OK; } +/* libref's mla_attn_paged (libref/ref_mla.cpp): dense causal latent attention over a cache row of + * the latent then the rotated key part, one sequence's page table, an optional head gate. */ +AVX_KERNEL(mla_attn_paged) { + if (a->n_t < 8 || !rad_arg_in(a, 0) || !rad_arg_in(a, 2) || !rad_arg_in(a, 3) || + !rad_arg_in(a, 4) || !rad_arg_in(a, 5) || !rad_arg_in(a, 7)) + 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 = rad_arg_in(a, 6); + const int64_t h = p_int(a, "heads", 0), L = p_int(a, "latent_dim", 0), + R = p_int(a, "rope_dim", 0), bs = p_int(a, "block_size", 0); + const float scale = p_f32(a, "scale", 0); + auto heads_view = [&](RadTensor& t, int64_t width) { + if (h > 0 && width > 0 && t.rank == 2 && t.shape[1] == h * width) { + t.rank = 3; + t.shape[1] = h; + t.shape[2] = width; + t.stride[2] = t.stride[1]; + t.stride[1] *= width; + } + }; + heads_view(q, L); + heads_view(qr, R); + heads_view(o, L); + if (h < 1 || L < 1 || L > 2048 || R < 0 || R > 2048 || bs < 1 || !std::isfinite(scale) || + scale <= 0 || q.rank != 3 || q.shape[0] < 1 || q.shape[1] != h || q.shape[2] != L || + (R && (!qr.data || qr.rank != 3 || qr.shape[0] != q.shape[0] || qr.shape[1] != h || + qr.shape[2] != R)) || + kv.rank != 4 || kv.shape[1] != 1 || kv.shape[2] != bs || kv.shape[3] < L + R || + bt.rank != 2 || su.rank != 1 || cu.rank != 1 || numel(&cu) != numel(&su) + 1 || + o.rank != 3 || o.shape[0] != q.shape[0] || o.shape[1] != h || o.shape[2] != L || + (gate && (gate->rank != 2 || gate->shape[0] != q.shape[0] || gate->shape[1] < h))) + return RAD_E_SHAPE; + const int64_t n_seq = numel(&su), rows = q.shape[0]; + auto cu_at = [&](int64_t i) { return ld_int_dt(cu.dtype, cu.data, i * laststride(&cu)); }; + if (cu_at(0) != 0 || cu_at(n_seq) != rows) return RAD_E_SHAPE; + AVX_PARALLEL_FOR_IF(rows * h * (L + R) * bt.shape[1] * bs >= AVX_PAR_MIN) + for (int64_t job = 0; job < rows * h; ++job) { + const int64_t r = job / h, head = job % h; + int64_t s = 0; + while (s + 1 < n_seq && cu_at(s + 1) <= r) ++s; + const int64_t qlen = cu_at(s + 1) - cu_at(s), i = r - cu_at(s); + const int64_t ctx = ld_int_dt(su.dtype, su.data, s * su.stride[0]); + const int64_t live = std::min(ctx - qlen + i + 1, bt.shape[1] * bs); + float *tmp = scratch_f32((size_t)(3 * L + 2 * R)), *query = tmp, *key = tmp + L, + *value = tmp + 2 * L, *qrot = tmp + 3 * L, *krot = qrot + R; + for (int64_t c = 0; c < L; ++c) { + query[c] = ldt(&q, r * q.stride[0] + head * q.stride[1] + c * q.stride[2]); + value[c] = 0; + } + for (int64_t c = 0; c < R; ++c) + qrot[c] = ldt(&qr, r * qr.stride[0] + head * qr.stride[1] + c * qr.stride[2]); + float max = -INFINITY, den = 0; + for (int64_t j = 0; j < live; ++j) { + const int64_t page = + ld_int_dt(bt.dtype, bt.data, s * bt.stride[0] + (j / bs) * bt.stride[1]); + if (page < 0 || page >= kv.shape[0]) continue; + const int64_t base = page * kv.stride[0] + (j % bs) * kv.stride[2]; + for (int64_t c = 0; c < L; ++c) key[c] = ldt(&kv, base + c * kv.stride[3]); + for (int64_t c = 0; c < R; ++c) krot[c] = ldt(&kv, base + (L + c) * kv.stride[3]); + vf acc = vf_zero(); + int64_t c = 0; + for (; c + VF_N <= L; c += VF_N) + acc = vf_fma(vf_loadu(query + c), vf_loadu(key + c), acc); + float score = vf_hsum(acc); + for (; c < L; ++c) score += query[c] * key[c]; + for (c = 0; c < R; ++c) score += qrot[c] * krot[c]; + score *= scale; + const float next = std::max(max, score), old = std::exp(max - next), + w = std::exp(score - next); + den = den * old + w; + max = next; + const vf a = vf_set1(old), b = vf_set1(w); + c = 0; + for (; c + VF_N <= L; c += VF_N) + vf_storeu(value + c, vf_fma(vf_loadu(key + c), b, vf_mul(vf_loadu(value + c), a))); + for (; c < L; ++c) value[c] = value[c] * old + key[c] * w; + } + float g = 1.0f; + if (gate) { + const float x = ldt(gate, r * gate->stride[0] + head * gate->stride[1]); + g = narrow1(RAD_BF16, 1.0f / (1.0f + std::exp(-x))); + } + for (int64_t c = 0; c < L; ++c) { + float v = den > 0 ? value[c] / den : 0; + if (gate) v = narrow1(RAD_BF16, v) * g; + stt(&o, r * o.stride[0] + head * o.stride[1] + c * o.stride[2], v); + } + } + return RAD_OK; +} + AVX_KERNEL(mla_attn) { if (!rad_args_have(a, 5)) return RAD_E_INVAL; const auto &q = a->t[0], &kv = a->t[1], &bt = a->t[2], &len = a->t[3], &out = a->t[4]; diff --git a/libavx/avx_registry.cpp b/libavx/avx_registry.cpp index f9fb37f4..0bdd9d7b 100644 --- a/libavx/avx_registry.cpp +++ b/libavx/avx_registry.cpp @@ -142,6 +142,10 @@ static const RadParamSpec pMlaAttn[] = { P_INT("M"), P_INT("latent_dim"), P_INT( 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 RadOperandSpec oMlaAttn[] = { OPD("q"), OPD("kv"), OPD("bt"), OPD("length"), OUT("out") }; +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[] = { OPD("q"), OPD_O("q_rope"), OPD("kv"), + OPD("block_table"), OPD("seqused"), OPD("cu_seqlens"), OPD_O("gate"), OUT("out") }; static const RadParamSpec pDsaScore[] = { P_INT("M"), P_INT("n"), P_INT("heads"), P_INT("blocks"), P_INT("seqs"), P_STR("dtype"), P_INTO("row_part") }; static const RadOperandSpec oDsaScore[] = { OPD("q"), OPD("q_scale"), OPD("gate"), OPD("k"), @@ -151,6 +155,8 @@ static const RadOperandSpec oDsaPool[] = { OPD("kg"), WGT("ape"), OUT("q"), OUT( 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 RadOperandSpec oRouterSigmoid[] = { OPD("logits"), WGT("bias"), OUT("ids"), OUT("weights") }; +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 RadParamSpec pMnD[] = { P_INT("M"), P_INT("n"), P_STR("dtype") }; /* `add`'s `div` divides the rounded sum (libref's pAdd). */ static const RadParamSpec pAdd[] = { P_INT("M"), P_INT("n"), P_STR("dtype"), P_F64O("div") }; @@ -1000,6 +1006,10 @@ static const RadOpSchema kSchemas[] = { "products f32, the sine and cosine f32 rounded once to y's dtype. y is [M, n (2 freqs + 1)]." }, { "mla_attn", ARR(pMlaAttn), ARR(oMlaAttn), "Softmax over selected latent vectors used as both key and value; per-query page tables and visible lengths." }, +{ "mla_attn_paged", ARR(pMlaAttnPaged), ARR(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])))." }, { "mla_project", ARR(pMlaProject), ARR(oGemm), "Per-head query absorption or value expansion through the shared [head,(K|V),latent] BF16 matrix." }, { "dsa_score", ARR(pDsaScore), ARR(oDsaScore), @@ -1010,6 +1020,8 @@ static const RadOpSchema kSchemas[] = { "Normalized Hadamard, BF16 boundary and power-of-two E4M3 quantization per query head." }, { "dsa_pool", ARR(pDsaPool), ARR(oDsaPool), "Channel-wise softmax pooling with learned position bias, BF16, normalized Hadamard, BF16, power-of-two FP8." }, +{ "swiglu_step", ARR(pSwigluClamped), ARR(oGateUp), + "min(silu(gate),limit)*clamp(up,-limit,limit); gate is the first half." }, { "swiglu_clamped", ARR(pSwigluClamped), ARR(oGateUp), "silu(min(gate,limit))*clamp(up,-limit,limit); gate is the first half." }, { "silu_mul", ARR(pMnD), ARR(oGateUp), @@ -1165,6 +1177,9 @@ static const RadOpSchema kSchemas[] = { { "qk_norm_rope", ARR(pQkNormRope), ARR(oQkNormRope), "per-head QK norm then rotary embedding." }, { "scale_rows", ARR(pScaleRows), ARR(oScaleRows), "one scalar per row, optionally through an activation, broadcast across the row." }, +{ "router_sigmoid_group_topk", ARR(pRouterSigmoidGroup), ARR(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." }, { "router_sigmoid_topk", ARR(pRouterSigmoid), ARR(oRouterSigmoid), "Single-group sigmoid routing; correction bias selects experts, original scores weight them." }, { "router_topk", ARR(pRouter), ARR(oRouter), "softmax then exact top-k routing." }, @@ -1637,6 +1652,8 @@ SIMPLE("avx_seg_sinusoid", "seg_sinusoid", "elem", SIMPLE("avx_attn_local_rel", "attn_local_rel", "attn", "local attention with a relative-position term and a softcap", DT_FLOAT, L(attn_local_rel)), +SIMPLE("avx_mla_attn_paged", "mla_attn_paged", "attn", "dense paged latent attention with a rotary part", + DT_FLOAT, L(mla_attn_paged)), SIMPLE("avx_mla_attn", "mla_attn", "attn", "absorbed latent MQA attention", DT_FLOAT, L(mla_attn)), SIMPLE("avx_dsa_score", "dsa_score", "attn", "weighted FP8 index scoring", DT_FLOAT, @@ -1649,6 +1666,8 @@ SIMPLE("avx_gemm_nt_f32", "gemm_nt_f32", "gemm", "F32 routing projection", DT_FL L(gemm_nt_f32)), SIMPLE("avx_mla_project", "mla_project", "attn", "absorbed MLA projections", DT_FLOAT, L(mla_project)), +SIMPLE("avx_swiglu_step", "swiglu_step", "elem", "SwiGLU clipped after the SiLU", DT_FLOAT, + L(swiglu_step)), SIMPLE("avx_swiglu_clamped", "swiglu_clamped", "elem", "asymmetrically clipped SwiGLU", DT_FLOAT, L(swiglu_clamped)), SIMPLE("avx_silu_mul", "silu_mul", "elem", "silu-gated product over a fused gate_up", DT_FLOAT, @@ -1799,6 +1818,8 @@ SIMPLE("avx_qsa_work", "qsa_work", "attn", SIMPLE("avx_router_topk", "router_topk", "moe", "softmax then exact top-k routing", DT_FLOAT, L(router_topk)), +SIMPLE("avx_router_sigmoid_group_topk", "router_sigmoid_group_topk", "moe", + "group-limited sigmoid correction-bias routing", DT_FLOAT, L(router_sigmoid_group_topk)), SIMPLE("avx_router_sigmoid_topk", "router_sigmoid_topk", "moe", "sigmoid correction-bias routing", DT_FLOAT, L(router_sigmoid_topk)), SIMPLE("avx_router_topk_scatter", "router_topk_scatter", "moe",