diff --git a/docs/OPS.md b/docs/OPS.md index e923f0af..dcbefa00 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -595,6 +595,7 @@ and adding 0.0f is exact, so a block sum over 8 wave partials and over 32 are th | `moe_gather` | `M`(range) `n` `top_k` `dtype` `act`:str/opt | `y_expert`, `expert_w`, `sorted_tok`, `shared`?, `shared_gate`? → `y` | | `row_topk` | `M`(range) `N` `R` `vocab_off`/opt `dtype` | `x` → `idx`, `val`, `pairs`? | | `row_topk_merge` | `M` `R` `world_size` `dtype` | `gathered` → `idx`, `val` | +| `pair_argmax` | `M`(range) `n` `dtype` | `pairs` → `idx`, `val`? | | `logit_rerank` | `M`(range) `R` `n_vocab` `n_embd` `vocab_off`/opt `dtype` | `x`, `head`w, `idx_in` → `idx`, `val`, `pairs`? | `row_topk` and `row_topk_merge` are a pair, and the second only means anything with the first's @@ -610,6 +611,14 @@ over the unsharded plane element for element. A slot a shard could not fill carr `pairs` and is dropped -- a sentinel rather than a -inf value, because a masked logit takes that value legitimately. +`pair_argmax` is the merge at R = 1, for a vocab-sharded draft head that wants each position's +winner as a proposal: `idx` gets the id of the largest value among a row's `n` gathered pairs, +ties to the lower id, a negative id skipped, -1 (and -inf in `val`) when nothing is valid -- +written one element a row at the output's own pitch, which is what a block drafter's contiguous +proposal needs. It is not `row_topk_merge` with R = 1 because a rank still sends R >= 2 pairs: a +row-interleaved `all_gather` moves whole 16-byte words and one pair is 8 bytes, so `n` is +`world_size * R` and the op takes the top-1 of all of them. + `logit_rerank` is the second half of a COARSE top-R. A speculative step can afford a cheap draft head -- the target verifies every proposal, so a worse draft costs acceptance and never a token -- but a head quantised hard enough to be cheap also picks a different top-1 often enough to matter. diff --git a/libavx/avx_cases.cpp b/libavx/avx_cases.cpp index e35bd33f..ffc36152 100644 --- a/libavx/avx_cases.cpp +++ b/libavx/avx_cases.cpp @@ -344,6 +344,7 @@ std::vector build_cases() { add("row_topk", { HI("M", 5), HI("N", 97), HI("R", 4), HI("vocab_off", 0), HS("dtype", dt) }); add("row_topk_merge", { HI("M", 5), HI("R", 4), HI("world_size", 2), HS("dtype", dt) }); + add("pair_argmax", { HI("M", 5), HI("n", 8), HS("dtype", dt) }); /* "sorted" and not "slot": libref refuses any other spelling with RAD_E_UNSUPPORTED, and a case at a spelling both plugins decline is a case that proves nothing. */ for (const char* order : { "token", "sorted" }) { diff --git a/libavx/avx_isa.h b/libavx/avx_isa.h index a04ac88e..74ec5f7f 100644 --- a/libavx/avx_isa.h +++ b/libavx/avx_isa.h @@ -107,7 +107,7 @@ int avx_isa_force(int level); /* ---- mixture of experts */ \ X(router_topk) X(moe_scatter) X(moe_gemm) X(moe_gemm_q) \ X(moe_gather) X(row_topk) X(row_topk_merge) X(logit_rerank) \ - X(moe_gemm_q_mod4) \ + X(moe_gemm_q_mod4) X(pair_argmax) \ /* ---- gated delta net */ \ X(gdn_conv_prep) X(gdn_conv_update) X(gdn_kkt_solve) X(gdn_chunk_scan) \ X(gdn_recurrent_update) X(gdn_conv_recurrent_update) X(gdn_gated_rmsnorm) \ diff --git a/libavx/avx_moe.cpp b/libavx/avx_moe.cpp index aad45cbc..bbbe0c38 100644 --- a/libavx/avx_moe.cpp +++ b/libavx/avx_moe.cpp @@ -740,3 +740,37 @@ AVX_KERNEL(row_topk_merge) { } return RAD_OK; } + +/* ------------------------------------------------------------------ pair_argmax */ +/* row_topk_merge at R = 1, one id a row at the output's own pitch: the vocab-sharded draft head's + * proposal. Same pads, same tie rule, -1 and -inf for a row with nothing valid; `val` optional. + * + * LEFT SCALAR for the merge's reason, more so: `n` is world_size * R -- sixteen pairs at TP8 and + * R 2 -- and the whole op is one pass over them a row. */ +AVX_KERNEL(pair_argmax) { + if (!rad_args_have(a, 2)) return RAD_E_INVAL; + const RadTensor *p = &a->t[0], *idx = &a->t[1]; + const RadTensor* val = rad_arg_in(a, 2); + const int64_t n = p_int(a, "n", 0); + if (n <= 0) return RAD_E_SHAPE; + if (p->dtype != RAD_F32) return RAD_E_DTYPE; /* the id is carried by bit pattern */ + const int64_t M = numel(p) / (n * 2); + if (M <= 0 || numel(idx) < M || (val && numel(val) < M)) return RAD_E_SHAPE; + const float* const pf = (const float*)p->data; + + AVX_PARALLEL_FOR_IF(M * n >= 4096) + for (int64_t m = 0; m < M; ++m) { + int32_t bid = -1; + float bv = -INFINITY; + for (int64_t j = 0; j < n; ++j) { + int32_t id; + std::memcpy(&id, pf + offlin(p, (m * n + j) * 2), sizeof id); + if (id < 0) continue; /* a pad, not a candidate */ + const float v = pf[offlin(p, (m * n + j) * 2 + 1)]; + if (bid < 0 || v > bv || (v == bv && id < bid)) { bid = id; bv = v; } + } + st_int_dt(idx->dtype, idx->data, offlin(idx, m), bid); + if (val) stt(val, offlin(val, m), bv); + } + return RAD_OK; +} diff --git a/libavx/avx_registry.cpp b/libavx/avx_registry.cpp index 5d186896..443c6b97 100644 --- a/libavx/avx_registry.cpp +++ b/libavx/avx_registry.cpp @@ -348,6 +348,8 @@ static const RadOperandSpec oRowTopk[] = { OPD("x"), OUT("idx"), OUT("val"), OUT static const RadParamSpec pRowTopkMerge[] = { P_INT("M"), P_INT("R"), P_INT("world_size"), P_STR("dtype") }; static const RadOperandSpec oRowTopkMerge[] = { OPD("gathered"), OUT("idx"), OUT("val") }; +static const RadParamSpec pPairArgmax[] = { P_INT("M"), P_INT("n"), P_STR("dtype") }; +static const RadOperandSpec oPairArgmax[] = { OPD("pairs"), OUT("idx"), OUT_O("val") }; /* Mirrors libref's row exactly: R candidates rescored against the full-precision head, ties to the * lower id, pads sort last. libref's shape hook declines to describe this op, so the checker skips @@ -610,6 +612,8 @@ static const RadOpSchema kSchemas[] = { { "row_topk", ARR(pRowTopk), ARR(oRowTopk), "exact per-row top-R." }, { "row_topk_merge", ARR(pRowTopkMerge), ARR(oRowTopkMerge), "the global top-R of the gathered per-rank candidate sets." }, +{ "pair_argmax", ARR(pPairArgmax), ARR(oPairArgmax), + "the global top-1 of a row of gathered (id, value) pairs, one id a row." }, { "logit_rerank", ARR(pLogitRerank), ARR(oLogitRerank), "R candidates a row rescored exactly against the full-precision head." }, { "gdn_conv_prep", ARR(pConvPrep), ARR(oConvPrep), @@ -832,6 +836,9 @@ SIMPLE("avx_moe_gather", "moe_gather", "moe", "weighted scatter back to token or SIMPLE("avx_row_topk", "row_topk", "moe", "exact per-row top-R", DT_FLOAT, L(row_topk)), SIMPLE("avx_row_topk_merge", "row_topk_merge", "moe", "the global top-R of the gathered per-rank candidate sets", DT_FLOAT, L(row_topk_merge)), +SIMPLE("avx_pair_argmax", "pair_argmax", "moe", + "the global top-1 of a row of gathered (id, value) pairs, one id a row", DT_FLOAT, + L(pair_argmax)), SIMPLE("avx_logit_rerank", "logit_rerank", "moe", "R candidates a row rescored exactly against the full-precision head", DT_FLOAT, L(logit_rerank)), diff --git a/libref/ref_moe.cpp b/libref/ref_moe.cpp index c130799f..18af48d2 100644 --- a/libref/ref_moe.cpp +++ b/libref/ref_moe.cpp @@ -488,6 +488,47 @@ int ref_row_topk_merge(const RadArgs* a, RadStream) { return RAD_OK; } +/* ------------------------------------------------------------------ pair_argmax */ +/* row_topk_merge at R = 1, for a caller that wants the winner's id as a PROPOSAL rather than as + * a candidate list: one element a row, at the output's own pitch, so a block drafter's per-position + * picks land contiguous in the token buffer it verifies. `pairs` is the same gathered plane -- + * `n` (int32 id, f32 value) pairs a row, a negative id a pad -- and the rule is the same: the + * largest value, ties to the LOWER id, so the pick equals an argmax over the unsharded row. + * + * Its own op rather than row_topk_merge with R = 1 because the shapes differ where it matters: + * row_topk_merge's `gathered` is world_size * R pairs a row, and a rank that sends R = 1 sends 8 + * bytes, which a row-interleaved all_gather moving whole 16-byte words cannot carry. So a rank + * sends R >= 2 and this takes the top-1 of all of them, whatever `n` that makes. A row with no + * valid pair writes -1 and -inf, as the merge does for a slot it cannot fill. `val` is optional. */ +int ref_pair_argmax(const RadArgs* a, RadStream) { + if (!have(a, 2)) return RAD_E_INVAL; + const RadTensor *p = &a->t[0], *idx = &a->t[1]; + const RadTensor* val = t_in(a, 2); + const int64_t n = p_int(a, "n", 0); + if (n <= 0) return RAD_E_SHAPE; + if (p->dtype != RAD_F32) return RAD_E_DTYPE; /* the id is carried by bit pattern */ + /* The rows are the operand's, as on row_topk_merge: `M` is a band ceiling. */ + const int64_t M = numel(p) / (n * 2); + if (M <= 0 || numel(idx) < M || (val && numel(val) < M)) return RAD_E_SHAPE; + const float* const pf = (const float*)p->data; + + #pragma omp parallel for schedule(static) + for (int64_t m = 0; m < M; ++m) { + int32_t bid = -1; + float bv = -INFINITY; + for (int64_t j = 0; j < n; ++j) { + int32_t id; + std::memcpy(&id, pf + offlin(p, (m * n + j) * 2), sizeof id); + if (id < 0) continue; /* a pad, not a candidate */ + const float v = pf[offlin(p, (m * n + j) * 2 + 1)]; + if (bid < 0 || v > bv || (v == bv && id < bid)) { bid = id; bv = v; } + } + st_int(idx->dtype, idx->data, offlin(idx, m), bid); + if (val) stt(val, offlin(val, m), bv); + } + return RAD_OK; +} + /* ------------------------------------------------------------------ logit_rerank */ /* EXACTLY RESCORE R CANDIDATES A ROW AGAINST THE FULL-PRECISION HEAD. * diff --git a/libref/ref_ops.h b/libref/ref_ops.h index 083482bf..4df8f840 100644 --- a/libref/ref_ops.h +++ b/libref/ref_ops.h @@ -141,6 +141,7 @@ int ref_scale_rows (const RadArgs*, RadStream); int ref_moe_gather (const RadArgs*, RadStream); int ref_row_topk (const RadArgs*, RadStream); int ref_row_topk_merge (const RadArgs*, RadStream); +int ref_pair_argmax (const RadArgs*, RadStream); int ref_logit_rerank (const RadArgs*, RadStream); /* ---- gated delta net */ @@ -270,6 +271,7 @@ REF_SHAPE_FN(ref_scale_rows); REF_SHAPE_FN(ref_moe_gather); REF_SHAPE_FN(ref_row_topk); REF_SHAPE_FN(ref_row_topk_merge); +REF_SHAPE_FN(ref_pair_argmax); REF_SHAPE_FN(ref_logit_rerank); REF_SHAPE_FN(ref_gdn_conv_prep); diff --git a/libref/ref_registry.cpp b/libref/ref_registry.cpp index 470a8e88..b75ad818 100644 --- a/libref/ref_registry.cpp +++ b/libref/ref_registry.cpp @@ -444,6 +444,8 @@ static const RadOperandSpec oRowTopk[] = { OPD("x"), OUT("idx"), OUT("val"), OUT static const RadParamSpec pRowTopkMerge[] = { P_INT("M"), P_INT("R"), P_INT("world_size"), P_STR("dtype") }; static const RadOperandSpec oRowTopkMerge[] = { OPD("gathered"), OUT("idx"), OUT("val") }; +static const RadParamSpec pPairArgmax[] = { P_INT("M"), P_INT("n"), P_STR("dtype") }; +static const RadOperandSpec oPairArgmax[] = { OPD("pairs"), OUT("idx"), OUT_O("val") }; static const RadParamSpec pLogitRerank[] = { P_INT("M"), P_INT("R"), P_INT("n_vocab"), P_INT("n_embd"), P_INTO("vocab_off"), P_STR("dtype") }; @@ -935,6 +937,11 @@ static const RadOpSchema kSchemas[] = { "(idx, val) form the single-rank top-R produces. `gathered` is [M, world_size * R, 2] pairs, " "rank r's at [r*R, (r+1)*R); id -1 is a pad and is dropped. Ties break on the LOWER id, which is " "what makes the merged answer agree with a top-R over the unsharded plane." }, +{ "pair_argmax", ARR(pPairArgmax), ARR(oPairArgmax), + "idx[m] = the id of the largest value among pairs[m, 0..n), each pair an int32 id in the first " + "f32 slot and its value in the second (row_topk's `pairs`, all-gathered): ties to the lower " + "id, a negative id skipped, -1 and -inf where nothing is valid. row_topk_merge at R = 1, " + "written one element a row at the output's own pitch." }, { "logit_rerank", ARR(pLogitRerank), ARR(oLogitRerank), "Rescore R candidate ids a row EXACTLY against the full-precision head and re-sort on those " @@ -1244,6 +1251,7 @@ SIMPLE("ref_qsa_block_key", "qsa_block_key", "attn", ref_qsa_block_key), SIMPLE("ref_row_topk", "row_topk", "moe", "exact per-row top-R", DT_FLOAT, ref_row_topk), SIMPLE("ref_row_topk_merge", "row_topk_merge", "moe", "the global top-R of the gathered per-rank candidate sets", DT_FLOAT, ref_row_topk_merge), +SIMPLE("ref_pair_argmax", "pair_argmax", "moe", "the global top-1 of a row of gathered (id, value) pairs, one id a row", DT_FLOAT, ref_pair_argmax), SIMPLE("ref_logit_rerank", "logit_rerank", "moe", "R candidates a row rescored exactly against the full-precision head", DT_FLOAT, ref_logit_rerank), SIMPLE("ref_gdn_conv_prep", "gdn_conv_prep", "gdn", diff --git a/libref/ref_shapes.cpp b/libref/ref_shapes.cpp index 44456a1e..b3535f7f 100644 --- a/libref/ref_shapes.cpp +++ b/libref/ref_shapes.cpp @@ -1476,6 +1476,19 @@ int ref_row_topk_merge_shape(const RadParam* p, int n_p, int operand, RadOpdDesc return o.finish("row_topk_merge", operand, out); } +/* The same plane at R = 1 a row, and fillable for the same reason the merge's is: the value lane + * draws proper floats and the id lane their bit patterns, so pads are dropped, ids compared and + * copied, and ties do not occur. */ +int ref_pair_argmax_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); + if (M <= 0 || n <= 0) return RAD_E_UNSUPPORTED; + Opd o; + o.t((uint32_t)RAD_F32, { M, n, 2 }); /* pairs */ + o.t((uint32_t)RAD_I32, { M }); /* idx */ + o.t((uint32_t)RAD_F32, { M }); /* val */ + return o.finish("pair_argmax", operand, out); +} + /* logit_rerank DESCRIBES ITSELF, AND THE READER THAT NEEDS IT INVERTS FIRST. diff --git a/tests/ref_test.cpp b/tests/ref_test.cpp index d6d60278..a2975f8e 100644 --- a/tests/ref_test.cpp +++ b/tests/ref_test.cpp @@ -273,7 +273,7 @@ TEST(op_vocabulary) { "attn_paged", "attn_dense", "kv_store", "rope", "rope_table", "qk_norm_rope", "qsa_block_key", "router_topk", "moe_scatter", "moe_gemm", "moe_gemm_q", "moe_gemm_q_mod4", "moe_gather", "row_topk", - "row_topk_merge", "logit_rerank", + "row_topk_merge", "pair_argmax", "logit_rerank", "gdn_conv_prep", "gdn_conv_update", "gdn_kkt_solve", "gdn_chunk_scan", "gdn_recurrent_update", "gdn_conv_recurrent_update", "gdn_gated_rmsnorm", "all_reduce", "all_gather", @@ -604,6 +604,43 @@ TEST(op_scale) { CHECK(run("scale", b) != RAD_OK); } +/* The sharded draft head's merge at R = 1, on paper: three rows of four gathered pairs, each case + * one rule. Row 0 ties on 2.0 between ids 9 and 3 (the lower id wins, whatever slot it sits in) + * beside a pad carrying the row's largest value (dropped: a pad is a negative id, not a value); + * row 1 is all pads (-1 and -inf, nothing invented); row 2 is all negative values (the largest is + * still the answer). `idx` is written at a pitch of two, as a proposal lands in a token buffer laid + * out for something else, and the slots between are left alone. */ +TEST(op_pair_argmax) { + struct P { int32_t id; float v; }; + const P rows[3][4] = { + { { 5, 1.0f }, { 9, 2.0f }, { 3, 2.0f }, { -1, 7.0f } }, + { { -1, 9.0f }, { -1, 9.0f }, { -1, 9.0f }, { -1, 9.0f } }, + { { 7, -3.0f }, { 2, -4.0f }, { 11, -1.0f }, { 4, -1.5f } }, + }; + T pairs(RAD_F32, {3, 4, 2}); + float* pf = (float*)pairs.t.data; + for (int m = 0; m < 3; ++m) + for (int j = 0; j < 4; ++j) { + std::memcpy(&pf[(m * 4 + j) * 2], &rows[m][j].id, 4); + pf[(m * 4 + j) * 2 + 1] = rows[m][j].v; + } + T idx(RAD_I32, {3, 2}); idx.n({ 100, 100, 100, 100, 100, 100 }); + idx.t.shape[1] = 1; /* [3, 1] at a row pitch of 2 */ + T val(RAD_F32, {3}); + A a; a.t(pairs).t(idx).t(val).i("M", 3).i("n", 4).s("dtype", "f32"); + CHECK_OK(run("pair_argmax", a)); + CHECK_EQ(idx.iat(0), 3); CHECK_EQ(val.at(0), 2.0f); + CHECK_EQ(idx.iat(2), -1); CHECK(std::isinf(val.at(1)) && val.at(1) < 0); + CHECK_EQ(idx.iat(4), 11); CHECK_EQ(val.at(2), -1.0f); + CHECK_EQ(idx.iat(1), 100); CHECK_EQ(idx.iat(3), 100); + + /* `val` is optional, and the ids do not depend on it. */ + T idx2(RAD_I32, {3}); + A b; b.t(pairs).t(idx2).tnull().i("M", 3).i("n", 4).s("dtype", "f32"); + CHECK_OK(run("pair_argmax", b)); + CHECK_EQ(idx2.iat(0), 3); CHECK_EQ(idx2.iat(1), -1); CHECK_EQ(idx2.iat(2), 11); +} + /* The quantised gather. Three things, and the scale is the least interesting of them. * * The E4M3 codes are chosen so their VALUES are exact and writable as literals: 0x38 is 1.0,