diff --git a/.agents/evidence/vt-flash-order-20261130/PROCESS.md b/.agents/evidence/vt-flash-order-20261130/PROCESS.md new file mode 100644 index 0000000000..babe57474d --- /dev/null +++ b/.agents/evidence/vt-flash-order-20261130/PROCESS.md @@ -0,0 +1,68 @@ +# vt-flash-order — the ggml-flash-order arm of vt::PagedAttention (KERNEL-ATTN-PAGED) + +Shared-seam unit for the kolibri11-u3 attention-core fp order (issue +ISSUE-LOCAL-01M8MYQZRAX0KV2SV497RT2MRR, row KERNEL-ATTN-PAGED; worktree +row/KERNEL-ATTN-PAGED-ggml-flash-order off main ee9c3de77). + +- DEFECT (from /tmp/kolibri11-u3 sparse-layer-set-20261129.txt): the oracle + computes attention through ggml CPU flash_attn_ext (GGML_PREC_F32, F16 K/V, + ggml-cpu/ops.cpp:8858-9076 f16_one_chunk @ 5f4d22289) while the default + vt::PagedAttention body is a two-pass softmax — fp-noise-scale divergence + (rel 2.1e-5 at (L13,pos1) with bitwise-exact inputs) that flips greedy + tokens at depth. +- CHANGE: ADDITIVE `PagedAttentionArgs::ggml_flash_order` (default false = + byte-identical two-pass body, untouched) + the arm branch in + cpu_paged_attn.cpp mirroring ggml's accumulation order: Q rounded to the + F16 vec-dot grid BEFORE the dot (:8933-8934,8972), ggml's softcap fold + (scale/=cap, cap*tanhf, :8915-8925,8998-9000), per-key ONLINE softmax + M/S/VKQ with ms/vs (:9004-9034), typed widen V mad (:9024-9032), ggml sink + block AFTER the key loop (:9038-9053), final 1/S (:9064-9065). Same paged + jmin..jmax walk; page-major pages slice reused. CPU-only; no provider + refusal extended (uniform_spec_query_len routing pattern). +- RED-FIRST: tests/vt/test_ops_paged_attn_ggml_flash_order.cpp failed to + COMPILE pre-arm ("no member named ggml_flash_order") — red-compile.log. +- GREEN: 4 cases / 16 assertions (red-compile.log, arm-green.log): + (1) INERTNESS default == the transcribed two-pass body byte-for-byte; + (2) ARM == GgmlFlashOrderRef (the scalar transcription of ggml's order) + byte-for-byte, over F16 KV, F32 KV, intersecting sliding window, and + the ggml softcap fold (a different fold than the default body's — + pinned separately); (3) DISCRIMINATOR arm != default on the same + fixture (the F16 query rounding plus the online rescale sequence). +- SIBLING INERTNESS: test_ops_paged_attn, _dtype, _neon, + test_ops_dflash_paged_block_attn, test_paged_attn_route all RC=0 + unchanged. +- MUTATION: `S = S*ms + vs` -> `S = S + vs` in the arm => arm test REDS + 4/4 cases, 4 assertions (mutation-red.log); restored BYTE-FOR-BYTE (cmp + clean) => 16/16 green again. +- HONEST SCOPE: the reference is the scalar f32 sequential transcription of + ggml's order (the NEON widened-lane scalar order). A live-oracle bit-proof + of ggml's SIMD lane grouping (vec.cpp ggml_vec_dot_f16) and the consumer + rewiring (kolibri1 setting the field per model) are the follow-up wave, + like the quant seam. The W1 flash harness named by the dispatch does not + exist on this host (/tmp worktrees searched); the transcription IS the + reference per the dispatch's METHOD clause. +- PREFLIGHT: agent-preflight.sh --staged RC=0 (preflight-staged.log; first + run failed role-undeclared — helper claimed under KERNEL-ATTN-PAGED, not a + checker change). No push. +- 2026-11-30 — F1 REPAIR (4a9383062). Review finding: the inertness guarantee + was only detected inside the arm suite; the sibling test_ops_paged_attn.cpp + compares at epsilon 1e-4..1e-5, an order above the ~2e-5 default-flip + divergence. Reproduced RED-first: flipping the field default + (include/vt/ops.h:2101) to true left the sibling GREEN (15/15 cases, 1838 + assertions, rc=0 — /tmp/vtfo-mut1-sib.log) while the arm suite redded 4/4 + (/tmp/vtfo-mut1-arm.log). Repair is additive: one focused pin in the + sibling suite, "paged_attention default body is byte-identical to the + two-pass transcription" (tests/vt/test_ops_paged_attn.cpp, TwoPassDefault- + BytesRef transcription of the default body, memcmp equality, multi-block + varlen GQA fixture, no epsilon touched). Under the flip the pin REDS + (memcmp -1, rc=1, 1839/1840) — /tmp/vtfo-mut1-sib2.log. Restore: + ops.h byte-clean (git diff empty), all six focused suites GREEN — + new arm suite, test_ops_paged_attn (16/16, 1840), _dtype, _neon, + test_ops_dflash_paged_block_attn, test_paged_attn_route + (/tmp/vtfo-green-*.log). Mutation 2 (neuter dispatch, `if (false && ...)`): + arm suite REDS 4/4 cases / 12 assertions as before + (/tmp/vtfo-mut2-arm.log); sibling green as expected (pin covers the + default path, not the dispatch); restored byte-clean. PREFLIGHT: + agent-preflight.sh --staged RC=0 (/tmp/vtfo-preflight-f1.log). Committed + 4a938306271f20c7390003765426e94de6a993fe on row/KERNEL-ATTN-PAGED-ggml- + flash-order; no push. diff --git a/.agents/issues/KERNEL-ATTN-PAGED/ISSUE-LOCAL-01M8MYQZRAX0KV2SV497RT2MRR.md b/.agents/issues/KERNEL-ATTN-PAGED/ISSUE-LOCAL-01M8MYQZRAX0KV2SV497RT2MRR.md new file mode 100644 index 0000000000..1071bcad19 --- /dev/null +++ b/.agents/issues/KERNEL-ATTN-PAGED/ISSUE-LOCAL-01M8MYQZRAX0KV2SV497RT2MRR.md @@ -0,0 +1,19 @@ +ID: ISSUE-LOCAL-01M8MYQZRAX0KV2SV497RT2MRR +Title: vt::PagedAttention ggml-flash-order arm (shared seam, kolibri11-u3 core fp order) +Row: KERNEL-ATTN-PAGED +State: OPEN +Kind: bug +GitHub: - +Mirror: PENDING +Availability: FULL +Created: 2026-11-30 +Updated: 2026-11-30 +Closed: - + +## Problem + +The kolibri11-u3 lane localized the remaining token divergence INSIDE the attention core arithmetic: with bitwise-exact inputs at (L13,pos1) the kqv core differs at rel 2.1e-5 (max abs 7.7e-6) because the oracle computes attention through ggml CPU flash_attn_ext (GGML_PREC_F32, F16 K/V, llama-graph.cpp:3173-3340 @ PR 5f4d22289) while ours runs the vt::PagedAttention two-pass softmax order (cpu_paged_attn.cpp). The fp-noise-scale difference accumulates through layers and flips greedy tokens at depth (24-golden gate stuck 6/24; raw probe holds 9224,46,14147). This unit adds an ADDITIVE opt-in ggml-flash-order arm in/behind vt::PagedAttention (per-call field, default false = byte-identical), mirroring ggml_compute_forward_flash_attn_ext_f16_one_chunk's accumulation order (Q to vec-dot F16, scale-after-dot, per-key online-softmax M/S/VKQ rescale, F16 V mad, final 1/S scale, ops.cpp:8858-9076). Consumer rewiring (kolibri1) is the follow-up wave, like the quant seam. Evidence: /tmp/kolibri11-u3/docs/bench-evidence/kolibri11-u3-oracle-20261125/sparse-layer-set-20261129.txt; precedent rows QUANT-GGUF-CIQ-GEMM-gemm-q80-fma and QUANT-GGUF-CIQ-GEMM-q4k-q6k-repack (6c510a9eb). + +## Resolution + +2026-11-30: SEAM ARM LANDED (shared-seam unit, row KERNEL-ATTN-PAGED): the additive PagedAttentionArgs::ggml_flash_order arm is in the CPU kernel (commit a6a533881, branch row/KERNEL-ATTN-PAGED-ggml-flash-order off main ee9c3de77), default-off byte-identical, bit-exact vs the scalar transcription of ggml flash_attn_ext_f16_one_chunk (ops.cpp:8858-9076 @ 5f4d22289) on F16 KV, F32 KV, intersecting window, and the ggml softcap fold; mutation-verified (S-bend reds 4/4, restore byte-identical green). OWED / issue stays OPEN: no model sets the field yet — the kolibri1 consumer rewiring and a live-oracle bit-proof of ggml's SIMD lane grouping (vec.cpp ggml_vec_dot_f16) are the follow-up wave, like the quant seam. Evidence: .agents/evidence/vt-flash-order-20261130/ on that branch. diff --git a/include/vt/ops.h b/include/vt/ops.h index 645b971231..30895584f2 100644 --- a/include/vt/ops.h +++ b/include/vt/ops.h @@ -2082,6 +2082,23 @@ struct PagedAttentionArgs { // softmax (the output is renormalised over the real keys only). This mirrors // the gpt-oss sink mechanism. nullptr => no sink (every model before MiMoV2). const Tensor* attn_sink = nullptr; + // ADDITIVE ggml-flash-order arm (KERNEL-ATTN-PAGED shared-seam unit, issue + // ISSUE-LOCAL-01M8MYQZRAX0KV2SV497RT2MRR): when true the CPU kernel computes + // attention in ggml CPU flash_attn_ext's accumulation order + // (GGML_PREC_F32 semantics: the query row rounded to the K vec-dot type's + // F16 grid BEFORE the dot, scale-after-dot folded per ggml's scale/=softcap + // setup, per-key ONLINE softmax with the M/S/VKQ rescale, F16 V widened mad, + // final 1/S scale — ggml-cpu/ops.cpp:8858-9076 @ 5f4d22289) instead of the + // two-pass softmax body. Same math, different fp accumulation order: the arm + // exists so a consumer can mirror an oracle whose attention runs through + // ggml's flash_attn_ext bit-for-bit (fp-noise-scale divergence flips greedy + // tokens at depth). FALSE (default) leaves the two-pass body byte-identical + // — every existing caller gets exactly the pre-arm order. CPU-only: the + // field extends no provider refusal (the uniform_spec_query_len routing + // pattern); non-CPU providers ignore it. The ggml sink block runs AFTER the + // key loop (ops.cpp:9038-9053), which is a different order from the seeded + // two-pass sink handling — the arm reorders it faithfully. + bool ggml_flash_order = false; }; // Arguments for vt::MlaDecodeAttention (MLA campaign W4). Mirrors the scalar diff --git a/src/vt/cpu/cpu_paged_attn.cpp b/src/vt/cpu/cpu_paged_attn.cpp index 31096ad81f..6bf1691c13 100644 --- a/src/vt/cpu/cpu_paged_attn.cpp +++ b/src/vt/cpu/cpu_paged_attn.cpp @@ -394,6 +394,108 @@ using vt::cpu::PagedAttnKDotBfDot; q_bytes + static_cast((t * hq + h) * d) * q_esize, d, qrow.data()); q = qrow.data(); + } + if (args.ggml_flash_order) { + // ADDITIVE ggml-flash-order arm (KERNEL-ATTN-PAGED, issue + // ISSUE-LOCAL-01M8MYQZRAX0KV2SV497RT2MRR): the accumulation order of + // ggml CPU flash_attn_ext (GGML_PREC_F32), transcribed from + // ggml_compute_forward_flash_attn_ext_f16_one_chunk + // (ggml-cpu/ops.cpp:8858-9076 @ 5f4d22289). The walk stays the same + // ascending paged jmin..jmax (ggml's F16 mask row is exactly the + // window the walk visits; a masked cell is one it never reads, the + // `mv == -INFINITY` skip at :8981-8984). Per ggml: + // - Q is converted to the K vec-dot type BEFORE the dot + // (:8933-8934,8972) — for F16 K the query rounds onto the F16 + // grid, a rounding the two-pass body never applies; + // - the scale folds per ggml's setup (:8915-8925): sc = scale, + // scale/cap when a softcap is set, then cap*tanhf(s) (:8998-9000) + // — NOT the two-pass body's cap*tanh(s/cap) after scaling; + // - the softmax is ONLINE per key (:9004-9034): M/S running state, + // ms = expf(Mold-M) rescales VKQ on a new maximum, vs = + // expf(s-M) widens the V term, S = S*ms + vs — no two-pass + // max pass, no normalized probabilities; + // - V is widened to f32 and mad-ed into the f32 VKQ accumulator + // (:9024-9032) — via the typed KvElem read, so every cache + // dtype the kernel serves keeps its read semantics; + // - the per-head sink joins AFTER the key loop (:9038-9053); + // - the final scale is 1/S (:9064-9065). + // The scalar f32 sequential accumulation is the NEON widened-lane + // order (each product in f32, summed in sequence); the arm is + // opt-in, default-off, and the two-pass body below is untouched. + std::vector q16; + const bool k_is_f16 = kv_kind == KvKind::kF16; + if (k_is_f16) { + q16.resize(static_cast(d)); + for (int64_t e = 0; e < d; ++e) + q16[static_cast(e)] = + vt::F32ToF16(q[static_cast(e)]); + } + float M = -std::numeric_limits::infinity(); + float S = 0.0f; + for (int64_t e = 0; e < d_v; ++e) acc[static_cast(e)] = 0.0f; + const float sc = softcap != 0.0f ? scale / softcap : scale; + for (int64_t j = jmin; j <= jmax;) { + // Page-major walk, the same ascending key order the scalar body + // uses (the pages slice was resolved above). + const int64_t pb = j / block_size; + const int64_t blk = pages[static_cast(pb - page0)]; + const int64_t kpage = blk * kc_blk + g * kc_hd; + const int64_t vpage = blk * vc_blk + g * vc_hd; + const int64_t page_end = std::min(jmax, (pb + 1) * block_size - 1); + for (; j <= page_end; ++j) { + const int64_t off = j - pb * block_size; + const int64_t kbase = kpage + off * kc_pg; + float dot = 0.0f; + for (int64_t e = 0; e < d; ++e) { + const float kv = + KvElem(k_base, kbase + e, k_scale); + const float qv = k_is_f16 + ? vt::F16ToF32(q16[static_cast(e)]) + : q[static_cast(e)]; + dot += kv * qv; + } + float s = dot * sc; + if (softcap != 0.0f) s = softcap * std::tanh(s); + const float Mold = M; + float ms = 1.0f, vs = 1.0f; + const int64_t vbase = vpage + off * vc_pg; + if (s > M) { + M = s; + ms = std::exp(Mold - M); + for (int64_t e = 0; e < d_v; ++e) + acc[static_cast(e)] *= ms; + } else { + vs = std::exp(s - M); + } + for (int64_t e = 0; e < d_v; ++e) + acc[static_cast(e)] += + KvElem(v_base, vbase + e, + v_scale) * + vs; + S = S * ms + vs; + } + } + // The ggml sink block, AFTER the key loop (:9038-9053): a new sink + // maximum rescales VKQ by expf(M-s), otherwise the sink joins at + // expf(s-M). The two-pass body seeds the max AT the sink instead — + // the arm keeps ggml's order faithfully. + if (sink_p != nullptr) { + const float s = sink_p[static_cast(h)]; + float ms = 1.0f, vs = 1.0f; + if (s > M) { + ms = std::exp(M - s); + M = s; + for (int64_t e = 0; e < d_v; ++e) + acc[static_cast(e)] *= ms; + } else { + vs = std::exp(s - M); + } + S = S * ms + vs; + } + const float S_inv = S == 0.0f ? 0.0f : 1.0f / S; + for (int64_t e = 0; e < d_v; ++e) acc[static_cast(e)] *= S_inv; + StoreRowF32(out, qoff, d_v, acc.data()); + continue; } // Pass 1: scores + running max. // SEEDED BY THE PER-Q-HEAD ATTENTION SINK when one is present. diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 25d401d788..817126da26 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -4068,6 +4068,11 @@ vllm_cpp_add_test(test_paged_attn_route vt/test_paged_attn_route.cpp) # PERF-CPU-ATTN-DTYPE: the hoisted dtype dispatch vs the pre-change per-element # switch, memcmp over every dtype the switch handled (spec §3, issue #391). vllm_cpp_add_test(test_ops_paged_attn_dtype vt/test_ops_paged_attn_dtype.cpp) +# KERNEL-ATTN-PAGED shared-seam unit: the additive ggml-flash-order arm of the +# CPU paged-attention kernel (ggml flash_attn_ext accumulation order, +# ops.cpp:8858-9076 @ 5f4d22289), inert-by-default, bit-exact vs the +# transcription reference. +vllm_cpp_add_test(test_ops_paged_attn_ggml_flash_order vt/test_ops_paged_attn_ggml_flash_order.cpp) vllm_cpp_add_test(test_ops_sample vt/test_ops_sample.cpp) if(UNIX) add_test(NAME test_rocm_sample_scratch diff --git a/tests/vt/test_ops_paged_attn.cpp b/tests/vt/test_ops_paged_attn.cpp index 46473e94ae..ef983a6bd2 100644 --- a/tests/vt/test_ops_paged_attn.cpp +++ b/tests/vt/test_ops_paged_attn.cpp @@ -345,6 +345,122 @@ TEST_CASE("paged_attention batched varlen (prefill + decode) vs composed referen CHECK(got[i] == doctest::Approx(ref[i]).epsilon(1e-5)); } +// =========================================================================== +// DEFAULT-BODY BYTE PIN (KERNEL-ATTN-PAGED F1): the DEFAULT paged-attention +// path (`ggml_flash_order == false`, the value every existing caller gets) +// must reproduce the pre-arm two-pass body BYTE-IDENTICALLY, memcmp over the +// raw float bytes — no epsilon. The tolerance-based comparisons above test +// other properties and cannot see a default flip: the ggml-flash-order arm +// diverges from the two-pass body at ~2e-5 fp-noise scale, far inside their +// 1e-4..1e-5 epsilon. Same technique as the arm suite's inertness pin +// (tests/vt/test_ops_paged_attn_ggml_flash_order.cpp): a scalar transcription +// of the default body from src/vt/cpu/cpu_paged_attn.cpp — sequential f32 +// dot, two-pass softmax (scores+max, then exp/denominator), normalized +// weighted V sum — over the same ascending paged key walk. +// =========================================================================== +namespace { + +std::vector TwoPassDefaultBytesRef(const std::vector& q, + const std::vector& kc, + const std::vector& vc, + const std::vector& block_table, + int64_t max_blocks, + const std::vector& seq_lens, + const std::vector& qsl, + int64_t hq, int64_t hk, int64_t d, + int64_t block_size, float scale) { + const int64_t num_reqs = static_cast(seq_lens.size()); + const int64_t num_tokens = qsl.back(); + const int64_t qpk = hq / hk; + std::vector out(static_cast(num_tokens * hq * d), 0.0f); + for (int64_t r = 0; r < num_reqs; ++r) { + const int64_t q0 = qsl[static_cast(r)]; + const int64_t qlen = + qsl[static_cast(r + 1)] - q0; + const int64_t context = seq_lens[static_cast(r)] - qlen; + for (int64_t local = 0; local < qlen; ++local) { + const int64_t t = q0 + local; + const int64_t p = context + local; + for (int64_t h = 0; h < hq; ++h) { + const int64_t g = h / qpk; + const int64_t qoff = (t * hq + h) * d; + const int64_t jmax = p; // causal + std::vector probs(static_cast(jmax + 1), 0.0f); + float m = -std::numeric_limits::infinity(); + for (int64_t j = 0; j <= jmax; ++j) { + const int64_t blk = block_table[static_cast(r * max_blocks + j / block_size)]; + const int64_t off = j % block_size; + const int64_t kbase = ((blk * block_size + off) * hk + g) * d; + float dot = 0.0f; + for (int64_t e = 0; e < d; ++e) + dot += q[static_cast(qoff + e)] * kc[static_cast(kbase + e)]; + dot *= scale; + probs[static_cast(j)] = dot; + if (dot > m) m = dot; + } + float denom = 0.0f; + for (int64_t j = 0; j <= jmax; ++j) { + const float e = std::exp(probs[static_cast(j)] - m); + probs[static_cast(j)] = e; + denom += e; + } + const float inv = 1.0f / denom; + for (int64_t e = 0; e < d; ++e) { + float acc = 0.0f; + for (int64_t j = 0; j <= jmax; ++j) { + const int64_t blk = block_table[static_cast(r * max_blocks + j / block_size)]; + const int64_t off = j % block_size; + const int64_t vbase = ((blk * block_size + off) * hk + g) * d; + const float pw = probs[static_cast(j)] * inv; + acc += pw * vc[static_cast(vbase + e)]; + } + out[static_cast(qoff + e)] = acc; + } + } + } + } + return out; +} + +} // namespace + +TEST_CASE("paged_attention default body is byte-identical to the two-pass transcription") { + const int64_t Hq = 4, Hk = 2, D = 16, block_size = 4; + const float scale = std::pow(static_cast(D), -0.5f); + // Same shape family as the arm suite's inertness fixture: two requests, one + // decode + a 3-token prefill over a 9-key context spanning 3 pages. + const int64_t num_tokens = 3; + std::vector qsl = {0, 1, 3}; + std::vector seq_lens = {1, 9}; + const int64_t num_blocks = 6, page = Hk * D, max_blocks = 3; + auto q = RandF32(static_cast(num_tokens * Hq * D), 2024); + auto kc = RandF32(static_cast(num_blocks * block_size * page), 137); + auto vc = RandF32(static_cast(num_blocks * block_size * page), 179); + // req0 seq1 → 1 block; req1 seq9 → 3 blocks; non-identity, disjoint. + std::vector block_table = {3, 0, 0, + 1, 4, 2}; + + std::vector ref = TwoPassDefaultBytesRef( + q, kc, vc, block_table, max_blocks, seq_lens, qsl, Hq, Hk, D, + block_size, scale); + + Queue qq = Q(); + Tensor tq = F32(q, {num_tokens, Hq, D}); + Tensor tkc = Contig(kc.data(), DType::kF32, Cpu(), {num_blocks, block_size, Hk, D}); + Tensor tvc = Contig(vc.data(), DType::kF32, Cpu(), {num_blocks, block_size, Hk, D}); + Tensor tbt = I32(block_table, {2, max_blocks}); + Tensor tsl = I32(seq_lens, {2}); + Tensor tqsl = I32(qsl, {3}); + std::vector got(ref.size(), 0.0f); + Tensor tp = F32(got, {num_tokens, Hq, D}); + // DEFAULT selection: `ggml_flash_order` left at its field default. + PagedAttentionArgs args{scale, true}; + vt::PagedAttention(qq, tp, tq, tkc, tvc, tbt, tsl, tqsl, args); + + REQUIRE(got.size() == ref.size()); + CHECK(std::memcmp(got.data(), ref.data(), got.size() * sizeof(float)) == 0); +} + // =========================================================================== // Causal masking: a decode query (context 2, seq_len 3) must ignore nothing up // to its own position, but a prefill query at position 0 must see only key 0 diff --git a/tests/vt/test_ops_paged_attn_ggml_flash_order.cpp b/tests/vt/test_ops_paged_attn_ggml_flash_order.cpp new file mode 100644 index 0000000000..e4ec4f1d9b --- /dev/null +++ b/tests/vt/test_ops_paged_attn_ggml_flash_order.cpp @@ -0,0 +1,411 @@ +// vllm.cpp original (vt runtime); no upstream mirror. +// +// KERNEL-ATTN-PAGED shared-seam unit: the ADDITIVE ggml-flash-order arm of the +// CPU vt::PagedAttention kernel (issue +// .agents/issues/KERNEL-ATTN-PAGED/ISSUE-LOCAL-01M8MYQZRAX0KV2SV497RT2MRR.md). +// +// The kolibri11-u3 lane localized the last token divergence INSIDE the +// attention core arithmetic: the oracle computes attention through ggml CPU +// flash_attn_ext (GGML_PREC_F32, F16 K/V, +// ggml/src/ggml-cpu/ops.cpp:8858-9076 f16_one_chunk @ 5f4d22289) while the +// default vt::PagedAttention body is a two-pass softmax (scores+max pass, +// exp/denominator pass, then a normalized weighted V sum, +// src/vt/cpu/cpu_paged_attn.cpp). Same math, different fp accumulation order, +// fp-noise-scale divergence that flips greedy tokens at depth. +// +// This file pins the additive arm three ways, bit-for-byte (memcmp over the +// raw storage bytes), never with a tolerance: +// +// 1. INERTNESS — `args.ggml_flash_order == false` (the default every +// existing caller gets) reproduces the two-pass body BYTE-IDENTICALLY on +// shapes where the two orders genuinely diverge when the arm IS selected. +// The default path must not move. +// 2. ARM — `args.ggml_flash_order == true` reproduces `GgmlFlashOrderRef` +// below, a literal scalar transcription of ggml's +// flash_attn_ext_f16_one_chunk accumulation order (Q rounded to the K +// vec-dot type's F16 grid BEFORE the dot — from_float for the F16 +// vec_dot_type, ops.cpp:8933-8934,8972; scale folded per ggml's +// scale/=softcap setup :8919-8925; per-key online update M/S/VKQ with +// ms/vs :9004-9034; F16 V widened mad :9024-9025; the ggml sink block +// AFTER the key loop :9038-9053; final 1/S scale :9064-9065), walking +// keys in the same ascending paged order the kernel walks. The scalar +// f32 accumulation is the NEON widened-lane order (each product computed +// in f32, summed sequentially); a live-oracle bit-proof of the SIMD lane +// grouping is the consumer wave's adjudication, as with the quant seam. +// 3. DISCRIMINATOR — on a shape where the orders differ, the arm's output +// DIFFERS from the default output. A test that only proves +// arm == reference while the arm == default would pin nothing. +// +// Mutating any accumulator term in the arm (scale placement, ms/vs update, +// the F16 query rounding, the final normalization) makes case 2 memcmp-fail +// while case 1 stays green. +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "vt/backend.h" +#include "vt/dtype.h" +#include "vt/ops.h" + +using vt::AttentionWindow; +using vt::Device; +using vt::DeviceType; +using vt::DType; +using vt::PagedAttentionArgs; +using vt::Queue; +using vt::Tensor; + +namespace { + +Device Cpu() { return Device{DeviceType::kCPU, 0}; } +Queue Q() { return Queue{Cpu(), nullptr}; } + +Tensor Contig(void* data, DType dt, const std::vector& shape) { + Tensor t; + t.data = data; + t.dtype = dt; + t.device = Cpu(); + t.rank = static_cast(shape.size()); + int64_t stride = 1; + for (int i = t.rank - 1; i >= 0; --i) { + t.shape[i] = shape[static_cast(i)]; + t.stride[i] = stride; + stride *= shape[static_cast(i)]; + } + return t; +} + +// Deterministic xorshift so both orders see identical bytes on every run. +uint32_t Xorshift(uint32_t& s) { + s ^= s << 13; + s ^= s >> 17; + s ^= s << 5; + return s; +} +float RandUnit(uint32_t& s) { + int32_t r = static_cast(Xorshift(s) % 2000001u) - 1000000; + return static_cast(r) / 1000000.0f; +} + +struct Fixture { + std::vector q_f32; // query base, always materialized f32 + std::vector k_f16, v_f16; + std::vector k_f32, v_f32; + std::vector btab, slens, qsl; + std::vector out_def, out_arm, out_ref; + int64_t total_q = 0, hq = 0, d = 0, d_v = 0, num_kv_heads = 0; + int64_t block_size = 0, max_blocks = 0, num_reqs = 0; + bool f16_kv = true; +}; + +// A small varlen paged batch: request 0 decodes one fresh token (context 0); +// request 1 queries 2 tokens over a 9-key context (3 pages); a 5/5 sliding +// window intersects the causal bound when requested. +Fixture MakeFixture(bool f16_kv) { + Fixture fx; + fx.f16_kv = f16_kv; + fx.hq = 4; + fx.num_kv_heads = 2; + fx.d = 16; // QK width + fx.d_v = 16; + fx.block_size = 4; + fx.num_reqs = 2; + fx.slens = {1, 9}; + fx.qsl = {0, 1, 3}; + fx.total_q = 3; + fx.max_blocks = 3; + const int64_t npages = fx.num_reqs * fx.max_blocks; + fx.btab.assign(static_cast(npages), 0); + for (int64_t r = 0; r < fx.num_reqs; ++r) + for (int64_t b = 0; b < fx.max_blocks; ++b) + fx.btab[static_cast(r * fx.max_blocks + b)] = + static_cast(r * fx.max_blocks + b); + const int64_t cache_page = fx.block_size * fx.num_kv_heads * fx.d; + fx.k_f16.resize(static_cast(npages * cache_page)); + fx.v_f16.resize(fx.k_f16.size()); + fx.k_f32.resize(fx.k_f16.size()); + fx.v_f32.resize(fx.k_f16.size()); + uint32_t s = 0x5eed1234u; + for (size_t i = 0; i < fx.k_f16.size(); ++i) { + fx.k_f32[i] = RandUnit(s); + fx.v_f32[i] = RandUnit(s); + fx.k_f16[i] = vt::F32ToF16(fx.k_f32[i]); + fx.v_f16[i] = vt::F32ToF16(fx.v_f32[i]); + } + fx.q_f32.resize(static_cast(fx.total_q * fx.hq * fx.d)); + for (auto& x : fx.q_f32) x = RandUnit(s); + fx.out_def.assign(static_cast(fx.total_q * fx.hq * fx.d_v), 0.0f); + fx.out_arm.resize(fx.out_def.size()); + fx.out_ref.resize(fx.out_def.size()); + return fx; +} + +Tensor FxQuery(const Fixture& fx) { + return Contig(const_cast(fx.q_f32.data()), DType::kF32, + {fx.total_q, fx.hq, fx.d}); +} +Tensor FxK(const Fixture& fx) { + const int64_t npages = fx.num_reqs * fx.max_blocks; + return fx.f16_kv + ? Contig(const_cast(fx.k_f16.data()), DType::kF16, + {npages, fx.block_size, fx.num_kv_heads, fx.d}) + : Contig(const_cast(fx.k_f32.data()), DType::kF32, + {npages, fx.block_size, fx.num_kv_heads, fx.d}); +} +Tensor FxV(const Fixture& fx) { + const int64_t npages = fx.num_reqs * fx.max_blocks; + return fx.f16_kv + ? Contig(const_cast(fx.v_f16.data()), DType::kF16, + {npages, fx.block_size, fx.num_kv_heads, fx.d_v}) + : Contig(const_cast(fx.v_f32.data()), DType::kF32, + {npages, fx.block_size, fx.num_kv_heads, fx.d_v}); +} +Tensor FxOut(Fixture& fx, std::vector& buf) { + return Contig(buf.data(), DType::kF32, {fx.total_q, fx.hq, fx.d_v}); +} +Tensor FxI32(const std::vector& v, const std::vector& shape) { + return Contig(const_cast(v.data()), DType::kI32, shape); +} + +PagedAttentionArgs BaseArgs(float scale, bool with_window) { + PagedAttentionArgs a; + a.scale = scale; + if (with_window) a.window_size = AttentionWindow{5, 5}; + return a; +} + +void RunK(Fixture& fx, std::vector& out, const PagedAttentionArgs& a) { + Queue q = Q(); + auto qt = FxQuery(fx); + auto k = FxK(fx); + auto v = FxV(fx); + auto o = FxOut(fx, out); + auto btab = FxI32(fx.btab, {fx.num_reqs, fx.max_blocks}); + auto slens = FxI32(fx.slens, {fx.num_reqs}); + auto qsl = FxI32(fx.qsl, {fx.num_reqs + 1}); + vt::PagedAttention(q, o, qt, k, v, btab, slens, qsl, a); +} + +bool BytesEqual(const std::vector& a, const std::vector& b) { + return a.size() == b.size() && + std::memcmp(a.data(), b.data(), a.size() * sizeof(float)) == 0; +} + +int CountByteDiffs(const std::vector& a, const std::vector& b) { + int n = 0; + for (size_t i = 0; i < a.size() && i < b.size(); ++i) + if (std::memcmp(&a[i], &b[i], sizeof(float)) != 0) ++n; + return n; +} + +// Request/local-position resolution shared by both references (mirrors the +// kernel's tok_pos/tok_slen/tok_req precompute). +void FxResolve(const Fixture& fx, int64_t t, int64_t& r, int64_t& p) { + r = t == 0 ? 0 : 1; + const int64_t local = t == 0 ? 0 : t - 1; + const int64_t query_len = + fx.qsl[static_cast(r + 1)] - fx.qsl[static_cast(r)]; + const int64_t context = fx.slens[static_cast(r)] - query_len; + p = context + local; +} + +void FxWindow(const Fixture&, bool with_window, int64_t p, int64_t& jmin, + int64_t& jmax) { + jmin = with_window ? std::max(0, p - 5) : 0; + jmax = with_window ? std::min(p, p + 5) : p; // causal +} + +// --------------------------------------------------------------------------- +// GgmlFlashOrderRef: literal scalar transcription of ggml's +// flash_attn_ext_f16_one_chunk (ops.cpp:8858-9076 @ 5f4d22289) over the SAME +// paged walk the kernel uses (ascending keys jmin..jmax through the block +// table; the causal/window bound replaces ggml's F16 mask — a masked cell is +// one the walk never visits, i.e. ggml's `mv == -INFINITY` skip :8981-8984). +// --------------------------------------------------------------------------- +void GgmlFlashOrderRef(const Fixture& fx, std::vector& out, float scale, + bool with_window, float softcap) { + const int64_t d = fx.d, d_v = fx.d_v, block_size = fx.block_size; + out.assign(static_cast(fx.total_q * fx.hq * d_v), 0.0f); + std::vector q_f16(static_cast(d)); + const float sc = softcap != 0.0f ? scale / softcap : scale; + for (int64_t t = 0; t < fx.total_q; ++t) { + int64_t r = 0, p = 0; + FxResolve(fx, t, r, p); + int64_t jmin = 0, jmax = 0; + FxWindow(fx, with_window, p, jmin, jmax); + for (int64_t h = 0; h < fx.hq; ++h) { + const int64_t g = h / (fx.hq / fx.num_kv_heads); + const float* q = &fx.q_f32[static_cast((t * fx.hq + h) * d)]; + if (fx.f16_kv) + for (int64_t e = 0; e < d; ++e) + q_f16[static_cast(e)] = vt::F32ToF16(q[e]); + float M = -std::numeric_limits::infinity(); + float S = 0.0f; + std::vector vkq(static_cast(d_v), 0.0f); + for (int64_t j = jmin; j <= jmax; ++j) { + const int64_t blk = + fx.btab[static_cast(r * fx.max_blocks + j / block_size)]; + const int64_t off = j % block_size; + const int64_t kbase = + (blk * block_size + off) * fx.num_kv_heads * d + g * d; + float dot = 0.0f; + for (int64_t e = 0; e < d; ++e) { + const float kv = fx.f16_kv + ? vt::F16ToF32(fx.k_f16[static_cast(kbase + e)]) + : fx.k_f32[static_cast(kbase + e)]; + const float qv = + fx.f16_kv ? vt::F16ToF32(q_f16[static_cast(e)]) : q[e]; + dot += kv * qv; // NEON widened-lane scalar order + } + float s = dot * sc; + if (softcap != 0.0f) s = softcap * std::tanh(s); + const float Mold = M; + float ms = 1.0f, vs = 1.0f; + const int64_t vbase = + (blk * block_size + off) * fx.num_kv_heads * d_v + g * d_v; + if (s > M) { + M = s; + ms = std::exp(Mold - M); + for (int64_t e = 0; e < d_v; ++e) vkq[static_cast(e)] *= ms; + } else { + vs = std::exp(s - M); + } + for (int64_t e = 0; e < d_v; ++e) { + const float vv = fx.f16_kv + ? vt::F16ToF32(fx.v_f16[static_cast(vbase + e)]) + : fx.v_f32[static_cast(vbase + e)]; + vkq[static_cast(e)] += vv * vs; + } + S = S * ms + vs; + } + const float S_inv = S == 0.0f ? 0.0f : 1.0f / S; + float* o = &out[static_cast((t * fx.hq + h) * d_v)]; + for (int64_t e = 0; e < d_v; ++e) + o[e] = vkq[static_cast(e)] * S_inv; + } + } +} + +// The pre-arm default body over the paged walk, transcribed for the inertness +// pin: sequential f32 dot (f32-widened reads), two-pass softmax, normalized +// weighted V sum. Copied from cpu_paged_attn.cpp's scalar body order. +void TwoPassDefaultRef(const Fixture& fx, std::vector& out, float scale, + bool with_window, float softcap) { + const int64_t d = fx.d, d_v = fx.d_v, block_size = fx.block_size; + out.assign(static_cast(fx.total_q * fx.hq * d_v), 0.0f); + for (int64_t t = 0; t < fx.total_q; ++t) { + int64_t r = 0, p = 0; + FxResolve(fx, t, r, p); + int64_t jmin = 0, jmax = 0; + FxWindow(fx, with_window, p, jmin, jmax); + for (int64_t h = 0; h < fx.hq; ++h) { + const int64_t g = h / (fx.hq / fx.num_kv_heads); + const float* q = &fx.q_f32[static_cast((t * fx.hq + h) * d)]; + auto kel = [&](int64_t j, int64_t e) { + const int64_t blk = fx.btab[static_cast( + r * fx.max_blocks + j / block_size)]; + const int64_t off = j % block_size; + const int64_t base = + (blk * block_size + off) * fx.num_kv_heads * d + g * d; + return fx.f16_kv + ? vt::F16ToF32(fx.k_f16[static_cast(base + e)]) + : fx.k_f32[static_cast(base + e)]; + }; + auto vel = [&](int64_t j, int64_t e) { + const int64_t blk = fx.btab[static_cast( + r * fx.max_blocks + j / block_size)]; + const int64_t off = j % block_size; + const int64_t base = + (blk * block_size + off) * fx.num_kv_heads * d_v + g * d_v; + return fx.f16_kv + ? vt::F16ToF32(fx.v_f16[static_cast(base + e)]) + : fx.v_f32[static_cast(base + e)]; + }; + std::vector probs(static_cast(jmax - jmin + 1), 0.0f); + float m = -std::numeric_limits::infinity(); + for (int64_t j = jmin; j <= jmax; ++j) { + float dot = 0.0f; + for (int64_t e = 0; e < d; ++e) dot += q[e] * kel(j, e); + dot *= scale; + if (softcap > 0.0f) dot = softcap * std::tanh(dot / softcap); + probs[static_cast(j - jmin)] = dot; + if (dot > m) m = dot; + } + float denom = 0.0f; + for (int64_t j = jmin; j <= jmax; ++j) { + const float e = std::exp(probs[static_cast(j - jmin)] - m); + probs[static_cast(j - jmin)] = e; + denom += e; + } + const float inv = 1.0f / denom; + std::vector acc(static_cast(d_v), 0.0f); + for (int64_t j = jmin; j <= jmax; ++j) { + const float pw = probs[static_cast(j - jmin)] * inv; + for (int64_t e = 0; e < d_v; ++e) + acc[static_cast(e)] += pw * vel(j, e); + } + float* o = &out[static_cast((t * fx.hq + h) * d_v)]; + for (int64_t e = 0; e < d_v; ++e) o[e] = acc[static_cast(e)]; + } + } +} + +void RunCase(bool f16_kv, bool with_window, float softcap = 0.0f) { + Fixture fx = MakeFixture(f16_kv); + const float scale = 0.25f; // head_size^-0.5 for d=16 + + PagedAttentionArgs a_def = BaseArgs(scale, with_window); + a_def.logits_soft_cap = softcap; + RunK(fx, fx.out_def, a_def); + + PagedAttentionArgs a_arm = BaseArgs(scale, with_window); + a_arm.logits_soft_cap = softcap; + a_arm.ggml_flash_order = true; + RunK(fx, fx.out_arm, a_arm); + + GgmlFlashOrderRef(fx, fx.out_ref, scale, with_window, softcap); + + // 1. INERTNESS: default == pre-arm two-pass body, byte-for-byte. + std::vector two_pass; + TwoPassDefaultRef(fx, two_pass, scale, with_window, softcap); + CHECK(BytesEqual(fx.out_def, two_pass)); + + // 2. ARM: arm == ggml flash order, byte-for-byte. + CHECK(BytesEqual(fx.out_arm, fx.out_ref)); + + // 3. DISCRIMINATOR: on shapes where the orders diverge, arm != default. + // The F16 query rounding alone guarantees divergence on generic random + // data; assert it explicitly so a degenerate fixture can never smuggle an + // arm that equals the default. + CHECK_FALSE(BytesEqual(fx.out_arm, fx.out_def)); + CHECK(CountByteDiffs(fx.out_arm, fx.out_def) > 0); +} + +} // namespace + +TEST_CASE("paged attention ggml-flash-order arm: F16 KV, causal, multi-block") { + RunCase(/*f16_kv=*/true, /*with_window=*/false); +} + +TEST_CASE("paged attention ggml-flash-order arm: F32 KV") { + RunCase(/*f16_kv=*/false, /*with_window=*/false); +} + +TEST_CASE("paged attention ggml-flash-order arm: sliding window intersects") { + RunCase(/*f16_kv=*/true, /*with_window=*/true); +} + +TEST_CASE("paged attention ggml-flash-order arm: softcap folds per ggml") { + // ggml folds the softcap INTO the scale (scale /= cap at setup, then + // cap*tanhf(s), ops.cpp:8919-8925,8998-9000); vLLM's kernel form is + // cap*tanh(s/cap) AFTER scaling (cpu_paged_attn.cpp:440,498). The arm must + // mirror ggml's fold exactly — different multiply order, different bits on + // generic data. + RunCase(/*f16_kv=*/true, /*with_window=*/false, /*softcap=*/30.0f); +}