diff --git a/.agents/evidence/quant-q4k-seam-20261129/PROCESS.md b/.agents/evidence/quant-q4k-seam-20261129/PROCESS.md new file mode 100644 index 0000000000..87a19615e2 --- /dev/null +++ b/.agents/evidence/quant-q4k-seam-20261129/PROCESS.md @@ -0,0 +1,139 @@ +# QUANT-GGUF-CIQ-GEMM — q4k/q6k repack shared-seam unit (2026-11-29) + +Helper session `q4k-seam`, row QUANT-GGUF-CIQ-GEMM, worktree +/tmp/quant-q4k-seam from main ee9c3de77, branch +row/QUANT-GGUF-CIQ-GEMM-q4k-q6k-repack. Canonical issue +ISSUE-LOCAL-01M8M4B648PC33WK7K3ANACVVP (.agents/issues/QUANT-GGUF-CIQ-GEMM/). + +## Unit + +1. `vt::cpu::QuantRepackMatmul` gains the Q4_K and Q6_K repack twins: the + dotprod gemv (rows <= 3) and the i8mm 4-row GEMM (rows > 3, leftover rows + back on the gemv), transcribed verbatim from the pinned tap + /tmp/llamacpp-kolibri11-tap at 5f4d22289 (arch/arm/repack.cpp:781/:1570/ + :4015/:4984 NEON arms; the SVE arms are NOT transcribed — this host + exposes no SVE, /proc/cpuinfo, so the oracle binary dispatches the NEON + arms). The upstream kernels' fused `vfmaq_f32` scale folds are kept + verbatim (the bit-identity target here is the oracle kernel — a different + fp order from the vec_dot path), a recorded deviation from the Q8_0 arm's + non-fused vmla policy (file header, cpu_quant_repack_arm.cpp). +2. QuantizeRowQ8KFused (explicit std::fma == the oracle binary's + -ffp-contract=fast nearest_int) and QuantizeRowQ8K4x8Fused (verbatim + ggml_quantize_mat_q8_K_4x8 + fused nearest_int) — ADDITIVE arms; the + default BlockFromFloat table is untouched. +3. QuantRepackEligible/QuantRepackWeight extended to Q4_K/Q6_K (N%8==0, + K%256==0 — the pinned selection, repack.cpp:5011-5017/:5052-5059); the + portable make_block_{q4_K,q6_K}x8 interleave lives in cpu_quant_repack.cpp. + +## Bit-proof (tap build /tmp/llamacpp-kolibri11-32891-build at 5f4d22289) + +Fixture tests/fixtures/quant-q4k-q6k-repack-oracle-f32.bin (5,385,315 bytes, +sha256 2975aa85fd1be8192f7f8e4a90fac2d0f01dfd32727dbfdee44a11d9eb30132f) +generated by the scratch generator in this directory (compiled against the +tap libs), containing: +- the tap's quantize_row_q8_K bytes on the 5 kolibri11 live rows, +- the tap's ggml_quantize_mat_q8_K_4x8 bytes + input, +- the tap's REPACKED block bytes for Q4_K/Q6_K 512x2560 (weights synthesized + from a shared xorshift32 LCG — leg 3 doubles as the generator-drift + tripwire), +- 40 kernel cases: the 5 live-row Q4_K tensors at m=1 (gemv, live row) and + m=4 (gemm), plus Q4_K/Q6_K random shapes at m in {1,2,3,4,5,8} (m=5 = + 4-row gemm + gemv leftover, the oracle forward_mul_mat shape). + +RED/GREEN (test_quant_repack_kq_repack): +- GREEN: 393/393 assertions byte-for-byte (green-full-run.txt). Notably the + gemm legs pin OUR QuantizeRowQ8K4x8Fused + GemmQ{4,6}K8x8 against the + TAP's own quantize_mat + gemm pairing — the interleaved-q8_K bsums layout + question raised during transcription is settled empirically by these legs. +- The in-test discriminating controls: the default contract=off quantizer + must differ from the oracle on at least one live row (passes; some live + rows and all-random rows coincide, per the kolibri actcheck evidence), and + the plain vec_dot class must differ from the repacked outputs somewhere. + +## Mutations (each: bend, rebuild, run, restore byte-for-byte — backups kept) + +- M2 QuantizeRowQ8KFused magic constant +1.0f: 5 leg-1 memcmp reds + gemv + reds. First attempt +0.5f was a NO-OP (below the f32 ULP at 2^23) and + stayed green — recorded as a bad mutation (kolibri precedent). +- M3 GemmQ4K8x8 bias vmlsq->vmlaq: 14 failures, red. +- M4 GemvQ6K8x8 high-bits mask 0x30->0x20: 8 failures, red. First attempt + (mask_hi -> mask_lo) failed to COMPILE (-Werror unused variable) and left + a stale binary reporting a false green — recorded; the redo notes the + stale-binary hazard. +- M5 QuantizeRowQ8K4x8Fused bsums index <<2->>1: 15 failures, red. +- M6 reachability: Q4_K/Q6_K routing condition disabled in + QuantRepackMatmul: the seam entry throws ("weight must be a repacked q8_0 + tensor"), red. VT_CPU_QUANT_REPACK=portable skips the test coherently + (exit 77), which is inertness, not red. + +## Inertness (default config, this host) + +- ctest -R 'quant|repack': 28/28 pass (4 CUDA/ROCm skip coherently). +- ctest GGUF-model subset (kolibri/flint/gguf_load/inkling2): running at + the time of writing; result recorded below. + +## Consumers owed re-proofs (coordinator dispatches) + +- kolibri11-u3 (model-local twin 5838c608b) — may now switch to the shared + seam in its own follow-up; NOT rewired here. +- inkling2-w1 per-op table. +- qwen3_5_gguf_weights.cpp and muse_glimmer_gguf_weights.cpp: the only two + loaders calling QuantRepackEligible/QuantRepackWeight; their eligible + Q4_K/Q6_K weights now REPACK on i8mm hosts and take the oracle repacked + class (intended change; their keep-quant goldens and any byte-exact gates + need re-proof). +- MatmulBTQuantGrouped (cpu_quant_gemm.cpp) repacked slices for Q4_K/Q6_K + expert towers. +- Every other MatmulBTQuant / QuantTraits.from_float consumer (deepseek_v4, + flint, laguna, minimax_h3, glm5_next, qwen4_exp, CUDA/ROCm/Vulkan/TT + providers) is byte-unchanged by construction (additive arms; default + from_float table untouched) but is listed for the fresh reviewer's + mutation check. + +## Scope discipline + +Seam + tests only; no model rewiring; no push; no tolerance concepts +anywhere (byte-for-byte or nothing). Spec note: this unit ran under the +row's committed spec umbrella (gguf-compute-in-quant-gemm.md / the G7/G6 +repack tiers); a row-level spec addendum for the q4k/q6k arms is owed with +the row's next lifecycle change. + +## APPENDIX 2026-11-29 (later same day) — opt-in default + attribution + +First staged preflight surfaced three GGUF-model gate failures +(test_kolibri1_gguf logit band + hard flips, test_deepseek_v4_gguf_load +stacked-expert non-repacked contract, test_flint_paged_engine goldens). +Attribution: test_flint_paged_engine needs the untracked per-host +tests/vllm/models/flint_goldens_q4_k_m.json (absent from a fresh worktree); +test_kolibri1_gguf and test_deepseek_v4_gguf_load fail IDENTICALLY on the +clean baseline ee9c3de77 (baseline run in /tmp/quant-q4k-base-bld, same +signatures: 5x logit-band CHECKs + hard_flips; the deepseek_v4.cpp:631 +non-repacked contract throw) — pre-existing on this host, not caused by this +unit. + +Nevertheless the eligibility extension DID flip eligible k-quant weights to +the repacked class by default, which silently moves every Q4_K/Q6_K model's +outputs on an i8mm host before its consumers are re-proofed. Resolution: the +Q4_K/Q6_K arm of QuantRepackEligible is OPT-IN behind +VT_CPU_QUANT_REPACK_KQ=1 (default off = byte-identical to today); the seam +dispatch, kernels, fused quantizers and bit-proof legs are unchanged (the +bit-proof test sets the flag in-process). The coordinator flips the default +when the consumer re-proofs land (kolibri11-u3, inkling2-w1, +qwen3_5/muse_glimmer keep-quant goldens, deepseek_v4 stacked-expert +contract). + +## APPENDIX 2026-11-29 (preflight repair, coordinator-visible) + +- check-env-doc: the new knob is now documented as a behavior-changing + selection row in docs/ENVIRONMENT.md (VT_CPU_QUANT_REPACK_KQ, default off, + inertness guarantee stated in the row). +- test_check_test_registration -> test_every_fetch_content_site_is_pinned_off + (6 != 3): PRE-EXISTING/environmental, NOT the staged content. Root cause: + the gate counts `FetchContent_Declare` under the WORKTREE root (rglob + CMakeLists.txt/*.cmake, skipping only .git), so an in-tree build directory + (build/_deps/*-src) inflates the count. Verified: the identical unittest + passes on the clean shared checkout at ee9c3de77 (no build dir), fails in + this worktree only while build/ existed, and passes after the build moved + out-of-tree (/tmp/quant-q4k-seam-bld) with the same staged content. Routed + to the coordinator as a checker-environment hazard: a gate that rglobs the + worktree counts developer build artifacts as tree content. Not fixed here. diff --git a/.agents/evidence/quant-q4k-seam-20261129/inertness-model-tests.txt b/.agents/evidence/quant-q4k-seam-20261129/inertness-model-tests.txt new file mode 100644 index 0000000000..26ffcf2793 --- /dev/null +++ b/.agents/evidence/quant-q4k-seam-20261129/inertness-model-tests.txt @@ -0,0 +1,9 @@ +=== Inertness rerun with the OPT-IN default (VT_CPU_QUANT_REPACK_KQ unset): model-gate subset === + +Total Test time (real) = 268.41 sec + +The following tests FAILED: + 40 - test_kolibri1_gguf (Failed) + 214 - test_flint_paged_engine (Failed) + 235 - test_deepseek_v4_gguf_load (Failed) +Errors while running CTest diff --git a/.agents/evidence/quant-q4k-seam-20261129/mutation-m2-magicconst-red.txt b/.agents/evidence/quant-q4k-seam-20261129/mutation-m2-magicconst-red.txt new file mode 100644 index 0000000000..fee4770fd1 --- /dev/null +++ b/.agents/evidence/quant-q4k-seam-20261129/mutation-m2-magicconst-red.txt @@ -0,0 +1,13 @@ +=== MUTATION M2 (contract arm): magic constant 12582912.0f -> 12582913.0f in QuantizeRowQ8KFused === +NOTE: a first attempt with +0.5f was a NO-OP mutation (below the f32 ULP at 2^23) and stayed green; recorded as a bad mutation, then repeated with +1.0f per the kolibri precedent. +./tests/vt/test_quant_repack_kq_repack.cpp:245: ERROR: CHECK( std::memcmp(fused.data(), tap.data(), tap.size()) == 0 ) is NOT correct! +./tests/vt/test_quant_repack_kq_repack.cpp:245: ERROR: CHECK( std::memcmp(fused.data(), tap.data(), tap.size()) == 0 ) is NOT correct! +./tests/vt/test_quant_repack_kq_repack.cpp:245: ERROR: CHECK( std::memcmp(fused.data(), tap.data(), tap.size()) == 0 ) is NOT correct! +./tests/vt/test_quant_repack_kq_repack.cpp:245: ERROR: CHECK( std::memcmp(fused.data(), tap.data(), tap.size()) == 0 ) is NOT correct! +./tests/vt/test_quant_repack_kq_repack.cpp:245: ERROR: CHECK( std::memcmp(fused.data(), tap.data(), tap.size()) == 0 ) is NOT correct! +./tests/vt/test_quant_repack_kq_repack.cpp:356: ERROR: CHECK( mismatches == 0 ) is NOT correct! +./tests/vt/test_quant_repack_kq_repack.cpp:356: ERROR: CHECK( mismatches == 0 ) is NOT correct! +./tests/vt/test_quant_repack_kq_repack.cpp:356: ERROR: CHECK( mismatches == 0 ) is NOT correct! +./tests/vt/test_quant_repack_kq_repack.cpp:356: ERROR: CHECK( mismatches == 0 ) is NOT correct! +./tests/vt/test_quant_repack_kq_repack.cpp:356: ERROR: CHECK( mismatches == 0 ) is NOT correct! +[doctest] Status: SUCCESS! diff --git a/.agents/evidence/quant-q4k-seam-20261129/mutation-m3-q4kgemm-bias-red.txt b/.agents/evidence/quant-q4k-seam-20261129/mutation-m3-q4kgemm-bias-red.txt new file mode 100644 index 0000000000..5c68b1136e --- /dev/null +++ b/.agents/evidence/quant-q4k-seam-20261129/mutation-m3-q4kgemm-bias-red.txt @@ -0,0 +1,4 @@ +=== MUTATION M3 (Q4_K i8mm gemm): dmins scale applied with + instead of the vmlsq bias-subtract (bias term bent) === +[doctest] assertions: 393 | 379 passed | 14 failed | +[doctest] Status: FAILURE! +[doctest] Status: SUCCESS! diff --git a/.agents/evidence/quant-q4k-seam-20261129/mutation-m4-q6kgemv-mask-red.txt b/.agents/evidence/quant-q4k-seam-20261129/mutation-m4-q6kgemv-mask-red.txt new file mode 100644 index 0000000000..54944416ca --- /dev/null +++ b/.agents/evidence/quant-q4k-seam-20261129/mutation-m4-q6kgemv-mask-red.txt @@ -0,0 +1,5 @@ +=== MUTATION M4 (Q6_K gemv): high-2-bits extraction mask 0x30 -> 0x20 (bent) === +NOTE: a first attempt replacing mask_hi with mask_lo failed to COMPILE (unused variable, -Werror) and left a stale binary that reported a false green; recorded, then repeated with a compiling value bend. +[doctest] assertions: 393 | 385 passed | 8 failed | +[doctest] Status: FAILURE! +[doctest] Status: SUCCESS! diff --git a/.agents/evidence/quant-q4k-seam-20261129/mutation-m5-bsums-index-red.txt b/.agents/evidence/quant-q4k-seam-20261129/mutation-m5-bsums-index-red.txt new file mode 100644 index 0000000000..3f20c2c82a --- /dev/null +++ b/.agents/evidence/quant-q4k-seam-20261129/mutation-m5-bsums-index-red.txt @@ -0,0 +1,4 @@ +=== MUTATION M5 (4x8 mat quantizer): bsums index formula bent === +[doctest] assertions: 393 | 378 passed | 15 failed | +[doctest] Status: FAILURE! +[doctest] Status: SUCCESS! diff --git a/.agents/evidence/quant-q4k-seam-20261129/mutation-m6-routing-red.txt b/.agents/evidence/quant-q4k-seam-20261129/mutation-m6-routing-red.txt new file mode 100644 index 0000000000..0e6d2f7614 --- /dev/null +++ b/.agents/evidence/quant-q4k-seam-20261129/mutation-m6-routing-red.txt @@ -0,0 +1,6 @@ +=== MUTATION M6 (reachability): Q4_K/Q6_K routing condition disabled — arms unreachable from the seam entry === +[3/3] Linking CXX executable tests/test_quant_repack_kq_repack +./tests/vt/test_quant_repack_kq_repack.cpp:167: ERROR: test case THREW exception: vt: quant_repack_matmul: weight must be a repacked q8_0 tensor at ./src/vt/cpu/cpu_quant_repack_arm.cpp:1093 +[doctest] assertions: 111 | 111 passed | 0 failed | +[doctest] Status: FAILURE! +[doctest] Status: SUCCESS! diff --git a/.agents/issues/QUANT-GGUF-CIQ-GEMM/ISSUE-LOCAL-01M8M4B648PC33WK7K3ANACVVP.md b/.agents/issues/QUANT-GGUF-CIQ-GEMM/ISSUE-LOCAL-01M8M4B648PC33WK7K3ANACVVP.md new file mode 100644 index 0000000000..b66b7400cc --- /dev/null +++ b/.agents/issues/QUANT-GGUF-CIQ-GEMM/ISSUE-LOCAL-01M8M4B648PC33WK7K3ANACVVP.md @@ -0,0 +1,19 @@ +ID: ISSUE-LOCAL-01M8M4B648PC33WK7K3ANACVVP +Title: Q4_K/Q6_K repack matmul arms absent from QuantRepackMatmul; QuantizeRowQ8_K contract=off bytes diverge from oracle +Row: QUANT-GGUF-CIQ-GEMM +State: OPEN +Kind: bug +GitHub: - +Mirror: PENDING +Availability: FULL +Created: 2026-11-29 +Updated: 2026-11-29 +Closed: - + +## Problem + +The serving oracle (llama.cpp 5f4d22289, NEON+i8mm host) computes every Q4_K and Q6_K matmul with ne[1]%8==0 through REPACKED kernels: rows<=3 -> ggml_gemv_q4_K_8x8_q8_K / ggml_gemv_q6_K_8x8_q8_K, rows>3 -> the i8mm ggml_gemm arm (repack.cpp:5011-5017/:5052-5059). The shared seam vt::cpu::QuantRepackMatmul is Q8_0-only, so every consumer (e.g. kolibri11-u3) must transcribe kernels model-locally; the kolibri lane's comparator (docs/bench-evidence/kolibri11-u3-oracle-20261125/repack-gemv-comparator-20261129.txt) proves repack-vs-oracle max=0 bit-exact while our vec_dot path differs up to 3.5e-3 relRMS on blk.4.attn_output. Separately, the oracle binary compiles quantize_row_q8_K_ref under -ffp-contract=fast so nearest_int's magic add fuses into one vfma; our contract=off build differs at 1-ULP ties (measured 396/7008 activation bytes on a live row, 0/7008 random). Evidence: /tmp/kolibri11-u3/PROCESS.md (2026-11-29 entries), tap tree /tmp/llamacpp-kolibri11-tap at 5f4d22289. + +## Resolution + +- diff --git a/docs/ENVIRONMENT.md b/docs/ENVIRONMENT.md index e47bd4193b..0e2d36414d 100644 --- a/docs/ENVIRONMENT.md +++ b/docs/ENVIRONMENT.md @@ -327,6 +327,7 @@ portable/reference path. In normal operation leave them unset. | `VT_CPU_PAGED_ATTN_SCALAR_FMA` | off | Set `1` to run the draft FMA-contracted scalar body of the CPU paged attention (4-lane pairwise K dot, fused V accumulate) instead of the default pre-batch sequential order (`src/vt/cpu/cpu_paged_attn.cpp`). NOT bit-identical to the default — the summation order changes — so it is a measurement arm only: the local bisect for row FIX-PAGED-REGRESSION (docs/bench-evidence/fix-paged-regression-20261028/) named the 2cd6b8a14 contraction as the first bad commit behind the dtype bit-identity and glm4 goldens regressions, and the default was restored to the pre-batch order. The PERF-CPU-ATTN-NEON sweep and the kolibri1 W3 gate pin `=1` for the cases that measure this arm | | `VT_CPU_QUANT_MMLA` | `auto` | Select the Arm i8mm quant-dot tier. `portable` (also `0`/`off`/`false`) disables it; `i8mm` (also `1`/`on`/`true`) forces it and fails closed unless Linux `HWCAP2_I8MM` or Darwin `hw.optional.arm.FEAT_I8MM` is present | | `VT_CPU_QUANT_REPACK` | `auto` | Select the Arm i8mm+DotProd Q8_0 repack tier. `portable` (also `0`/`off`/`false`) disables it; `i8mm` (also `1`/`on`/`true`) forces it and fails closed unless the exact Linux HWCAP/HWCAP2 or Darwin sysctl capabilities are present | +| `VT_CPU_QUANT_REPACK_KQ` | off | Set `1` to extend the repack-at-load eligibility to Q4_K and Q6_K weights (N%8==0, K%256==0 — the pinned oracle's selection, llama.cpp 5f4d22289 repack.cpp:5011-5017/:5052-5059): the loader then repacks them into the block_q4_Kx8/block_q6_Kx8 interleave and `kMatmulBTQuant` computes them through the oracle's repacked gemv (rows<=3) / i8mm gemm (rows>3) kernels — a DIFFERENT fp order from the vec_dot path, so outputs move to the oracle's bytes. Default OFF is byte-identical to the plain path for every model; flip it only after the consumers of those weights are re-proofed (kolibri11-u3, inkling2-w1, the qwen3_5/muse_glimmer keep-quant goldens, the deepseek_v4 stacked-expert non-repacked contract). Bit-proof: `test_quant_repack_kq_repack` (393/393 byte-exact vs the tap build; evidence `.agents/evidence/quant-q4k-seam-20261129/`) | | `VT_DFLASH_DRAFT` | off | The DFlash2-classified draft proposes through the bundle's DIRECT-ARGMAX arm (`dflash2.py` `has_selector == false`): full-vocab argmax per block row over the block forward, the candidate selector and its codebooks never resident (~254 MB freed), and the `RefuseDflash1ArgmaxOnDflash2Block` guard bypassed as the operator's explicit choice. The verify stays lossless (greedy accept = the target's argmax), so the emitted tokens are unchanged and only acceptance/TPOT can move. Default OFF keeps the selector lane byte-identical (QWEN38-DFLASH2-STAGE-C W3) | | `VT_DFLASH_CTX_MAX_TOKENS` | unset (the resolved cap is `max_model_len + 1 + k`, itself capped at an 8 GiB budget shared across `--max-num-seqs`, so `8 GiB / max_num_seqs` per request) | Caps the DFlash/DFlash2/DSpark draft's CONTEXT STORE in tokens, PER REQUEST. The store is a per-request, per-draft-layer bf16 pool holding K and V, so its size is `tokens x num_draft_layers x num_kv_heads x head_dim x 2 x 2` bytes per concurrent request, and the runner builds ONE PER BATCH ROW — so what the device holds is that number times `--max-num-seqs`, and `gpu_memory_utilization` accounts NONE of it. The default budget is therefore the AGGREGATE rather than a per-request allowance: a 262144-token `--max-model-len` would ask for about a gigabyte per request, and unbounded device residency has OOM-rebooted a box here ([#1647](https://github.com/mudler/vllm.cpp/issues/1647)). Set this BELOW the advertised context to bound that memory, or ABOVE the default share to speculate further into a long context — the aggregate arithmetic (`tokens x bytes_per_token x max_num_seqs`) is then yours. The effective limit AND the aggregate it costs are announced at startup either way. A request whose context passes the limit keeps running WITHOUT speculation, on the target alone — never refused, and never fatal: before [#1919](https://github.com/mudler/vllm.cpp/issues/1919) the store was a fixed 4096 slots unrelated to `--max-model-len`, and the first prompt above it threw from inside an EngineCore step and left the server answering `[request submitted to a stopped AsyncLLM]` for every later request. Mirrors upstream, whose draft context lives in the engine's own paged KV cache sized `cdiv(max_model_len, block_size)` and whose speculators emit an EMPTY draft where they cannot serve a request | | `VT_DFLASH_PAGED` | on (CUDA, DFlash spec-decode) | The materialized `[context;block]` draft forward instead of the fixed-capacity paged draft-KV store read through `vt::DFlashPagedBlockAttention` (bit-identical; only the DFlash single-request propose path) | diff --git a/docs/bench-evidence/quant-q4k-seam-20261129/fixture.sha256 b/docs/bench-evidence/quant-q4k-seam-20261129/fixture.sha256 new file mode 100644 index 0000000000..cc2c5395f1 --- /dev/null +++ b/docs/bench-evidence/quant-q4k-seam-20261129/fixture.sha256 @@ -0,0 +1 @@ +2975aa85fd1be8192f7f8e4a90fac2d0f01dfd32727dbfdee44a11d9eb30132f tests/fixtures/quant-q4k-q6k-repack-oracle-f32.bin diff --git a/docs/bench-evidence/quant-q4k-seam-20261129/gen_fixture.cpp b/docs/bench-evidence/quant-q4k-seam-20261129/gen_fixture.cpp new file mode 100644 index 0000000000..7f75ccc2b9 --- /dev/null +++ b/docs/bench-evidence/quant-q4k-seam-20261129/gen_fixture.cpp @@ -0,0 +1,392 @@ +// QUANT-GGUF-CIQ-GEMM q4k/q6k repack seam — fixture GENERATOR (scratch, runs +// OUTSIDE the tree against the tap build at llama.cpp 5f4d22289 +// (/tmp/llamacpp-kolibri11-32891-build/bin)). Not compiled by the project; the +// generator writes tests/fixtures/quant-q4k-q6k-repack-oracle-f32.bin (+.idx) +// that the in-tree test test_quant_repack_kq_repack consumes. +// +// Per case: TAP repack + TAP ggml_gemv/gemm_{q4_K,q6_K}_8x8_q8_K outputs. +// Weights are synthesized from a shared xorshift32 LCG (identical code lives in +// the in-tree test) so the fixture need not embed weight bytes, except the two +// small REPACKED-weight pin cases which store the tap's repacked bytes +// verbatim. The live kolibri11 rows come from +// tests/fixtures/kolibri11-q4k-gemv-oracle-f32.bin (the U3 lane's captures). +#include "ggml.h" +#include "ggml-backend.h" +#include "ggml-backend-impl.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +extern "C" { +void ggml_gemv_q4_K_8x8_q8_K(int n, float* s, size_t bs, const void* vx, + const void* vy, int nr, int nc); +void ggml_gemv_q6_K_8x8_q8_K(int n, float* s, size_t bs, const void* vx, + const void* vy, int nr, int nc); +void ggml_gemm_q4_K_8x8_q8_K(int n, float* s, size_t bs, const void* vx, + const void* vy, int nr, int nc); +void ggml_gemm_q6_K_8x8_q8_K(int n, float* s, size_t bs, const void* vx, + const void* vy, int nr, int nc); +void quantize_row_q8_K(const float* src, void* dst, int64_t n); +void ggml_quantize_mat_q8_K_4x8(const float* x, void* vy, int64_t k); +} + +ggml_backend_buffer_type_t ggml_backend_cpu_repack_buffer_type(); + +namespace { + +constexpr uint32_t kQK_K = 256; + +// The shared deterministic weight synthesizer. xorshift32; identical body in +// the in-tree test. Row-block bytes: scales/delta bytes and quant bytes are +// drawn from the LCG stream in a fixed order, so both sides agree byte-for-byte +// without embedding weights in the fixture. +struct Lcg { + uint32_t s; + explicit Lcg(uint32_t seed) : s(seed) {} + uint32_t next() { + uint32_t x = s; + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + s = x; + return x; + } + uint8_t byte() { return static_cast(next() >> 24); } + void fill(uint8_t* p, size_t n) { + for (size_t i = 0; i < n; ++i) p[i] = byte(); + } +}; + +// f16 with a random 16-bit pattern (any bits decode to a finite/infinite f16; +// kernels only multiply — keep patterns in the normal range by masking the +// exponent to < 0x7800 to avoid NaN x NaN polluting a bit-exactness check). +uint16_t rand_f16(Lcg& lcg) { + uint16_t bits = static_cast(lcg.next() >> 16); + bits &= 0x83FF; // keep exponent small, allow sign + mantissa noise + return bits; +} + +struct Case { + std::string name; + int gtype; // 12 = Q4_K, 14 = Q6_K + int64_t n, k, m; + bool live_row; // x row 0 taken from the kolibri fixture + int64_t live_k, live_n; + std::vector x_live; +}; + +std::vector LoadKolibriFixture(const std::string& fpath) { + std::ifstream in(fpath, std::ios::binary); + if (!in.good()) return {}; + char hdr[11]; + in.read(hdr, 11); + if (std::memcmp(hdr, "VTU3Q4KFIX1", 11) != 0) return {}; + std::ifstream idx_in(fpath + ".idx"); + std::vector> index; + std::string line; + while (std::getline(idx_in, line)) { + if (line.empty()) continue; + const auto sp = line.rfind(' '); + index.push_back({line.substr(0, sp), + static_cast(std::atoi(line.c_str() + sp + 1))}); + } + std::vector cases; + for (const auto& e : index) { + const auto bar = e.first.find('|'); + // first record of each tag only (c == 0); the idx field is the byte + // offset of the entry's FIRST record. + Case cs; + cs.name = e.first.substr(0, bar); + int64_t kk = 0, nn = 0; + in.read(reinterpret_cast(&kk), 8); + in.read(reinterpret_cast(&nn), 8); + cs.live_k = kk; + cs.live_n = nn; + cs.x_live.resize(static_cast(kk)); + in.read(reinterpret_cast(cs.x_live.data()), + static_cast(kk) * 4); + std::vector y(nn); + in.read(reinterpret_cast(y.data()), + static_cast(nn) * 4); + (void)y; + cases.push_back(std::move(cs)); + // skip the remaining (count - 1) seeded-random records of this entry + const uint64_t rec_bytes = 16 + static_cast(kk + nn) * 4; + in.seekg(static_cast(static_cast(e.second - 1) * rec_bytes), + std::ios::cur); + } + return cases; +} + +size_t PlainRowBytes(int gtype, int64_t k) { + const int64_t nb = k / static_cast(kQK_K); + return gtype == 12 ? static_cast(nb) * 144 : static_cast(nb) * 210; +} + +void SynthWeight(int gtype, int64_t n, int64_t k, uint32_t seed, + std::vector& w) { + w.resize(PlainRowBytes(gtype, k) * static_cast(n)); + Lcg lcg(seed); + const int64_t nb = k / static_cast(kQK_K); + size_t off = 0; + for (int64_t r = 0; r < n; ++r) { + for (int64_t b = 0; b < nb; ++b) { + if (gtype == 12) { // BlockQ4_K: d, dmin, scales[12], qs[128] + *reinterpret_cast(w.data() + off) = rand_f16(lcg); + off += 2; + *reinterpret_cast(w.data() + off) = rand_f16(lcg); + off += 2; + lcg.fill(w.data() + off, 12); + off += 12; + lcg.fill(w.data() + off, 128); + off += 128; + } else { // BlockQ6_K: ql[128], qh[64], scales[16] (int8), d + lcg.fill(w.data() + off, 128); + off += 128; + lcg.fill(w.data() + off, 64); + off += 64; + lcg.fill(w.data() + off, 16); + off += 16; + *reinterpret_cast(w.data() + off) = rand_f16(lcg); + off += 2; + } + } + } +} + +struct Writer { + std::ofstream out; + std::ofstream idx; + int64_t pos = 0; + void Open(const std::string& base) { + out.open(base, std::ios::binary); + idx.open(base + ".idx"); + out.write("VTQ4K6KREP1", 11); + pos = 11; + } + void Case(const std::string& name, int64_t n, int64_t k, int64_t m) { + + out.write(reinterpret_cast(&k), 8); + out.write(reinterpret_cast(&n), 8); + out.write(reinterpret_cast(&m), 8); + const int64_t bytes = 24 + static_cast((k + n) * m) * 4; + idx << name << " " << pos << " " << bytes << "\n"; + pos += bytes; + } + void Extra(const std::string& name, int64_t bytes) { + idx << name << " " << pos << " " << bytes << "\n"; + pos += bytes; + } + void F32(const std::vector& v) { + out.write(reinterpret_cast(v.data()), + static_cast(v.size()) * 4); + } + void Bytes(const void* p, size_t n) { + out.write(reinterpret_cast(p), static_cast(n)); + } +}; + +void RunCase(Writer& w, const Case& cs) { + const int64_t nb = cs.k / static_cast(kQK_K); + const int64_t act_row = 4 * nb + cs.k + (cs.k / 16) * 2; // BlockQ8_K x nb + std::vector plain; + SynthWeight(cs.gtype, cs.n, cs.k, 0x1234567u + (cs.gtype == 12 ? 11u : 29u), + plain); + + // TAP repack through the repack buffer type (same method as gemv_compare). + ggml_init_params gp{512 * 1024 * 1024, nullptr, true}; + ggml_context* ctx = ggml_init(gp); + ggml_tensor* gt = ggml_new_tensor_2d( + ctx, cs.gtype == 12 ? GGML_TYPE_Q4_K : GGML_TYPE_Q6_K, cs.k, cs.n); + ggml_backend_buffer_type_t buft = ggml_backend_cpu_repack_buffer_type(); + const size_t nbytes = PlainRowBytes(cs.gtype, cs.k) * static_cast(cs.n); + ggml_backend_buffer_t buf = ggml_backend_buft_alloc_buffer(buft, nbytes); + gt->buffer = buf; + gt->data = ggml_backend_buffer_get_base(buf); + buf->iface.init_tensor(buf, gt); + buf->iface.set_tensor(buf, gt, plain.data(), 0, nbytes); + + // activations: m rows; row 0 = the live row when requested (length must + // equal k), the rest seeded random. + std::vector x(static_cast(cs.m) * cs.k); + Lcg lx(0x9E3779B9u + static_cast(cs.k)); + for (size_t i = 0; i < x.size(); ++i) x[i] = static_cast(static_cast(lx.next() >> 8)) / 8388608.0f - 1.0f; + if (cs.live_row && cs.live_k == cs.k) { + std::memcpy(x.data(), cs.x_live.data(), static_cast(cs.k) * 4); + } + + std::vector y(static_cast(cs.m) * cs.n, 0.0f); + const bool q4k = cs.gtype == 12; + // Full 4-row groups through the i8mm gemm (m > 3); leftover rows through the + // gemv — the oracle's forward_mul_mat shape. + if (cs.m > 3) { + const int64_t groups = cs.m / 4; + const size_t q8k4 = static_cast(nb) * (16 + 4 * kQK_K + (kQK_K / 4) * 2); + std::vector actm(groups * q8k4); + for (int64_t g = 0; g < groups; ++g) { + ggml_quantize_mat_q8_K_4x8(x.data() + static_cast(g) * 4 * cs.k, + actm.data() + static_cast(g) * q8k4, + cs.k); + } + for (int64_t g = 0; g < groups; ++g) { + if (q4k) ggml_gemm_q4_K_8x8_q8_K(static_cast(cs.k), y.data() + static_cast(g) * 4 * cs.n, cs.n, gt->data, actm.data() + static_cast(g) * q8k4, 4, static_cast(cs.n)); + else ggml_gemm_q6_K_8x8_q8_K(static_cast(cs.k), y.data() + static_cast(g) * 4 * cs.n, cs.n, gt->data, actm.data() + static_cast(g) * q8k4, 4, static_cast(cs.n)); + } + for (int64_t i = groups * 4; i < cs.m; ++i) { + std::vector act(static_cast(act_row)); + quantize_row_q8_K(x.data() + static_cast(i) * cs.k, act.data(), cs.k); + if (q4k) ggml_gemv_q4_K_8x8_q8_K(static_cast(cs.k), y.data() + static_cast(i) * cs.n, cs.n, gt->data, act.data(), 1, static_cast(cs.n)); + else ggml_gemv_q6_K_8x8_q8_K(static_cast(cs.k), y.data() + static_cast(i) * cs.n, cs.n, gt->data, act.data(), 1, static_cast(cs.n)); + } + } else { + for (int64_t i = 0; i < cs.m; ++i) { + std::vector act(static_cast(act_row)); + quantize_row_q8_K(x.data() + static_cast(i) * cs.k, act.data(), cs.k); + if (q4k) ggml_gemv_q4_K_8x8_q8_K(static_cast(cs.k), y.data() + static_cast(i) * cs.n, cs.n, gt->data, act.data(), 1, static_cast(cs.n)); + else ggml_gemv_q6_K_8x8_q8_K(static_cast(cs.k), y.data() + static_cast(i) * cs.n, cs.n, gt->data, act.data(), 1, static_cast(cs.n)); + } + } + + w.Case(cs.name + "|g" + std::to_string(cs.gtype) + "|n" + std::to_string(cs.n) + + "|k" + std::to_string(cs.k) + "|m" + std::to_string(cs.m), + cs.n, cs.k, cs.m); + w.F32(x); + w.F32(y); + ggml_backend_buffer_free(buf); + ggml_free(ctx); +} + +} // namespace + +int main(int argc, char** argv) { + if (argc < 3) { + std::fprintf(stderr, "usage: %s \n", argv[0]); + return 2; + } + Writer w; + w.Open(argv[2]); + + // 1. The tap's own q8_K quantizer bytes on the live rows: pins + // QuantizeRowQ8KFused (the oracle-binary contract arm). + auto kf = LoadKolibriFixture(argv[1]); + std::fprintf(stderr, "kolibri cases: %zu\n", kf.size()); for (auto& c : kf) std::fprintf(stderr, " %s k=%" PRIi64 " n=%" PRIi64 "\n", c.name.c_str(), c.live_k, c.live_n); + for (const auto& cs : kf) { + if (cs.live_k % 256 != 0 || cs.live_k == 0) continue; + std::vector q8(static_cast(4 * (cs.live_k / 256) + cs.live_k + (cs.live_k / 16) * 2)); + quantize_row_q8_K(cs.x_live.data(), q8.data(), cs.live_k); + w.Extra("q8k|" + cs.name, static_cast(q8.size())); + w.Bytes(q8.data(), q8.size()); + } + // ... and the 4x8 mat quantizer on four seeded rows. + { + const int64_t k = 2560; + std::vector x(4 * k); + Lcg lcg(0xC0FFEEu); + for (size_t i = 0; i < x.size(); ++i) x[i] = static_cast(lcg.next()) / 2137483648.0f - 1.0f; + std::vector q8m((k / 256) * (16 + 4 * kQK_K + (kQK_K / 4) * 2)); + ggml_quantize_mat_q8_K_4x8(x.data(), q8m.data(), k); + w.Extra("q8k4x8|k2560", static_cast(q8m.size())); + w.Bytes(q8m.data(), q8m.size()); + w.Extra("q8k4x8|x", static_cast(x.size()) * 4); + w.Bytes(x.data(), x.size() * 4); + } + + // 2. The tap's REPACKED weight bytes for one small shape per type: pins + // QuantRepackWeight byte-for-byte. + for (int g : {12, 14}) { + const int64_t n = 512, k = 2560; + std::vector plain; + SynthWeight(g, n, k, g == 12 ? 0x4B455931u : 0x4B455932u, plain); + ggml_init_params gp{512 * 1024 * 1024, nullptr, true}; + ggml_context* ctx = ggml_init(gp); + ggml_tensor* gt = ggml_new_tensor_2d( + ctx, g == 12 ? GGML_TYPE_Q4_K : GGML_TYPE_Q6_K, k, n); + ggml_backend_buffer_type_t buft = ggml_backend_cpu_repack_buffer_type(); + const size_t nbytes = PlainRowBytes(g, k) * static_cast(n); + ggml_backend_buffer_t buf = ggml_backend_buft_alloc_buffer(buft, nbytes); + gt->buffer = buf; + gt->data = ggml_backend_buffer_get_base(buf); + buf->iface.init_tensor(buf, gt); + buf->iface.set_tensor(buf, gt, plain.data(), 0, nbytes); + const std::string name = std::string("repk|g") + std::to_string(g); + w.Extra(name + "|plain", static_cast(nbytes)); + w.Bytes(plain.data(), nbytes); + w.Extra(name + "|repacked", static_cast(nbytes)); + w.Bytes(gt->data, nbytes); + ggml_backend_buffer_free(buf); + ggml_free(ctx); + } + + // 3. Kernel output cases. Live-row Q4_K cases from the kolibri fixture at + // m=1 (gemv) and m=4 (gemm); random Q4_K/Q6_K at m in {1,2,3,4,5,8}. + for (const auto& cs : kf) { + if (cs.live_n % 8 != 0 || cs.live_k % 256 != 0) continue; + for (int64_t m : {1, 4}) { + Case c = cs; + c.gtype = 12; // kolibri fixture cases are all Q4_K tensors + c.k = cs.live_k; + c.n = cs.live_n; + c.m = m; + c.live_row = (m == 1); + std::fprintf(stderr, "case %s m=%" PRIi64 "\n", cs.name.c_str(), m); RunCase(w, c); + } + } + struct RS { int g; int64_t n, k; }; + const RS rnd[] = {{12, 512, 2560}, {12, 256, 512}, {14, 512, 2560}, + {14, 128, 512}, {12, 1024, 2048}}; + for (const auto& r : rnd) { + for (int64_t m : {1, 2, 3, 4, 5, 8}) { + std::fprintf(stderr, "rnd case g=%d n=%" PRIi64 " k=%" PRIi64 " m=%" PRIi64 "\n", r.g, r.n, r.k, m); + Case c; + c.name = "rnd"; + c.gtype = r.g; + c.n = r.n; + c.k = r.k; + c.m = m; + c.live_row = false; + std::fprintf(stderr, "case %s m=%" PRIi64 "\n", c.name.c_str(), m); RunCase(w, c); + } + } + // Self-verification: reopen and check every kernel-case header sits where + // the idx claims. + { + std::ifstream in(argv[2], std::ios::binary); + w.out.flush(); + w.idx.flush(); + std::ifstream idx_in(std::string(argv[2]) + ".idx"); + std::string line; + int checked = 0, lines = 0; + while (std::getline(idx_in, line)) { + ++lines; + const auto sp1 = line.find(' '); + const auto sp2 = line.rfind(' '); + const uint64_t off = std::strtoull(line.c_str() + sp1 + 1, nullptr, 10); + const std::string name = line.substr(0, sp1); + if (name.rfind("|m", 0) == std::string::npos && name.find("|g") == std::string::npos) continue; + in.seekg(static_cast(off)); + int64_t kk = 0, nn = 0, mm = 0; + in.read(reinterpret_cast(&kk), 8); + in.read(reinterpret_cast(&nn), 8); + in.read(reinterpret_cast(&mm), 8); + // name carries |k|m suffixes + size_t p = name.find("|k"), q = name.find("|m"); + if (p == std::string::npos || q == std::string::npos) continue; + const int64_t ek = std::atoll(name.c_str() + p + 2); + const int64_t em = std::atoll(name.c_str() + q + 2); + if (kk != ek || mm != em) { + std::fprintf(stderr, "MISMATCH %s: hdr(%" PRIi64 ",%" PRIi64 ",%" PRIi64 ") want k=%" PRIi64 " m=%" PRIi64 "\n", name.c_str(), kk, nn, mm, ek, em); + return 3; + } + ++checked; + } + std::fprintf(stderr, "self-check ok: %d case headers (lines seen %d)\n", checked, lines); + } + std::printf("wrote %s (%" PRIi64 " bytes)\n", argv[2], w.pos); + return 0; +} diff --git a/docs/bench-evidence/quant-q4k-seam-20261129/green-full-run.txt b/docs/bench-evidence/quant-q4k-seam-20261129/green-full-run.txt new file mode 100644 index 0000000000..b530936cd0 --- /dev/null +++ b/docs/bench-evidence/quant-q4k-seam-20261129/green-full-run.txt @@ -0,0 +1,6 @@ +[doctest] doctest version is "2.5.2" +[doctest] run with "--help" for options +=============================================================================== +[doctest] test cases: 1 | 1 passed | 0 failed | 0 skipped +[doctest] assertions: 393 | 393 passed | 0 failed | +[doctest] Status: SUCCESS! diff --git a/docs/bench-evidence/quant-q4k-seam-20261129/preflight-staged-final.log b/docs/bench-evidence/quant-q4k-seam-20261129/preflight-staged-final.log new file mode 100644 index 0000000000..e2c41ecc49 --- /dev/null +++ b/docs/bench-evidence/quant-q4k-seam-20261129/preflight-staged-final.log @@ -0,0 +1,297 @@ +Session role: + ok role=helper row=QUANT-GGUF-CIQ-GEMM session=ppid:91340 branch=row/QUANT-GGUF-CIQ-GEMM-q4k-q6k-repack +Record gates: + ok check-conflict-markers + ok check-evidence-refs + ok check-evidence-pin-sha + ok check-doc-sha-pins + ok check-prompt-contract + ok check-agent-record + ok check-release-binary-contract + ok check-release-workflow + ok check-windows-release-state + ok check-container-matrix + ok check-container-workflow + ok check-build-runtime-deps + ok check-lease-ccache + ok claim-view + ok check-readme-structure + ok check-quickstart-recipes + ok check-benchmark-index + ok check-model-checklist + ok check-supported-models + ok check-env-doc + ok check-fusion-consistency + ok check-attention-rung-consistency + ok check-fp4-resident-consistency + ok check-cuda-op-arch-gate + ok check-rocm-dp4a-intrinsic + ok check-runner-routing-consistency + ok check-surface-coverage + ok check-test-registration + ok check-snapshot-pins + ok check-oracle-pins + ok check-comparator-pins + ok check-oracle-denominator-flags + ok check-now-current + ok check-gate-commands + ok check-symbol-anchors + ok ready-for-helper + ok upstream-inventory + ok audit-live-rows +Mutation suites: + ok test_check_prompt_contract + ok test_check_evidence_refs + ok test_check_evidence_pin_sha + ok test_check_doc_sha_pins + ok test_agent_gates + ok test_agent_record + ok test_check_release_binary_contract + ok test_release_manifest + ok test_release_archive + ok test_release_pipeline + ok test_check_windows_release_state + ok test_release_postpublish_audit + ok test_check_container_matrix + ok test_check_container_workflow + ok test_check_build_runtime_deps + ok test_check_lease_ccache + ok test_validate_container_image + ok test_release_index + ok test_release_metadata + ok test_release_accelerator_metadata + ok test_release_macos_metadata + ok test_release_windows_metadata + ok test_cpu_release_gates + ok test_agent_role + ok test_agent_onboard + ok test_agent_start + ok test_gate_bringup + ok test_env_agnostic_tooling + ok test_claim_view + ok test_upstream_inventory + ok test_check_readme_structure + ok test_check_quickstart_recipes + ok test_check_benchmark_index + ok test_check_model_checklist + ok test_check_supported_models + ok test_check_env_doc + ok test_check_deepseek_v4_vision_manifests + ok test_checker_text + ok test_check_fusion_consistency + ok test_check_attention_rung_consistency + ok test_check_fp4_resident_consistency + ok test_check_cuda_op_arch_gate + ok test_check_rocm_dp4a_intrinsic + ok test_rocm_rank_kernels + ok test_check_runner_routing_consistency + ok test_check_surface_coverage + ok test_check_test_registration + ok test_check_snapshot_pins + ok test_check_oracle_pins + ok test_check_comparator_pins + ok test_dsv4v_w6_compare + ok test_cpu_x86_llamacpp_floor + ok test_audit_live_rows + ok test_check_gate_commands + ok test_gpu_lock_one_truth + ok test_main_baseline + ok test_agent_preflight_skip_report + ok test_agent_pr_body + ok test_agent_issue_index + ok test_check_symbol_anchors + ok test_check_oracle_denominator_flags + ok test_rocm_quant_gather_compare + ok test_rocm_strix_ourarm_staged + ok test_rocm_cooperative_toggles + ok test_tokengate_buildreq + ok test_check_conflict_markers + ok test_check_tree_compiles + ok test_msvc_wx_diagnostics + ok test_prepush_checker_names + ok test_ab_arms_differ + ok test_variadic_harness + ok test_ltx25_pixel_ab_harness + ok test_ltx2_dit_attn_knob_arms + ok test_ltx25_ab_memwatch + ok test_ltx2_oracle_goldens + ok test_ltx2_latent_dump + ok test_tower_skip_rss_report + ok test_tower_skip_rss_arm + ok test_ci_walk_base + ok test_rc_stage_checkpoint + ok test_sglang_lease_identity + ok test_rocprof_attach_preflight + ok test_q4exp_layerfp_diff + ok test_check_ctest_accounting + ok test_qwen3_capture_tools + ok test_qwen3_capture_outputs + ok test_ltx25_render_compare + ok test_ltx25_absolute_reference + ok test_ltx25_prompt_adherence + ok test_ltx25_adherence_detail_loss + ok test_convert_glm5_next_gguf + ok test_check_windows_portability + ok trailer suites + ok commit style suites + ok tools suites + SKIP check-arm-isa-build.py + needs arguments preflight does not supply: usage: check-arm-isa-build.py [-h] --compile-commands COMPILE_COMMANDS + ok check-attention-rung-consistency.py + ok check-benchmark-index.py + ok check-build-runtime-deps.py + ok check-comparator-pins.py + ok check-conflict-markers.py + ok check-container-matrix.py + ok check-container-workflow.py + SKIP check-cpu-isa-build.py + needs arguments preflight does not supply: usage: check-cpu-isa-build.py [-h] --compile-commands COMPILE_COMMANDS + SKIP check-ctest-accounting.py + needs arguments preflight does not supply: usage: check-ctest-accounting.py [-h] --run RUN --count COUNT + SKIP check-cuda-fat-gencode.py + needs arguments preflight does not supply: usage: check-cuda-fat-gencode.py [-h] --compile-commands COMPILE_COMMANDS + ok check-cuda-op-arch-gate.py + ok check-deepseek-v4-vision-manifests.py + ok check-device-leakage.py + ok check-doc-sha-pins.py + ok check-dsv4-gguf-namemap.py + ok check-env-doc.py + ok check-evidence-pin-sha.py + ok check-evidence-refs.py + ok check-fp4-resident-consistency.py + ok check-fusion-consistency.py + ok check-gate-commands.py + ok check-gemv-invocation-consistency.py + ok check-lease-ccache.py + ok check-model-checklist.py + ok check-oracle-denominator-flags.py + ok check-oracle-pins.py + SKIP check-pr-size.py + needs arguments preflight does not supply: usage: check-pr-size.py [-h] --base BASE --head HEAD [--branch BRANCH] + ok check-prompt-contract.py + ok check-quickstart-recipes.py + ok check-readme-structure.py + ok check-release-binary-contract.py + ok check-release-workflow.py + ok check-rocm-dp4a-intrinsic.py + ok check-runner-routing-consistency.py + ok check-site.py + ok check-snapshot-pins.py + ok check-supported-models.py + ok check-surface-coverage.py + ok check-symbol-anchors.py + ok check-test-registration.py + SKIP check-triton-aot-multiarch.py + needs arguments preflight does not supply: usage: check-triton-aot-multiarch.py [-h] --vendored-root VENDORED_ROOT + ok check-tt-public-surface.py + ok check-windows-portability.py + ok check-windows-release-state.py +Committed range vs origin/main 9104388e0b7b641d14525fcb2e951bb27d717090: + ok now-current range +Tree compiles: + compiling what this change reaches. A records-only change returns + at once; a wide header change can take minutes. + ok tree-compiles + check-tree-compiles: 83 of 83 translation unit(s) in scope compiled (19.6s). This checks syntax and semantics only; it does not link, run, or leave the default host configuration. +Commit trailers vs origin/main 9104388e0b7b641d14525fcb2e951bb27d717090: + ok commit-trailers + ok commit-style +Staged change: + ok now-current --staged + +6 gate(s) SKIPPED: check-arm-isa-build.py check-cpu-isa-build.py check-ctest-accounting.py check-cuda-fat-gencode.py check-pr-size.py check-triton-aot-multiarch.py +NOT a green preflight: a skipped gate reported nothing about this tree. +Each reason is printed beside its SKIP above. + +================ .agents/NOW.md ================ +# NOW — the one-Read resume surface + + + +Snapshot, not log. History is git; evidence: +[parity ledger](parity-ledger.md), and benchmarks. Budget: 100 lines / 6,000 +characters. + +## Live claims + +Rendered on demand: **`scripts/now.py`**. It assembles every `SPIKE`/`ACTIVE` +row, its claim and PR, and the row's own next step from the matrices, +`.agents/claims/`, and each row spec's `## Now`. + +They are NOT listed here any more (ENG-NOW-DERIVED, #374). A per-row table in +this file made it a surface every row-advancing PR had to write, which is a lock +under `AGENTS.md` §Records; it conflicted in 5 of the 16 conflicting open PRs +measured at `d928e2c3`. What remains below is authored at operator cadence, so +no per-row change needs to touch this file at all. + +## Current gate + +Token-exact (or ratified distributional) vs pinned vLLM; ≥ throughput and ≤ +latency/memory on every axis, both gate models, reproduced 2–3x idle. See +[verification](verification.md). Pin: vLLM `a7c23ac96d` (0.3.0.dev267), advanced +2026-09-26 from `e126687a9a` by sync `4f11dfc10`. The OPT-125m tokengate PASS +(2026-09-04, `dgx:gpu0`, byte-identical 96/96) ran at the PRIOR pin and +discharges nothing about the other four strict goldens -- 27B W4A4, 32B-NVFP4A16, +35B, Coder -- still owed at the target: they live under `## Owed` in +[the tokengate spec](specs/upstream-sync-headpin-tokengate.md#L569), and the +benchmark baselines still owe step 6 at `555967922` (#2818). Also +[oracles/vllm.md](oracles/vllm.md#L93). + + +## Next actions + +0. **35B mid-band: first lever LANDED** (+1.31% c8, +1.38% c4). The fused + shared gate_up sink still took the MoE-marlin route (20320 launches = 5.4% + GPU); `VT_MARLIN_DENSE_PAIR` ON. Second lever LANDED: shared down-proj emits + bf16, **+2.05% BIT-IDENTICAL**. SiLU [spec](specs/moe-silu-vectorize.md) + **NEGATIVE**: the 9.2x was a MEAN over a bimodal kernel (min 1.34/max 979us); + decode SiLU already beats vLLM's. ~5% UNATTRIBUTED; needs decode-only, 1 tool. +1. **27B NVFP4 0.72x -> 0.85x** (FP8 tower native). Next: NVFP4 MLP marlin, 68% + of roof. Dense-marlin +0.5%; Triton-AOT GDN a WASH. +2. **Spike the Parakeet encoder row** (vLLM: `nano_nemotron_vl.py`; the + transducer half is NOT in vLLM: separate call). +3. **Qwen3.5-4B #206:** +2.83% `PENDING`; latency/VRAM open. +4. **Invocation-parity prevention:** CI guard + checklist; build-verify + `kGemvHeuristicAlgos` on dgx. +5. **Restore `local-ai-worker`** on dgx at campaign end (`--restart=always`). +6. **MiMoV2 port + EXL3 generalisation** (C13, 2026-09-25): specs filed + ([mimov2.md](specs/mimov2.md) + [quant-exl3-generalise.md](specs/quant-exl3-generalise.md)), + local issues created. **W1+W2+W3 DONE and PUSHED.** The device forward + computes through all 48 layers (hybrid full/SWA attention with sink bias, + partial RoPE, asymmetric V head dim, attention_value_scale; layer 0 dense + MLP, layers 1-47 MoE with sigmoid + noaux_tc routing). The EXL3 + generalisation is DONE and PUSHED. **REMAINING:** W4 (MTP, deferred), + W5 (parity gate — no token emitted yet), and wiring EXL3 into the MiMoV2 + forward (EXL3 W3/W4). +7. **Protocol substrate — partly done.** Triage/audit + `STATUS.md` ratchet + + `AGENTS.md` tiering DONE. REMAINING: anchor backfill (6 model rows need a + DECISION); record-era rollover BLOCKED on `DONE` rows bound to + `parity-ledger.md` LINE anchors (re-anchor by ROW ID). + +**Operator/helper protocol** ([spec](workflow.md)): roles are a coordinator +record or worktree+PR; helpers claim `row/` with a DRAFT PR. Role gates +ENFORCE `agent-start.py` → claim → preflight. Review FAIL loops to a fresh +implementer until PASS. Queue: 10 rows; backfill 79, 30 anchored. +**Upstream inventory** ([spec](specs/upstream-derived-inventory-2026-08-05.md)): +SM060/061/070 below vLLM's floor = OUT-OF-SCOPE; COMP-*/DISTRIBUTED-* are REAL +unported work; **every arch in the pinned registry has a row** (the count lives in +[model-matrix.md](model-matrix.md), not here — #622); llama.cpp's 11 extra +devices IN SCOPE (`ROAD-V1-D6`). + +## Protocol invariants that bite most often + +- Every commit carries `FOLLOWING_AGENTS_PROTOCOL` + `Assisted-by:`; never + `Co-Authored-By` or `Signed-off-by` from AI. +- Three MUST-route seams: fusion, merged-GEMM, born-on-the-runner decode. + Not routing is drift; allowlist consciously or fold. +- Mirror vLLM; never ask how a feature should behave. +- `nsys` BOTH sides, SAME tool, before any perf claim; cross-tool comparisons + never establish invocation parity; whole-run sums mix prefill. +- GPU: claim a lease with `rc run` or `rc hold`. Never `ssh` to a box, because + that makes the fleet report it free while you are on it. The flock now lives + INSIDE the lease ([environment](environment.md)). Single-load steady-state, + never reload per rep, named tmux. +- Never weaken a checker to pass; repair the record. +- Work happens in its own worktree on a task branch; the shared checkout stays + clean on `main`, never a work surface. Land via `row/*` PR or authorized + local merge; remove the worktree after. diff --git a/include/vt/quant.h b/include/vt/quant.h index 99d7710184..a07c4626a0 100644 --- a/include/vt/quant.h +++ b/include/vt/quant.h @@ -166,8 +166,11 @@ bool HasQuantDotKernel(DType dtype); // are untouched) and the gemm/gemv fold the per-block scale in the SAME order // as the tier-0 / mmla path with a NON-FUSED multiply-add, so the repacked GEMM // is BIT-IDENTICAL to `kMatmulBTQuant`'s non-repacked output (proven by the -// memcmp round-trip test). Only q8_0 is repacked in G7 (the profile's -// kMatmulBTQuant is q8_0); the k-quants keep the mmla tier. +// memcmp round-trip test). G7 repacked q8_0 only. QUANT-GGUF-CIQ-GEMM +// (q4k/q6k repack seam) EXTENDS the same tier to q4_K and q6_K — there the +// bit-identity target is the ORACLE'S REPACKED KERNEL (a different fp order +// from the vec_dot path), so those arms keep the upstream kernels' FUSED +// vfmaq_f32 scale fold verbatim; see cpu_quant_repack_arm.cpp. // True when the i8mm repack tier is LIVE in this process: compiled for aarch64 // with i8mm, the exact HWCAP/sysctl bits probed present, and not forced to @@ -176,10 +179,23 @@ bool HasQuantDotKernel(DType dtype); bool QuantRepackActive(); // True when a weight of (dtype, N=out, K=in) is repack-eligible on THIS process: -// QuantRepackActive() AND dtype == kQ8_0 AND N % 4 == 0 AND K % 32 == 0 (the -// exact `ne[1] % 4 == 0`, `ne[0] % 8 == 0` guard of repack_q8_0_to_q8_0_4_bl; -// K % 32 subsumes the K % 8 one). A weight that fails it stays plain and takes -// the normal path — correct, just unrepacked. +// QuantRepackActive() AND one of +// dtype == kQ8_0 AND N % 4 == 0 AND K % 32 == 0 (the `ne[1] % 4 == 0`, +// `ne[0] % 8 == 0` guard of repack_q8_0_to_q8_0_4_bl; K % 32 subsumes the +// K % 8 one), or +// dtype in {kQ4_K, kQ6_K} AND N % 8 == 0 AND K % 256 == 0 — the pinned +// oracle's selection (repack.cpp:5011-5017/:5052-5059, tap 5f4d22289): +// on a NEON+i8mm host EVERY Q4_K/Q6_K weight with ne[1] % 8 == 0 repacks +// to the 8x8 kernels; K % 256 is the whole-block rule and subsumes the +// repacks' ne[0] % 8. OPT-IN: also requires VT_CPU_QUANT_REPACK_KQ=1. +// The repacked kernels are a different fp order from the vec_dot path, so +// a default-on flip would silently move every k-quant model's outputs +// before its consumers are re-proofed (kolibri1 logit band, deepseek_v4 +// stacked-expert non-repacked contract, inkling2-w1). Default OFF is +// byte-identical to today; the coordinator flips the default when the +// consumer re-proofs land. +// A weight that fails it stays plain and takes the normal path — correct, just +// unrepacked. bool QuantRepackEligible(DType weight_dtype, int64_t n, int64_t k); // --- ELEMENTWISE repack-at-load (KERNEL-GEMM-CPU-TILED lever 2) ------------- @@ -218,12 +234,34 @@ bool QuantRepackEligible(DType weight_dtype, int64_t n, int64_t k); bool ElemRepackEligible(DType weight_dtype, int64_t n, int64_t k); void ElemRepackWeight(DType weight_dtype, uint8_t* bytes, int64_t n, int64_t k); -// Repack a [N,K] q8_0 weight buffer IN PLACE into the block_q8_0x4 interleave. -// `blocks` holds N*(K/32) plain BlockQ8_0 on entry and N/4 groups of (K/32) -// BlockQ8_0x4 on return (same total bytes). Requires QuantRepackEligible. +// Repack a [N,K] block-quant weight buffer IN PLACE into the i8mm interleave +// its dtype selects: q8_0 -> block_q8_0x4 (N/4 groups), q4_K -> block_q4_Kx8 +// and q6_K -> block_q6_Kx8 (N/8 groups). `blocks` holds N plain block rows on +// entry and the same total bytes interleaved on return (all three layouts are +// size-neutral). Requires QuantRepackEligible. void QuantRepackWeight(DType weight_dtype, uint8_t* blocks, int64_t n, int64_t k); +// The oracle binary's QUANTIZE-CONTRACT arm for Q8_K activations (QUANT-GGUF-CIQ- +// GEMM q4k/q6k repack seam). The pinned oracle (llama.cpp 5f4d22289) compiles +// quantize_row_q8_K_ref under the toolchain-default -ffp-contract=fast, so GCC +// fuses nearest_int's magic add with the preceding scale multiply into ONE +// vfma — the product never rounds to f32 before + 12582912.f. The tree pins +// -ffp-contract=off globally, so the default QuantizeRowQ8_K (BlockFromFloat) +// rounds the product first and differs at 1-ULP ties (measured: 396/7008 +// activation bytes on a live kolibri11 blk.4 row, 0/7008 on random rows — +// ISSUE-LOCAL-01M8M4B648PC33WK7K3ANACVVP). This twin uses the explicit +// correctly-rounded form (std::fma) and is BYTE-IDENTICAL to the oracle +// binary's rows; it is ADDITIVE: the default from_float table is untouched, +// and only the oracle-mirroring repack seam selects it. +void QuantizeRowQ8KFused(const float* x, void* vy, int64_t k); + +// The GEMM twin of the above: ggml_quantize_mat_q8_K_4x8 (repack.cpp:262, +// tap 5f4d22289) with the same fused nearest_int — quantizes FOUR activation +// rows (each `k` long, stride `k`) into `k/256` BlockQ8Kx4 groups. The +// interleaved qs/bsums layout the i8mm GemmQ4K8x8/GemmQ6K8x8 kernels consume. +void QuantizeRowQ8K4x8Fused(const float* x, void* vy, int64_t k); + // Brick 4 (DeepSeek-V4 last-mile): CUDA coalesced-load repack. Eligible = Q8_0 + // K a whole number of 32-blocks (any N). RepackQ8_0Cuda rewrites the [N,K] Q8_0 // buffer IN PLACE from block-interleaved `[d,qs]×nblk` into two contiguous @@ -240,9 +278,11 @@ namespace vt { struct Tensor; namespace cpu { // The repacked-weight GEMM dispatched by `kMatmulBTQuant` when `b.repacked`. -// out[M,N] = a[M,K] @ b[N,K]^T with `b` a q8_0 weight already repacked by -// QuantRepackWeight. Bit-identical to the non-repacked quant path: the i8mm -// gemm runs 4-row activation groups, the i8mm gemv the M=1 / leftover rows. +// out[M,N] = a[M,K] @ b[N,K]^T with `b` a q8_0/q4_K/q6_K weight already +// repacked by QuantRepackWeight. Bit-identical to the oracle's repacked path: +// q8_0 runs the i8mm 4-row gemm plus the i8mm gemv for leftover rows; +// q4_K/q6_K mirror the pinned oracle's dispatch (rows <= 3 the gemv, rows > 3 +// the i8mm 4-row gemm with the leftover rows on the gemv). void QuantRepackMatmul(vt::Tensor& out, const vt::Tensor& a, const vt::Tensor& b); } // namespace cpu } // namespace vt diff --git a/src/vt/cpu/cpu_quant_act.cpp b/src/vt/cpu/cpu_quant_act.cpp index 0bd1d71c5a..6d1911d357 100644 --- a/src/vt/cpu/cpu_quant_act.cpp +++ b/src/vt/cpu/cpu_quant_act.cpp @@ -133,6 +133,113 @@ void QuantizeRowQ8_K(const float* x, void* vy, int64_t k) { } // namespace +// --- Oracle-contract arms (see vt/quant.h for the contract divergence) ------ +// Both are verbatim quantize_row_q8_K_ref / ggml_quantize_mat_q8_K_4x8 (tap +// 5f4d22289) with the fused nearest_int the oracle binary emits under +// -ffp-contract=fast. ADDITIVE: BlockFromFloat still hands out the non-fused +// default; only the repack seam selects these. + +// ggml-quants.c quantize_row_q8_K_ref with std::fma == the oracle binary's +// single vfma. See QuantizeRowQ8_K above for the body it mirrors. +void QuantizeRowQ8KFused(const float* x, void* vy, int64_t k) { + VT_CHECK(k % kQK_K == 0, + "quantize_row_q8_K_fused: k must be a whole 256-block count"); + const int64_t nb = k / kQK_K; + BlockQ8_K* y = static_cast(vy); + + for (int64_t i = 0; i < nb; i++) { + float max = 0; + float amax = 0; + for (int j = 0; j < kQK_K; ++j) { + float ax = std::fabs(x[j]); + if (ax > amax) { + amax = ax; + max = x[j]; + } + } + if (!amax) { + y[i].d = 0; + std::memset(y[i].qs, 0, kQK_K); + std::memset(y[i].bsums, 0, sizeof(y[i].bsums)); + x += kQK_K; + continue; + } + const float iscale = -127.0f / max; + for (int j = 0; j < kQK_K; ++j) { + // The oracle binary fuses `iscale * x[j] + 12582912.0f` into one vfma; + // std::fma is the same correctly-rounded operation spelled explicitly. + float val = std::fma(iscale, x[j], 12582912.0f); + int i32 = 0; + std::memcpy(&i32, &val, sizeof(int)); + int v = (i32 & 0x007fffff) - 0x00400000; + y[i].qs[j] = static_cast(v < 127 ? v : 127); + } + for (int j = 0; j < kQK_K / 16; ++j) { + int sum = 0; + for (int ii = 0; ii < 16; ++ii) { + sum += y[i].qs[j * 16 + ii]; + } + y[i].bsums[j] = static_cast(sum); + } + y[i].d = 1 / iscale; + x += kQK_K; + } +} + +// ggml-cpu/repack.cpp:262 ggml_quantize_mat_q8_K_4x8_generic, fused nearest_int +// (same contract note). FOUR rows (stride `k`) -> kQK_K/256 BlockQ8Kx4. +void QuantizeRowQ8K4x8Fused(const float* x, void* vy, int64_t k) { + VT_CHECK(k % kQK_K == 0, + "quantize_mat_q8_K_4x8_fused: k must be a whole 256-block count"); + const int64_t nb = k / kQK_K; + BlockQ8Kx4* y = static_cast(vy); + + constexpr int kBlckSizeInterleave = 8; + float srcv[4][kQK_K]; + float iscale[4]; + + for (int64_t i = 0; i < nb; i++) { + for (int row_iter = 0; row_iter < 4; row_iter++) { + float amax = 0.0f; // absolute max + float max = 0; + + for (int j = 0; j < kQK_K; j++) { + srcv[row_iter][j] = x[row_iter * k + i * kQK_K + j]; + // Upstream's MAX() is a ternary, NOT fmaxf (NaN propagation). + if (amax < std::fabs(srcv[row_iter][j])) { + amax = std::fabs(srcv[row_iter][j]); + max = srcv[row_iter][j]; + } + } + + iscale[row_iter] = amax ? -127.f / max : 0; + y[i].d[row_iter] = amax ? 1 / iscale[row_iter] : 0; + } + + for (int j = 0; j < kQK_K / 4; j++) { + y[i].bsums[j] = 0; + } + + // Quants values are interleaved in sequence of eight bytes from + // corresponding super blocks; bsums accumulate through upstream's index + // formula verbatim (NOT row-major). + for (int j = 0; j < kQK_K * 4; j++) { + const int src_offset = + (j / (4 * kBlckSizeInterleave)) * kBlckSizeInterleave + + (j % kBlckSizeInterleave); + const int src_id = (j % (4 * kBlckSizeInterleave)) / kBlckSizeInterleave; + const int index = (((j & 31) >> 3) << 2) + ((j >> 8) << 4) + ((j >> 6) & 3); + + float val = std::fma(iscale[src_id], srcv[src_id][src_offset], 12582912.0f); + int i32 = 0; + std::memcpy(&i32, &val, sizeof(int)); + const int v = (i32 & 0x007fffff) - 0x00400000; + y[i].qs[j] = static_cast(v); + y[i].bsums[index] += static_cast(y[i].qs[j]); + } + } +} + FromFloatFn BlockFromFloat(DType dtype) { switch (dtype) { case DType::kQ8_0: return &QuantizeRowQ8_0; diff --git a/src/vt/cpu/cpu_quant_blocks.h b/src/vt/cpu/cpu_quant_blocks.h index 231eeba4ef..f2d2a8d042 100644 --- a/src/vt/cpu/cpu_quant_blocks.h +++ b/src/vt/cpu/cpu_quant_blocks.h @@ -123,6 +123,42 @@ struct BlockQ6_K { }; static_assert(sizeof(BlockQ6_K) == 210, "wrong q6_K block size/padding"); +// ggml-cpu/repack.h:101 — block_q8_Kx4: FOUR Q8_K activation rows interleaved +// for the i8mm GEMM tier. `d` is one f32 per row; `qs` interleaves the four +// rows in 16-byte chunks ([r0 16B][r1 16B][r0 16B][r1 16B]... per 64-element +// sub-super-block; see ggml_quantize_mat_q8_K_4x8_generic); `bsums` follows the +// quantizer's index formula, NOT row-major. Produced only by +// QuantizeRowQ8K4x8Fused; consumed only by GemmQ4K8x8 / GemmQ6Kx8x8. +struct BlockQ8Kx4 { + float d[4]; + int8_t qs[kQK_K * 4]; + int16_t bsums[kQK_K / 4]; +}; +static_assert(sizeof(BlockQ8Kx4) == 16 + kQK_K * 4 + kQK_K / 2, + "wrong q8_Kx4 block size"); + +// ggml-cpu/repack.h:48 — block_q4_Kx8: EIGHT Q4_K weight rows interleaved. +// Same size as 8 plain BlockQ4_K, so the repack is size-neutral. +struct BlockQ4Kx8 { + uint16_t d[8]; + uint16_t dmin[8]; + uint8_t scales[96]; + uint8_t qs[kQK_K * 4]; +}; +static_assert(sizeof(BlockQ4Kx8) == 8 * sizeof(BlockQ4_K), + "wrong q4_Kx8 block size"); + +// ggml-cpu/repack.h:91 — block_q6_Kx8: EIGHT Q6_K weight rows interleaved. +// Same size as 8 plain BlockQ6_K. +struct BlockQ6Kx8 { + uint16_t d[8]; + int8_t scales[kQK_K / 16 * 8]; + uint8_t ql[kQK_K / 2 * 8]; + uint8_t qh[kQK_K / 4 * 8]; +}; +static_assert(sizeof(BlockQ6Kx8) == 8 * sizeof(BlockQ6_K), + "wrong q6_Kx8 block size"); + // ggml-common.h:361-365 — the K-quant ACTIVATION encoding. `d` is a full f32 // (not ggml_half) and `bsums` caches the per-16-element quant sums that the // Q4_K/Q5_K vec_dots use to apply the block minimum in one pass. diff --git a/src/vt/cpu/cpu_quant_repack.cpp b/src/vt/cpu/cpu_quant_repack.cpp index 3a3bd55011..264b626479 100644 --- a/src/vt/cpu/cpu_quant_repack.cpp +++ b/src/vt/cpu/cpu_quant_repack.cpp @@ -10,6 +10,7 @@ // resident buffer keeps the same total size and the quant math is unchanged. #include "cpu_quant_repack.h" +#include #include #include @@ -42,18 +43,57 @@ void InterleaveQ8_0Rows4(const BlockQ8_0* row0, const BlockQ8_0* row1, bool QuantRepackEligible(DType weight_dtype, int64_t n, int64_t k) { if (!QuantRepackActive()) return false; - // G7 repacks q8_0 only (the profile's kMatmulBTQuant is q8_0). The k-quants - // keep the mmla tier; adding their repack layouts is a follow-up row. - if (weight_dtype != DType::kQ8_0) return false; - // repack_q8_0_to_q8_0_4_bl guard: ne[1] % 4 == 0 (N rows) and ne[0] % 8 == 0 - // (K); K % 32 == 0 is the whole-q8_0-block rule and subsumes K % 8. - return n > 0 && k > 0 && n % kQ8_0xNrowsInterleaved == 0 && k % kQK8_0 == 0; + // The pinned oracle (5f4d22289) on a NEON+i8mm host selects q8_0_4x8_q8_0 for + // q8_0 with ne[1] % 4 == 0, and q4_K_8x8_q8_K / q6_K_8x8_q8_K for EVERY Q4_K + // / Q6_K weight with ne[1] % 8 == 0 (ggml-cpu/repack.cpp:5011-5017/:5052- + // 5059). K % 256 is the whole-block rule and subsumes the k-quants' ne[0] % 8. + switch (weight_dtype) { + case DType::kQ8_0: + return n > 0 && k > 0 && n % kQ8_0xNrowsInterleaved == 0 && k % kQK8_0 == 0; + case DType::kQ4_K: + case DType::kQ6_K: + // OPT-IN until every consumer of a Q4_K/Q6_K MatmulBTQuant weight is + // re-proofed against the repacked class (the kolibri1 logit band, the + // deepseek_v4 stacked-expert non-repacked contract, inkling2-w1): the + // repacked kernels are a different fp order from the vec_dot path, so + // flipping eligibility by default silently moves every k-quant model's + // outputs on an i8mm host. VT_CPU_QUANT_REPACK_KQ=1 selects the pinned + // oracle's predicate; the default (off) is byte-identical to today. + // Read per call (cheap) so tests can enable it in-process. + if (std::getenv("VT_CPU_QUANT_REPACK_KQ") == nullptr) return false; + return n > 0 && k > 0 && n % 8 == 0 && k % kQK_K == 0; + default: + return false; + } } void QuantRepackWeight(DType weight_dtype, uint8_t* blocks, int64_t n, int64_t k) { VT_CHECK(QuantRepackEligible(weight_dtype, n, k), "quant_repack_weight: weight is not repack-eligible"); + if (weight_dtype == DType::kQ4_K || weight_dtype == DType::kQ6_K) { + // repack_{q4_K,q6_K}_to_*_8_bl: 8-row groups, snapshot first (not + // in-place-safe; all three layouts are size-neutral). + const int64_t nblocks = k / kQK_K; + const size_t row_bytes = + weight_dtype == DType::kQ4_K ? sizeof(BlockQ4_K) : sizeof(BlockQ6_K); + const size_t total = static_cast(n) * nblocks * row_bytes; + std::vector src(blocks, blocks + total); + const uint8_t* srcb = src.data(); + for (int64_t g = 0; g < n / 8; ++g) { + const uint8_t* in = srcb + static_cast(g) * 8 * nblocks * row_bytes; + if (weight_dtype == DType::kQ4_K) { + RepackQ4KRows8(reinterpret_cast(in), + reinterpret_cast(blocks) + g * nblocks, + nblocks); + } else { + RepackQ6KRows8(reinterpret_cast(in), + reinterpret_cast(blocks) + g * nblocks, + nblocks); + } + } + return; + } const int64_t nblocks = k / kQK8_0; const int64_t ngroups = n / kQ8_0xNrowsInterleaved; // The transform is not in-place-safe, so snapshot the plain rows first. Same @@ -83,6 +123,107 @@ void QuantRepackWeight(DType weight_dtype, uint8_t* blocks, int64_t n, // dst layout for global block index i = r*nb+b (r in [0,n), b in [0,nb)): // qs bytes : blocks[ i*32 .. i*32+32 ) // scale d : *(uint16*)(blocks + n*nb*32 + i*2) +// make_block_q4_Kx8 (ggml-cpu/repack.cpp:3177 @ 5f4d22289), interleave_block=8: +// d/dmin carried verbatim; qs interleaved in 8-byte chunks round-robin over the +// 8 rows; scales unpacked from the 6-bit q4_K packing into the 12-byte-per- +// group interleaved layout (4 subblocks x 2 nibble groups x 12 bytes = 96). +void RepackQ4KRows8(const BlockQ4_K* rows0_7, BlockQ4Kx8* dst, + int64_t nblocks) { + for (int64_t x = 0; x < nblocks; ++x) { + const BlockQ4_K* in[8]; + BlockQ4Kx8& out = *dst++; + for (int i = 0; i < 8; i++) in[i] = &rows0_7[x + i * nblocks]; + + for (int i = 0; i < 8; i++) out.d[i] = in[i]->d; + for (int i = 0; i < 8; i++) out.dmin[i] = in[i]->dmin; + + const int end = kQK_K * 4 / 8; // 128 8-byte chunks + for (int i = 0; i < end; ++i) { + const int src_id = i % 8; + const int src_offset = (i / 8) * 8; + const int dst_offset = i * 8; + std::memcpy(&out.qs[dst_offset], &in[src_id]->qs[src_offset], 8); + } + + uint8_t s[8], m[8]; + for (int i = 0; i < 4; i++) { + for (int j = 0; j < 8; j++) { + s[j] = in[j]->scales[i] & 63; + m[j] = in[j]->scales[i + 4] & 63; + } + out.scales[i * 12 + 0] = (s[0] & 63) + ((s[4] & 48) << 2); + out.scales[i * 12 + 1] = (s[1] & 63) + ((s[5] & 48) << 2); + out.scales[i * 12 + 2] = (s[2] & 63) + ((s[6] & 48) << 2); + out.scales[i * 12 + 3] = (s[3] & 63) + ((s[7] & 48) << 2); + out.scales[i * 12 + 4] = (m[0] & 63) + ((m[4] & 48) << 2); + out.scales[i * 12 + 5] = (m[1] & 63) + ((m[5] & 48) << 2); + out.scales[i * 12 + 6] = (m[2] & 63) + ((m[6] & 48) << 2); + out.scales[i * 12 + 7] = (m[3] & 63) + ((m[7] & 48) << 2); + out.scales[i * 12 + 8] = (s[4] & 15) + ((m[4] & 15) << 4); + out.scales[i * 12 + 9] = (s[5] & 15) + ((m[5] & 15) << 4); + out.scales[i * 12 + 10] = (s[6] & 15) + ((m[6] & 15) << 4); + out.scales[i * 12 + 11] = (s[7] & 15) + ((m[7] & 15) << 4); + } + for (int i = 0; i < 4; i++) { + for (int j = 0; j < 8; j++) { + s[j] = ((in[j]->scales[i] & 192) >> 2) | (in[j]->scales[i + 8] & 15); + m[j] = ((in[j]->scales[i + 4] & 192) >> 2) | + ((in[j]->scales[i + 8] & 240) >> 4); + } + out.scales[i * 12 + 48] = (s[0] & 63) + ((s[4] & 48) << 2); + out.scales[i * 12 + 49] = (s[1] & 63) + ((s[5] & 48) << 2); + out.scales[i * 12 + 50] = (s[2] & 63) + ((s[6] & 48) << 2); + out.scales[i * 12 + 51] = (s[3] & 63) + ((s[7] & 48) << 2); + out.scales[i * 12 + 52] = (m[0] & 63) + ((m[4] & 48) << 2); + out.scales[i * 12 + 53] = (m[1] & 63) + ((m[5] & 48) << 2); + out.scales[i * 12 + 54] = (m[2] & 63) + ((m[6] & 48) << 2); + out.scales[i * 12 + 55] = (m[3] & 63) + ((m[7] & 48) << 2); + out.scales[i * 12 + 56] = (s[4] & 15) + ((m[4] & 15) << 4); + out.scales[i * 12 + 57] = (s[5] & 15) + ((m[5] & 15) << 4); + out.scales[i * 12 + 58] = (s[6] & 15) + ((m[6] & 15) << 4); + out.scales[i * 12 + 59] = (s[7] & 15) + ((m[7] & 15) << 4); + } + } +} + +// make_block_q6_Kx8 (ggml-cpu/repack.cpp:3433 @ 5f4d22289), interleave_block=8: +// d verbatim; ql in 8-byte chunks (128), qh in 8-byte chunks (64); scales +// transposed to [16 groups][8 rows] so a column's scale bytes are contiguous. +void RepackQ6KRows8(const BlockQ6_K* rows0_7, BlockQ6Kx8* dst, + int64_t nblocks) { + constexpr int n_blocks = 8; + for (int64_t x = 0; x < nblocks; ++x) { + const BlockQ6_K* in[8]; + BlockQ6Kx8& out = *dst++; + for (int i = 0; i < n_blocks; i++) in[i] = &rows0_7[x + i * nblocks]; + + for (int i = 0; i < n_blocks; i++) out.d[i] = in[i]->d; + + constexpr int kInterleave = 8; + const int end_ls = kQK_K * 4 / kInterleave; // 128 chunks + for (int i = 0; i < end_ls; ++i) { + const int src_id = i % n_blocks; + const int src_offset = (i / n_blocks) * kInterleave; + const int dst_offset = i * kInterleave; + std::memcpy(&out.ql[dst_offset], &in[src_id]->ql[src_offset], kInterleave); + } + const int end_hs = end_ls / 2; // 64 chunks + for (int i = 0; i < end_hs; ++i) { + const int src_id = i % n_blocks; + const int src_offset = (i / n_blocks) * kInterleave; + const int dst_offset = i * kInterleave; + std::memcpy(&out.qh[dst_offset], &in[src_id]->qh[src_offset], kInterleave); + } + + constexpr int n_scales = kQK_K / 16; // 16 + for (int i = 0; i < n_blocks; i++) { + for (int j = 0; j < n_scales; j++) { + out.scales[j * n_blocks + i] = in[i]->scales[j]; + } + } + } +} + bool RepackQ8_0CudaEligible(DType weight_dtype, int64_t n, int64_t k) { return weight_dtype == DType::kQ8_0 && n > 0 && k > 0 && k % kQK8_0 == 0; } diff --git a/src/vt/cpu/cpu_quant_repack.h b/src/vt/cpu/cpu_quant_repack.h index 0ba6791af6..fcd6322e44 100644 --- a/src/vt/cpu/cpu_quant_repack.h +++ b/src/vt/cpu/cpu_quant_repack.h @@ -26,4 +26,17 @@ void InterleaveQ8_0Rows4(const BlockQ8_0* row0, const BlockQ8_0* row1, const BlockQ8_0* row2, const BlockQ8_0* row3, BlockQ8_0x4* dst, int64_t nblocks); +// Interleave EIGHT plain Q4_K rows (each `nblocks` contiguous BlockQ4_K) into +// `nblocks` BlockQ4Kx8 written to `dst`. make_block_q4_Kx8 (ggml-cpu/repack.cpp +// :3177 @ 5f4d22289) with interleave_block = 8, under +// repack_q4_K_to_q4_K_8_bl (:3572). Pure byte permutation. +void RepackQ4KRows8(const BlockQ4_K* rows0_7, BlockQ4Kx8* dst, + int64_t nblocks); + +// Interleave EIGHT plain Q6_K rows into `nblocks` BlockQ6Kx8. +// make_block_q6_Kx8 (ggml-cpu/repack.cpp:3433 @ 5f4d22289) with +// interleave_block = 8, under repack_q6_K_to_q6_K_8_bl (:3761). +void RepackQ6KRows8(const BlockQ6_K* rows0_7, BlockQ6Kx8* dst, + int64_t nblocks); + } // namespace vt::cpu diff --git a/src/vt/cpu/cpu_quant_repack_arm.cpp b/src/vt/cpu/cpu_quant_repack_arm.cpp index 5bcd2c6b49..2e24480189 100644 --- a/src/vt/cpu/cpu_quant_repack_arm.cpp +++ b/src/vt/cpu/cpu_quant_repack_arm.cpp @@ -1,12 +1,26 @@ // CIQ G7 repack-at-load — Arm i8mm gemm/gemv kernels + dispatch. // -// Ported from llama.cpp @ 237ad9b96 `ggml/src/ggml-cpu/arch/arm/repack.cpp`: +// Ported from llama.cpp. The q8_0 arm mirrors @ 237ad9b96 +// `ggml/src/ggml-cpu/arch/arm/repack.cpp`: // ggml_gemm_q8_0_4x8_q8_0 :5006 (NEON + i8mm 4x4-tile prefill kernel) // ggml_gemv_q8_0_4x8_q8_0 :1757 (NEON + dotprod M=1 / leftover-row kernel) // selected for q8_0 on NEON + i8mm by `ggml_repack_get_optimal_repack_type` // (repack.cpp:4683 -> q8_0_4x8_q8_0 == tensor_traits). // -// DEVIATION for BIT-IDENTITY (recorded). Upstream folds the per-block scale with +// QUANT-GGUF-CIQ-GEMM (q4k/q6k repack seam) adds the K-quant twins, ported +// verbatim from the pinned oracle tap 5f4d22289 (arch/arm/repack.cpp): +// ggml_gemv_q4_K_8x8_q8_K :781 (NEON + dotprod, rows <= 3) +// ggml_gemv_q6_K_8x8_q8_K :1570 (NEON + dotprod, rows <= 3) +// ggml_gemm_q4_K_8x8_q8_K :4015 (NEON + i8mm 4-row arm, rows > 3) +// ggml_gemm_q6_K_8x8_q8_K :4984 (NEON + i8mm 4-row arm, rows > 3) +// plus the activation quantizers quantize_row_q8_K_ref (QuantizeRowQ8KFused, +// cpu_quant_act.cpp) and ggml_quantize_mat_q8_K_4x8 (QuantizeRowQ8K4x8Fused). +// The SVE arms of the upstream gemms are NOT transcribed: this host (and every +// host the i8mm predicate serves here) exposes no SVE, so the oracle binary +// dispatches the NEON arms; the tap-build comparator proved the NEON gemv +// byte-identical to the oracle's live outputs (kolibri11-u3, 2026-11-29). +// +// DEVIATION for the Q8_0 arm (recorded). Upstream folds the per-block scale with // the FUSED `vfmaq_f32`; this port uses the NON-FUSED `vmlaq_f32` in the SAME // block order, so — combined with the global -ffp-contract=off — the float // accumulation is the exact `scale = d_w*d_a; acc = cvt(int)*scale + acc` @@ -15,12 +29,21 @@ // quant values verbatim, so the repacked GEMM is byte-for-byte equal to // `kMatmulBTQuant`'s non-repacked output (memcmp round-trip test). // -// COMPILE/RUNTIME GATING mirrors the mmla tier: compiled with +i8mm for one TU -// (CMakeLists), body guarded by `__aarch64__ && __ARM_FEATURE_MATMUL_INT8`, and -// handed out at runtime only after the shared Linux HWCAP/HWCAP2 or Darwin -// sysctl detector proves i8mm+DotProd. VT_CPU_QUANT_REPACK can force portable -// or i8mm; forcing i8mm on unsupported hardware fails before these instructions -// can execute. Off i8mm aarch64 the loader never repacks. +// DEVIATION POLICY for the Q4_K/Q6_K arms (recorded, the W1 transcription +// policy). The bit-identity target here IS the oracle kernel — a different fp +// order from the vec_dot path — so the upstream kernels' fused `vfmaq_f32` +// scale folds are kept VERBATIM (an explicit intrinsic cannot be un-fused by +// -ffp-contract=off), and the activation quantizers use the oracle binary's +// fused nearest_int (std::fma). The fused quantizer arms are additive: the +// default BlockFromFloat table is untouched (see vt/quant.h). +// +// COMPILE/RUNTIME GATING mirrors the mmla tier: compiled with +i8mm+dotprod for +// one TU (CMakeLists), body guarded by `__aarch64__ && +// __ARM_FEATURE_MATMUL_INT8`, and handed out at runtime only after the shared +// Linux HWCAP/HWCAP2 or Darwin sysctl detector proves i8mm+DotProd. +// VT_CPU_QUANT_REPACK can force portable or i8mm; forcing i8mm on unsupported +// hardware fails before these instructions can execute. Off i8mm aarch64 the +// loader never repacks. #include "vt/quant.h" #if defined(__aarch64__) && defined(__ARM_FEATURE_MATMUL_INT8) @@ -167,6 +190,880 @@ void GemvRowQ8_0(float* s_row, const BlockQ8_0x4* wgroups, } } +// --- Q4_K / Q6_K 8x8 twins (oracle tap 5f4d22289, verbatim) ----------------- + +// arch/arm/repack.cpp:29 decode_q_Kx8_6bit_scales — decodes one 12-byte +// scale/min group of an interleaved Kx8 block into 8 mins (int16x8) and 8 +// scales (int8[8]). +void DecodeQKx86BitScales(const uint8_t* scales_in, int16x8_t* out_mins, + int8_t* out_scales) { + constexpr uint32_t kmask1 = 0x3f3f3f3f; + constexpr uint32_t kmask2 = 0x0f0f0f0f; + constexpr uint32_t kmask3 = 0x03030303; + constexpr uint8_t scales_size = 12; + + uint32_t sm[3]; + std::memcpy(sm, scales_in, scales_size); + + const uint32_t mins_0_3 = sm[1] & kmask1; + const uint32_t mins_4_7 = ((sm[2] >> 4) & kmask2) | (((sm[1] >> 6) & kmask3) << 4); + const uint32x2_t mins_u32 = {mins_0_3, mins_4_7}; + + *out_mins = vreinterpretq_s16_u16(vmovl_u8(vreinterpret_u8_u32(mins_u32))); + + uint32_t scales_u32[2]; + scales_u32[0] = sm[0] & kmask1; + scales_u32[1] = (sm[2] & kmask2) | (((sm[0] >> 6) & kmask3) << 4); + std::memcpy(out_scales, scales_u32, 8); +} + +// ggml_gemv_q4_K_8x8_q8_K (arch/arm/repack.cpp:781, NEON + dotprod). ONE +// activation row (plain BlockQ8_K) against 8-column interleaved tiles; the +// fused vfmaq_f32 scale folds are verbatim (the bit-identity target is the +// oracle kernel). +void GemvQ4K8x8(float* s_row, const BlockQ4Kx8* wgroups, const BlockQ8_K* a_row, + int64_t nblocks, int64_t xg0, int64_t xg1) { + constexpr int col_pairs = 4; // ncols_interleaved / 2 + const uint8x16_t m4b = vdupq_n_u8(0x0f); + + // 1x8 tile = 2 x 4 + float32x4_t acc_f32[2]; + + for (int64_t x = xg0; x < xg1; x++) { + const BlockQ4Kx8* q4_ptr = wgroups + x * nblocks; + + for (int i = 0; i < 2; i++) acc_f32[i] = vdupq_n_f32(0); + + for (int64_t b = 0; b < nblocks; b++) { + float32x4_t q4_d_0 = vcvt_f32_f16(vld1_f16((const __fp16*)q4_ptr[b].d)); + float32x4_t q4_d_1 = + vcvt_f32_f16(vld1_f16((const __fp16*)q4_ptr[b].d + 4)); + float32x4_t q8_d = vdupq_n_f32(a_row[b].d); + float32x4_t sb_scale_0 = vmulq_f32(q4_d_0, q8_d); + float32x4_t sb_scale_1 = vmulq_f32(q4_d_1, q8_d); + float32x4_t q4_dmin_0 = + vcvt_f32_f16(vld1_f16((const __fp16*)q4_ptr[b].dmin)); + float32x4_t q4_dmin_1 = + vcvt_f32_f16(vld1_f16((const __fp16*)q4_ptr[b].dmin + 4)); + float32x4_t sb_min_0 = vmulq_f32(q4_dmin_0, q8_d); + float32x4_t sb_min_1 = vmulq_f32(q4_dmin_1, q8_d); + + // interleaved bias_acc: [0]->r0 0123, [1]->r0 4567 + int32x4_t bias_acc[2] = {vdupq_n_s32(0), vdupq_n_s32(0)}; + // 2 sb each iteration + int32x4_t acc_lo[col_pairs]; + int32x4_t acc_hi[col_pairs]; + + // Each bsum is 16 elements, pairwise add leaves us with the 8 bsums of + // the entire block + const int16x8_t bsums = + vpaddq_s16(vld1q_s16(a_row[b].bsums), vld1q_s16(a_row[b].bsums + 8)); + int16_t bsums_arr[8]; + vst1q_s16(bsums_arr, bsums); + for (int sb = 0; sb < kQK_K / 64; sb++) { + for (int i = 0; i < col_pairs; i++) { + acc_lo[i] = vdupq_n_s32(0); + acc_hi[i] = vdupq_n_s32(0); + } + // Need scales for the low and high nibbles + // 2 * 12 = 24 bytes per subblock, 4 sbs -> 4 * 24 = 96 bytes total + int16x8_t q4sb_mins[2]; + int16x8_t q4sb_scales[2]; + for (int i = 0; i < 2; i++) { + int8_t aux_q4sb[8]; + const int offset = sb * 24 + i * 12; + DecodeQKx86BitScales(&q4_ptr[b].scales[offset], &q4sb_mins[i], + aux_q4sb); + q4sb_scales[i] = vmovl_s8(vld1_s8(aux_q4sb)); + } + + const uint8_t* q4_base = q4_ptr[b].qs + sb * kQK_K; + + // Load the 64 quans from q8K duplicated to use vecdots with the + // interleaved columns but still need the qs to use the low and hi + // bits from q4 + const int8_t* q8_base = a_row[b].qs + sb * 64; + int8x16_t q8_qs[8]; + for (int i = 0; i < 8; i++) { + q8_qs[i] = (int8x16_t)vld1q_dup_s64((const int64_t*)(q8_base + i * 8)); + } + + // Q4s columns iterated in pairs (01, 23, 45, 67) + for (int cp = 0; cp < col_pairs; cp++) { + uint8x16_t q4_qs_cp_0 = vld1q_u8(q4_base + 16 * cp); + uint8x16_t q4_qs_cp_1 = vld1q_u8(q4_base + 16 * cp + 64); + uint8x16_t q4_qs_cp_2 = vld1q_u8(q4_base + 16 * cp + 128); + uint8x16_t q4_qs_cp_3 = vld1q_u8(q4_base + 16 * cp + 192); + + acc_lo[cp] = vdotq_s32(acc_lo[cp], + vreinterpretq_s8_u8(vandq_u8(q4_qs_cp_0, m4b)), + q8_qs[0]); + acc_lo[cp] = vdotq_s32(acc_lo[cp], + vreinterpretq_s8_u8(vandq_u8(q4_qs_cp_1, m4b)), + q8_qs[1]); + acc_lo[cp] = vdotq_s32(acc_lo[cp], + vreinterpretq_s8_u8(vandq_u8(q4_qs_cp_2, m4b)), + q8_qs[2]); + acc_lo[cp] = vdotq_s32(acc_lo[cp], + vreinterpretq_s8_u8(vandq_u8(q4_qs_cp_3, m4b)), + q8_qs[3]); + + acc_hi[cp] = vdotq_s32(acc_hi[cp], + vreinterpretq_s8_u8(vshrq_n_u8(q4_qs_cp_0, 4)), + q8_qs[4]); + acc_hi[cp] = vdotq_s32(acc_hi[cp], + vreinterpretq_s8_u8(vshrq_n_u8(q4_qs_cp_1, 4)), + q8_qs[5]); + acc_hi[cp] = vdotq_s32(acc_hi[cp], + vreinterpretq_s8_u8(vshrq_n_u8(q4_qs_cp_2, 4)), + q8_qs[6]); + acc_hi[cp] = vdotq_s32(acc_hi[cp], + vreinterpretq_s8_u8(vshrq_n_u8(q4_qs_cp_3, 4)), + q8_qs[7]); + } + + // Iterates over a pair of column pairs (4 columns) to use a single + // 128 register; p = 0 -> 0123, p = 2 -> 4567 + for (int i = 0, p = 0; p < col_pairs; i++, p += 2) { + int16x4_t group_scales_lo = + p == 0 ? vget_low_s16(q4sb_scales[0]) : vget_high_s16(q4sb_scales[0]); + int16x4_t group_scales_hi = + p == 0 ? vget_low_s16(q4sb_scales[1]) : vget_high_s16(q4sb_scales[1]); + float32x4_t sb_scale = p == 0 ? sb_scale_0 : sb_scale_1; + + // 0123 or 4567 + float32x4_t sumf_0 = + vcvtq_f32_s32(vmulq_s32(vmovl_s16(group_scales_lo), + vpaddq_s32(acc_lo[p], acc_lo[p + 1]))); + acc_f32[i] = vfmaq_f32(acc_f32[i], sb_scale, sumf_0); + + float32x4_t sumf_1 = + vcvtq_f32_s32(vmulq_s32(vmovl_s16(group_scales_hi), + vpaddq_s32(acc_hi[p], acc_hi[p + 1]))); + acc_f32[i] = vfmaq_f32(acc_f32[i], sb_scale, sumf_1); + } + + // Multiply Acc bsum + mins; each pair of subblocks share the same + // bsums. + int16x4_t bsums_vec_lo = vdup_n_s16(bsums_arr[2 * sb + 0]); + int16x4_t bsums_vec_hi = vdup_n_s16(bsums_arr[2 * sb + 1]); + + // cols 0-3 bias + bias_acc[0] = vmlal_s16(bias_acc[0], bsums_vec_lo, vget_low_s16(q4sb_mins[0])); + bias_acc[0] = vmlal_s16(bias_acc[0], bsums_vec_hi, vget_low_s16(q4sb_mins[1])); + + // cols 4-7 bias + bias_acc[1] = vmlal_s16(bias_acc[1], bsums_vec_lo, vget_high_s16(q4sb_mins[0])); + bias_acc[1] = vmlal_s16(bias_acc[1], bsums_vec_hi, vget_high_s16(q4sb_mins[1])); + } // for sb + + acc_f32[0] = vmlsq_f32(acc_f32[0], vcvtq_f32_s32(bias_acc[0]), sb_min_0); + acc_f32[1] = vmlsq_f32(acc_f32[1], vcvtq_f32_s32(bias_acc[1]), sb_min_1); + + vst1q_f32(s_row + x * 8, acc_f32[0]); + vst1q_f32(s_row + x * 8 + 4, acc_f32[1]); + } + } +} + +// ggml_gemm_q4_K_8x8_q8_K (arch/arm/repack.cpp:4015, NEON + i8mm arm). FOUR +// activation rows (BlockQ8Kx4 interleave) against 8-column interleaved tiles. +// `s` is f32 [4*mgroups, N]; parallelized over row GROUPS (yg), never inside a +// tile, so each output element is written by exactly one thread. +void GemmQ4K8x8(float* s, int64_t bs, const BlockQ4Kx8* wgroups, + const BlockQ8Kx4* agroups, int64_t mgroups, int64_t nblocks, + int64_t xg0, int64_t xg1) { + constexpr int q8_k_blocklen = 4; + const uint8x16_t m4b = vdupq_n_u8(0x0f); + + // 8 accumulators: 2 row pairs x 4 col pairs + float32x4_t acc_f32[8]; + + for (int64_t y = 0; y < mgroups; y++) { + const BlockQ8Kx4* q8_ptr = agroups + y * nblocks; + + for (int64_t x = xg0; x < xg1; x++) { + const BlockQ4Kx8* q4_ptr = wgroups + x * nblocks; + + for (int i = 0; i < 8; i++) { + acc_f32[i] = vdupq_n_f32(0); + } + + for (int64_t b = 0; b < nblocks; b++) { + // bsums pairs belongs to the same q8_k subblock + const int16x8_t bsums[4]{ + vpaddq_s16(vld1q_s16(q8_ptr[b].bsums + 16 * 0), + vld1q_s16(q8_ptr[b].bsums + 16 * 0 + 8)), + vpaddq_s16(vld1q_s16(q8_ptr[b].bsums + 16 * 1), + vld1q_s16(q8_ptr[b].bsums + 16 * 1 + 8)), + vpaddq_s16(vld1q_s16(q8_ptr[b].bsums + 16 * 2), + vld1q_s16(q8_ptr[b].bsums + 16 * 2 + 8)), + vpaddq_s16(vld1q_s16(q8_ptr[b].bsums + 16 * 3), + vld1q_s16(q8_ptr[b].bsums + 16 * 3 + 8)), + }; + int16_t bsums_arr[4][8]; + for (int q8_row = 0; q8_row < 4; q8_row++) { + vst1q_s16(bsums_arr[q8_row], bsums[q8_row]); + } + + int32x4_t sb_acc[4]; // Aux accumulators to store subblock (partial) results + int32x4_t acc[8]; // rows 01 stored in [0][1][2][3] rows 23 stored in [4][5][6][7] + int32x4_t bias_acc[8]; // interleaved bias_acc: [0]->r0 0123, [1]->r0 4567, [2]->r1 0123 ... + for (int i = 0; i < 8; i++) { + acc[i] = vdupq_n_s32(0); + bias_acc[i] = vdupq_n_s32(0); + } + + for (int sb = 0; sb < kQK_K / 64; sb++) { + // Need scales for the low and high nibbles + // 2 * 12 = 24 bytes per subblock, 4 sbs -> 4 * 24 = 96 bytes total + int8_t q4sb_scales[2][8]; + int16x8_t q4sb_mins[2]; // int16 as its needed for bias_acc later + for (int i = 0; i < 2; i++) { + const int offset = sb * 24 + i * 12; + DecodeQKx86BitScales(&q4_ptr[b].scales[offset], &q4sb_mins[i], + q4sb_scales[i]); + } + + // q8_ptr[b].qs has interleaved Q8 rows (01, 23) + const int8_t* q8_base = q8_ptr[b].qs + sb * 256; + + int8x16_t q8_qs_01[8]; + int8x16_t q8_qs_23[8]; + + // Load 32-byte per row pair, 1 subblock each time + for (int i = 0; i < 8; i++) { + const int offset = i * 32; // 16 for row 01, 16 for row 23 + q8_qs_01[i] = vld1q_s8(q8_base + offset); + q8_qs_23[i] = vld1q_s8(q8_base + offset + 16); + } + + const int8x16_t q8s[2][8] = { + {q8_qs_01[0], q8_qs_01[1], q8_qs_01[2], q8_qs_01[3], q8_qs_01[4], + q8_qs_01[5], q8_qs_01[6], q8_qs_01[7]}, + {q8_qs_23[0], q8_qs_23[1], q8_qs_23[2], q8_qs_23[3], q8_qs_23[4], + q8_qs_23[5], q8_qs_23[6], q8_qs_23[7]}, + }; + + // Q4s columns iterated in pairs (01, 23, 45, 67) + for (int cp = 0; cp < 4; cp++) { + for (int i = 0; i < 4; i++) { + sb_acc[i] = vdupq_n_s32(0); + } + + uint8x16_t q4_qs_cp_0 = vld1q_u8(q4_ptr[b].qs + sb * kQK_K + 16 * cp + 0); + uint8x16_t q4_qs_cp_1 = vld1q_u8(q4_ptr[b].qs + sb * kQK_K + 16 * cp + 64); + uint8x16_t q4_qs_cp_2 = vld1q_u8(q4_ptr[b].qs + sb * kQK_K + 16 * cp + 128); + uint8x16_t q4_qs_cp_3 = vld1q_u8(q4_ptr[b].qs + sb * kQK_K + 16 * cp + 192); + const int8x16_t q4_nibbles[2][4] = { + {vreinterpretq_s8_u8(vandq_u8(q4_qs_cp_0, m4b)), + vreinterpretq_s8_u8(vandq_u8(q4_qs_cp_1, m4b)), + vreinterpretq_s8_u8(vandq_u8(q4_qs_cp_2, m4b)), + vreinterpretq_s8_u8(vandq_u8(q4_qs_cp_3, m4b))}, + {vreinterpretq_s8_u8(vshrq_n_u8(q4_qs_cp_0, 4)), + vreinterpretq_s8_u8(vshrq_n_u8(q4_qs_cp_1, 4)), + vreinterpretq_s8_u8(vshrq_n_u8(q4_qs_cp_2, 4)), + vreinterpretq_s8_u8(vshrq_n_u8(q4_qs_cp_3, 4))}}; + + // Calculates the Qs muladd of every row pair (rp) rows 01 and 23 + // of q8 for each of the internal 32 qs subblock (blk) + for (int rp = 0; rp < 2; rp++) { + for (int blk = 0; blk < 2; blk++) { + const int8x16_t* q8 = &q8s[rp][4 * blk]; + const int8x16_t* q4 = q4_nibbles[blk]; + int32x4_t accm = sb_acc[2 * rp + blk]; + // mul add for each qs in the same subblock + for (int qs_offset = 0; qs_offset < 4; qs_offset++) { + accm = vmmlaq_s32(accm, q4[qs_offset], q8[qs_offset]); + } + sb_acc[2 * rp + blk] = accm; + } + } + + // Scales[i] corresponds to column i + const int scale_offset = cp * 2; + const int32_t scale_00 = q4sb_scales[0][scale_offset]; + const int32_t scale_01 = q4sb_scales[0][scale_offset + 1]; + const int32_t scale_10 = q4sb_scales[1][scale_offset]; + const int32_t scale_11 = q4sb_scales[1][scale_offset + 1]; + const int32x4_t block_scale_0 = + vcombine_s32(vdup_n_s32(scale_00), vdup_n_s32(scale_01)); + const int32x4_t block_scale_1 = + vcombine_s32(vdup_n_s32(scale_10), vdup_n_s32(scale_11)); + + acc[cp] = vmlaq_s32(acc[cp], sb_acc[0], block_scale_0); + acc[cp + 4] = vmlaq_s32(acc[cp + 4], sb_acc[2], block_scale_0); + acc[cp] = vmlaq_s32(acc[cp], sb_acc[1], block_scale_1); + acc[cp + 4] = vmlaq_s32(acc[cp + 4], sb_acc[3], block_scale_1); + } + + // Multiply Acc bsum + mins + for (int q8_row = 0; q8_row < 4; q8_row++) { + // Each pair of subblocks share the same bsums + // Load scalar bsum -> broadcast to a vector (vdupq_n_s16(s)). + int16x4_t bsums_vec_lo = vdup_n_s16(bsums_arr[sb][q8_row * 2]); + int16x4_t bsums_vec_hi = vdup_n_s16(bsums_arr[sb][q8_row * 2 + 1]); + + bias_acc[2 * q8_row] = + vmlal_s16(bias_acc[2 * q8_row], bsums_vec_lo, + vget_low_s16(q4sb_mins[0])); + bias_acc[2 * q8_row] = + vmlal_s16(bias_acc[2 * q8_row], bsums_vec_hi, + vget_low_s16(q4sb_mins[1])); + bias_acc[2 * q8_row + 1] = + vmlal_s16(bias_acc[2 * q8_row + 1], bsums_vec_lo, + vget_high_s16(q4sb_mins[0])); + bias_acc[2 * q8_row + 1] = + vmlal_s16(bias_acc[2 * q8_row + 1], bsums_vec_hi, + vget_high_s16(q4sb_mins[1])); + } + } // for sb + + // Reorder of i8mm output with bias and output layout + for (int i = 0; i < 8; i++) { + int32x2x2_t aux = vzip_s32(vget_low_s32(acc[i]), vget_high_s32(acc[i])); + acc[i] = vcombine_s32(aux.val[0], aux.val[1]); + } + int32x4_t reorder_acc[8] = { + vcombine_s32(vget_low_s32(acc[0]), vget_low_s32(acc[1])), + vcombine_s32(vget_low_s32(acc[2]), vget_low_s32(acc[3])), + vcombine_s32(vget_high_s32(acc[0]), vget_high_s32(acc[1])), + vcombine_s32(vget_high_s32(acc[2]), vget_high_s32(acc[3])), + vcombine_s32(vget_low_s32(acc[4]), vget_low_s32(acc[5])), + vcombine_s32(vget_low_s32(acc[6]), vget_low_s32(acc[7])), + vcombine_s32(vget_high_s32(acc[4]), vget_high_s32(acc[5])), + vcombine_s32(vget_high_s32(acc[6]), vget_high_s32(acc[7])), + }; + + for (int i = 0; i < q8_k_blocklen; i++) { + for (int j = 0; j < 2; j++) { + float32x4_t q8_d = vdupq_n_f32(q8_ptr[b].d[i]); + float32x4_t q4_dmin = + vcvt_f32_f16(vld1_f16((const __fp16*)(q4_ptr[b].dmin + j * 4))); + const float32x4_t dmins = vmulq_f32(q4_dmin, q8_d); + + float32x4_t q4_d = + vcvt_f32_f16(vld1_f16((const __fp16*)(q4_ptr[b].d + j * 4))); + const float32x4_t scale = vmulq_f32(q4_d, q8_d); + + acc_f32[2 * i + j] = vmlsq_f32(acc_f32[2 * i + j], + vcvtq_f32_s32(bias_acc[2 * i + j]), + dmins); + acc_f32[2 * i + j] = + vmlaq_f32(acc_f32[2 * i + j], + vcvtq_f32_s32(reorder_acc[2 * i + j]), scale); + } + } + } // for b + + // With the previous reorder, the tile is already in the correct memory layout. + for (int i = 0; i < q8_k_blocklen; i++) { + const int64_t row = y * q8_k_blocklen + i; + for (int j = 0; j < 2; j++) { + const int64_t col = x * 8 + j * 4; + vst1q_f32(s + row * bs + col, acc_f32[2 * i + j]); + } + } + } // for x + } // for y +} + +// ggml_gemv_q6_K_8x8_q8_K (arch/arm/repack.cpp:1570, NEON + dotprod). ONE +// activation row (plain BlockQ8_K). +void GemvQ6K8x8(float* s_row, const BlockQ6Kx8* wgroups, const BlockQ8_K* a_row, + int64_t nblocks, int64_t xg0, int64_t xg1) { + constexpr int col_pairs = 4; + const uint8x16_t m4b = vdupq_n_u8(0x0f); + const uint8x16_t mask_lo = vdupq_n_u8(0x03); + const uint8x16_t mask_hi = vdupq_n_u8(0x30); + + // 1x8 tile = 2 x 4 + float32x4_t acc_f32[2]; + + for (int64_t x = xg0; x < xg1; x++) { + const BlockQ6Kx8* q6_ptr = wgroups + x * nblocks; + + acc_f32[0] = vdupq_n_f32(0); + acc_f32[1] = vdupq_n_f32(0); + + for (int64_t b = 0; b < nblocks; b++) { + float32x4_t q6_d_0 = vcvt_f32_f16(vld1_f16((const __fp16*)q6_ptr[b].d)); + float32x4_t q6_d_1 = + vcvt_f32_f16(vld1_f16((const __fp16*)q6_ptr[b].d + 4)); + float32x4_t q8_d = vdupq_n_f32(a_row[b].d); + float32x4_t sb_scale_0 = vmulq_f32(q6_d_0, q8_d); + float32x4_t sb_scale_1 = vmulq_f32(q6_d_1, q8_d); + + int32x2_t acc[col_pairs]; + for (int i = 0; i < col_pairs; i++) { + acc[i] = vdup_n_s32(0); + } + + // Load all 16 scales once and widen to int16 (Q6_K has 16 scales per block) + // Reused for bias and dequantization later + int16_t q6_scales[16 * 8]; + for (int i = 0; i < 16; i++) { + int16x8_t scales = vmovl_s8(vld1_s8(q6_ptr[b].scales + i * 8)); + vst1q_s16(q6_scales + i * 8, scales); + } + + // Compute bias per column using q8 bsums and preloaded scales to skip the -32 shift + int32x4_t bias_lo = vdupq_n_s32(0); + int32x4_t bias_hi = vdupq_n_s32(0); + + // Load bsums in chunks of 4 to process with vectorized operations + for (int i = 0; i < 16; i += 4) { + int16x4_t bsums_vec = vld1_s16(a_row[b].bsums + i); + int16x4_t scales_lo_0 = vld1_s16(q6_scales + (i + 0) * 8); + int16x4_t scales_hi_0 = vld1_s16(q6_scales + (i + 0) * 8 + 4); + int16x4_t scales_lo_1 = vld1_s16(q6_scales + (i + 1) * 8); + int16x4_t scales_hi_1 = vld1_s16(q6_scales + (i + 1) * 8 + 4); + int16x4_t scales_lo_2 = vld1_s16(q6_scales + (i + 2) * 8); + int16x4_t scales_hi_2 = vld1_s16(q6_scales + (i + 2) * 8 + 4); + int16x4_t scales_lo_3 = vld1_s16(q6_scales + (i + 3) * 8); + int16x4_t scales_hi_3 = vld1_s16(q6_scales + (i + 3) * 8 + 4); + + bias_lo = vmlal_lane_s16(bias_lo, scales_lo_0, bsums_vec, 0); + bias_hi = vmlal_lane_s16(bias_hi, scales_hi_0, bsums_vec, 0); + bias_lo = vmlal_lane_s16(bias_lo, scales_lo_1, bsums_vec, 1); + bias_hi = vmlal_lane_s16(bias_hi, scales_hi_1, bsums_vec, 1); + bias_lo = vmlal_lane_s16(bias_lo, scales_lo_2, bsums_vec, 2); + bias_hi = vmlal_lane_s16(bias_hi, scales_hi_2, bsums_vec, 2); + bias_lo = vmlal_lane_s16(bias_lo, scales_lo_3, bsums_vec, 3); + bias_hi = vmlal_lane_s16(bias_hi, scales_hi_3, bsums_vec, 3); + } + bias_lo = vshlq_n_s32(bias_lo, 5); + bias_hi = vshlq_n_s32(bias_hi, 5); + + // Process two 128-value halves per superblock + for (int half = 0; half < 2; half++) { + const uint8_t* ql_base = q6_ptr[b].ql + half * 512; + const uint8_t* qh_base = q6_ptr[b].qh + half * 256; + + for (int sb = 0; sb < kQK_K / 64; sb++) { + const int8_t* q8_base_l = a_row[b].qs + half * 128 + sb * 16; + const int8_t* q8_base_h = q8_base_l + 64; + + // Load and duplicate q8 values (each register covers two interleaved columns of q6) + int8x16_t q8_l[2]; + int8x16_t q8_h[2]; + for (int i = 0; i < 2; i++) { + q8_l[i] = (int8x16_t)vld1q_dup_s64((const int64_t*)(q8_base_l + i * 8)); + q8_h[i] = (int8x16_t)vld1q_dup_s64((const int64_t*)(q8_base_h + i * 8)); + } + + const int ql_off_base = sb * kQK_K / 2; + const int qh_off_base = ql_off_base & 255; // wraps after 256 bytes + + // Load 4 vectors at once (64 bytes each for ql_0, ql_1, qh_0, qh_1) + uint8x16x4_t q6_ql_0 = vld1q_u8_x4(ql_base + ql_off_base); + uint8x16x4_t q6_ql_1 = vld1q_u8_x4(ql_base + ql_off_base + 64); + uint8x16x4_t q6_qh_0 = vld1q_u8_x4(qh_base + qh_off_base); + uint8x16x4_t q6_qh_1 = vld1q_u8_x4(qh_base + qh_off_base + 64); + + // Adjust qh for subblocks 2 and 3 (shift right by 2) + if (sb > 1) { + q6_qh_0.val[0] = vshrq_n_u8(q6_qh_0.val[0], 2); + q6_qh_0.val[1] = vshrq_n_u8(q6_qh_0.val[1], 2); + q6_qh_0.val[2] = vshrq_n_u8(q6_qh_0.val[2], 2); + q6_qh_0.val[3] = vshrq_n_u8(q6_qh_0.val[3], 2); + q6_qh_1.val[0] = vshrq_n_u8(q6_qh_1.val[0], 2); + q6_qh_1.val[1] = vshrq_n_u8(q6_qh_1.val[1], 2); + q6_qh_1.val[2] = vshrq_n_u8(q6_qh_1.val[2], 2); + q6_qh_1.val[3] = vshrq_n_u8(q6_qh_1.val[3], 2); + } + + // Process column pairs (0-1, 2-3, 4-5, 6-7) + for (int cp = 0; cp < col_pairs; cp++) { + const uint8x16_t q6_qs_cp_0_l = q6_ql_0.val[cp]; + const uint8x16_t q6_qs_cp_1_l = q6_ql_1.val[cp]; + const uint8x16_t q6_qs_cp_0_h = q6_qh_0.val[cp]; + const uint8x16_t q6_qs_cp_1_h = q6_qh_1.val[cp]; + + // Extract high 2 bits for upper nibble reconstruction + const uint8x16_t q6_qs_cp_0_hh = vandq_u8(q6_qs_cp_0_h, mask_hi); + const uint8x16_t q6_qs_cp_1_hh = vandq_u8(q6_qs_cp_1_h, mask_hi); + + // q6 = (low4 | high2<<4), without -32 bias (handled via bsums) + const int8x16_t q6_l0 = vreinterpretq_s8_u8( + vsliq_n_u8(vandq_u8(q6_qs_cp_0_l, m4b), + vandq_u8(q6_qs_cp_0_h, mask_lo), 4)); + const int8x16_t q6_l1 = vreinterpretq_s8_u8( + vsliq_n_u8(vandq_u8(q6_qs_cp_1_l, m4b), + vandq_u8(q6_qs_cp_1_h, mask_lo), 4)); + const int8x16_t q6_h0 = vreinterpretq_s8_u8( + vorrq_u8(vshrq_n_u8(q6_qs_cp_0_l, 4), q6_qs_cp_0_hh)); + const int8x16_t q6_h1 = vreinterpretq_s8_u8( + vorrq_u8(vshrq_n_u8(q6_qs_cp_1_l, 4), q6_qs_cp_1_hh)); + + int32x4_t sb_acc_l = vdupq_n_s32(0); + sb_acc_l = vdotq_s32(sb_acc_l, q6_l0, q8_l[0]); + sb_acc_l = vdotq_s32(sb_acc_l, q6_l1, q8_l[1]); + + int32x4_t sb_acc_h = vdupq_n_s32(0); + sb_acc_h = vdotq_s32(sb_acc_h, q6_h0, q8_h[0]); + sb_acc_h = vdotq_s32(sb_acc_h, q6_h1, q8_h[1]); + + // Pairwise add to get per-column sums: [col0, col1] + int32x2_t sum_l = + vpadd_s32(vget_low_s32(sb_acc_l), vget_high_s32(sb_acc_l)); + int32x2_t sum_h = + vpadd_s32(vget_low_s32(sb_acc_h), vget_high_s32(sb_acc_h)); + + const int scale_idx_l = half * 8 + sb; + const int scale_idx_h = half * 8 + sb + 4; + + // Access scales using array indexing (scales are interleaved by column) + const int32x2_t scale_vec_l = { + (int32_t)q6_scales[scale_idx_l * 8 + cp * 2], + (int32_t)q6_scales[scale_idx_l * 8 + cp * 2 + 1]}; + const int32x2_t scale_vec_h = { + (int32_t)q6_scales[scale_idx_h * 8 + cp * 2], + (int32_t)q6_scales[scale_idx_h * 8 + cp * 2 + 1]}; + + // Accumulate scaled results + acc[cp] = vmla_s32(acc[cp], sum_l, scale_vec_l); + acc[cp] = vmla_s32(acc[cp], sum_h, scale_vec_h); + } + } + } // for half + + // Bias correction + acc[0] = vsub_s32(acc[0], vget_low_s32(bias_lo)); + acc[1] = vsub_s32(acc[1], vget_high_s32(bias_lo)); + acc[2] = vsub_s32(acc[2], vget_low_s32(bias_hi)); + acc[3] = vsub_s32(acc[3], vget_high_s32(bias_hi)); + + // Apply superblock scale (no mins for q6_K) + // acc[cp] has [c0, c1] + float32x2_t w_01 = vmul_f32(vcvt_f32_s32(acc[0]), vget_low_f32(sb_scale_0)); + float32x2_t w_23 = vmul_f32(vcvt_f32_s32(acc[1]), vget_high_f32(sb_scale_0)); + float32x2_t w_45 = vmul_f32(vcvt_f32_s32(acc[2]), vget_low_f32(sb_scale_1)); + float32x2_t w_67 = vmul_f32(vcvt_f32_s32(acc[3]), vget_high_f32(sb_scale_1)); + + acc_f32[0] = vaddq_f32(acc_f32[0], vcombine_f32(w_01, w_23)); + acc_f32[1] = vaddq_f32(acc_f32[1], vcombine_f32(w_45, w_67)); + } // for b + + vst1q_f32(s_row + x * 8, acc_f32[0]); + vst1q_f32(s_row + x * 8 + 4, acc_f32[1]); + } // for x +} + +// ggml_gemm_q6_K_8x8_q8_K (arch/arm/repack.cpp:4984, NEON + i8mm arm). FOUR +// activation rows (BlockQ8Kx4 interleave) against 8-column interleaved tiles. +void GemmQ6K8x8(float* s, int64_t bs, const BlockQ6Kx8* wgroups, + const BlockQ8Kx4* agroups, int64_t mgroups, int64_t nblocks, + int64_t xg0, int64_t xg1) { + constexpr int q8_k_blocklen = 4; + const uint8x16_t m4b = vdupq_n_u8(0x0f); + const uint8x16_t mask_lo = vdupq_n_u8(0x03); + const uint8x16_t mask_hi = vdupq_n_u8(0x30); + const int8x16_t m32s = vdupq_n_s8(32); + + // 8 accumulators: 4 q8 rows x 2 col groups (0-3, 4-7) + float32x4_t acc_f32[8]; + + for (int64_t y = 0; y < mgroups; y++) { + const BlockQ8Kx4* q8_ptr = agroups + y * nblocks; + + for (int64_t x = xg0; x < xg1; x++) { + const BlockQ6Kx8* q6_ptr = wgroups + x * nblocks; + + for (int i = 0; i < 8; i++) { + acc_f32[i] = vdupq_n_f32(0); + } + + for (int64_t b = 0; b < nblocks; b++) { + int32x4_t acc[8]; // rows 01 stored in [0][1][2][3], rows 23 stored in [4][5][6][7] + for (int i = 0; i < 8; i++) { + acc[i] = vdupq_n_s32(0); + } + + // Q6_K has simple 8-bit scales, 16 per block (one per 16 values) + // Reused for bias and dequantization later + int16_t q6_scales[16 * 8]; + for (int i = 0; i < 16; ++i) { + int16x8_t s16 = vmovl_s8(vld1_s8(q6_ptr[b].scales + i * 8)); + vst1q_s16(q6_scales + i * 8, s16); + } + + // Process two 128-value halves per superblock + for (int half = 0; half < 2; half++) { + const uint8_t* ql_base = q6_ptr[b].ql + half * 512; + const uint8_t* qh_base = q6_ptr[b].qh + half * 256; + + // A subblock (sb) is a set of weights that share the scale + // Since q6_K scales are per 16 elements + for (int sb = 0; sb < kQK_K / 64; sb++) { + // Q6_K weight index increasing by 64 instead of 32 requires + // loading various q8 memory regions + const int8_t* q8_base_l = q8_ptr[b].qs + half * 512 + sb * 64; + const int8_t* q8_base_h = q8_ptr[b].qs + half * 512 + 256 + sb * 64; + + int8x16_t q8_l_01[2]; + int8x16_t q8_l_23[2]; + for (int i = 0; i < 2; i++) { + const int offset = i * 32; + q8_l_01[i] = vld1q_s8(q8_base_l + offset); // 0..7 & 8..15 (r01) + q8_l_23[i] = vld1q_s8(q8_base_l + offset + 16); // 0..7 & 8..15 (r23) + } + + int8x16_t q8_h_01[2]; + int8x16_t q8_h_23[2]; + for (int i = 0; i < 2; i++) { + const int offset = i * 32; + q8_h_01[i] = vld1q_s8(q8_base_h + offset); + q8_h_23[i] = vld1q_s8(q8_base_h + offset + 16); + } + + const int ql_off_base = sb * kQK_K / 2; + + uint8x16_t q6_ql_0[4]; + uint8x16_t q6_ql_1[4]; + for (int k = 0; k < 4; k++) { + q6_ql_0[k] = vld1q_u8(ql_base + ql_off_base + 16 * k); + q6_ql_1[k] = vld1q_u8(ql_base + ql_off_base + 64 + 16 * k); + } + + const int qh_off_base = (sb * kQK_K / 2) & 255; // wrap after 256 bytes + uint8x16_t q6_qh_0[4]; + uint8x16_t q6_qh_1[4]; + for (int k = 0; k < 4; k++) { + q6_qh_0[k] = vld1q_u8(qh_base + qh_off_base + 16 * k); + q6_qh_1[k] = vld1q_u8(qh_base + qh_off_base + 64 + 16 * k); + } + + // Adjust for the proper high bits (Sb 2 and 3) + if (sb > 1) { + for (int k = 0; k < 4; k++) { + q6_qh_0[k] = vshrq_n_u8(q6_qh_0[k], 2); + q6_qh_1[k] = vshrq_n_u8(q6_qh_1[k], 2); + } + } + + // Process column pairs (0-1, 2-3, 4-5, 6-7) + for (int cp = 0; cp < 4; cp++) { + const uint8x16_t q6_qs_cp_0_l = q6_ql_0[cp]; + const uint8x16_t q6_qs_cp_1_l = q6_ql_1[cp]; + const uint8x16_t q6_qs_cp_0_h = q6_qh_0[cp]; + const uint8x16_t q6_qs_cp_1_h = q6_qh_1[cp]; + + // Extract high 2 bits for upper nibble reconstruction + const uint8x16_t q6_qs_cp_0_hh = vandq_u8(q6_qs_cp_0_h, mask_hi); + const uint8x16_t q6_qs_cp_1_hh = vandq_u8(q6_qs_cp_1_h, mask_hi); + + // q6 = (low4 | high2<<4) - 32 + const int8x16_t q6_l0 = vsubq_s8( + vreinterpretq_s8_u8(vsliq_n_u8(vandq_u8(q6_qs_cp_0_l, m4b), + vandq_u8(q6_qs_cp_0_h, mask_lo), + 4)), + m32s); + const int8x16_t q6_l1 = vsubq_s8( + vreinterpretq_s8_u8(vsliq_n_u8(vandq_u8(q6_qs_cp_1_l, m4b), + vandq_u8(q6_qs_cp_1_h, mask_lo), + 4)), + m32s); + const int8x16_t q6_h0 = vsubq_s8( + vreinterpretq_s8_u8( + vorrq_u8(vshrq_n_u8(q6_qs_cp_0_l, 4), q6_qs_cp_0_hh)), + m32s); + const int8x16_t q6_h1 = vsubq_s8( + vreinterpretq_s8_u8( + vorrq_u8(vshrq_n_u8(q6_qs_cp_1_l, 4), q6_qs_cp_1_hh)), + m32s); + + // row pair 0, base_l + int32x4_t sb_acc_0l = + vmmlaq_s32(vdupq_n_s32(0), q6_l0, q8_l_01[0]); + sb_acc_0l = vmmlaq_s32(sb_acc_0l, q6_l1, q8_l_01[1]); + // row pair 0, base_h + int32x4_t sb_acc_0h = + vmmlaq_s32(vdupq_n_s32(0), q6_h0, q8_h_01[0]); + sb_acc_0h = vmmlaq_s32(sb_acc_0h, q6_h1, q8_h_01[1]); + // row pair 1, base_l + int32x4_t sb_acc_1l = + vmmlaq_s32(vdupq_n_s32(0), q6_l0, q8_l_23[0]); + sb_acc_1l = vmmlaq_s32(sb_acc_1l, q6_l1, q8_l_23[1]); + // row pair 1, base_h + int32x4_t sb_acc_1h = + vmmlaq_s32(vdupq_n_s32(0), q6_h0, q8_h_23[0]); + sb_acc_1h = vmmlaq_s32(sb_acc_1h, q6_h1, q8_h_23[1]); + + const int scale_idx_l = half * 8 + sb; + const int scale_idx_h = half * 8 + sb + 4; + + const int32x4_t scale_vec_l = { + q6_scales[scale_idx_l * 8 + cp * 2 + 0], + q6_scales[scale_idx_l * 8 + cp * 2 + 0], + q6_scales[scale_idx_l * 8 + cp * 2 + 1], + q6_scales[scale_idx_l * 8 + cp * 2 + 1], + }; + const int32x4_t scale_vec_h = { + q6_scales[scale_idx_h * 8 + cp * 2 + 0], + q6_scales[scale_idx_h * 8 + cp * 2 + 0], + q6_scales[scale_idx_h * 8 + cp * 2 + 1], + q6_scales[scale_idx_h * 8 + cp * 2 + 1], + }; + + acc[cp] = vmlaq_s32(acc[cp], sb_acc_0l, scale_vec_l); + acc[cp] = vmlaq_s32(acc[cp], sb_acc_0h, scale_vec_h); + acc[cp + 4] = vmlaq_s32(acc[cp + 4], sb_acc_1l, scale_vec_l); + acc[cp + 4] = vmlaq_s32(acc[cp + 4], sb_acc_1h, scale_vec_h); + } + } + } // for half + + // Reorder i8mm output to match memory layout + for (int i = 0; i < 8; i++) { + int32x2x2_t aux = vzip_s32(vget_low_s32(acc[i]), vget_high_s32(acc[i])); + acc[i] = vcombine_s32(aux.val[0], aux.val[1]); + } + int32x4_t reorder_acc[8] = { + vcombine_s32(vget_low_s32(acc[0]), vget_low_s32(acc[1])), + vcombine_s32(vget_low_s32(acc[2]), vget_low_s32(acc[3])), + vcombine_s32(vget_high_s32(acc[0]), vget_high_s32(acc[1])), + vcombine_s32(vget_high_s32(acc[2]), vget_high_s32(acc[3])), + vcombine_s32(vget_low_s32(acc[4]), vget_low_s32(acc[5])), + vcombine_s32(vget_low_s32(acc[6]), vget_low_s32(acc[7])), + vcombine_s32(vget_high_s32(acc[4]), vget_high_s32(acc[5])), + vcombine_s32(vget_high_s32(acc[6]), vget_high_s32(acc[7])), + }; + + // Apply superblock scale (no mins for q6_K) + for (int i = 0; i < q8_k_blocklen; i++) { + for (int j = 0; j < 2; j++) { + float32x4_t q8_d = vdupq_n_f32(q8_ptr[b].d[i]); + float32x4_t q6_d = + vcvt_f32_f16(vld1_f16((const __fp16*)(q6_ptr[b].d + j * 4))); + const float32x4_t scale = vmulq_f32(q6_d, q8_d); + + acc_f32[2 * i + j] = + vmlaq_f32(acc_f32[2 * i + j], + vcvtq_f32_s32(reorder_acc[2 * i + j]), scale); + } + } + } // for b + + // Store results + for (int i = 0; i < q8_k_blocklen; i++) { + const int64_t row = y * q8_k_blocklen + i; + for (int j = 0; j < 2; j++) { + const int64_t col = x * 8 + j * 4; + vst1q_f32(s + row * bs + col, acc_f32[2 * i + j]); + } + } + } // for x + } // for y +} + +} // namespace + +namespace { + +// The Q4_K/Q6_K repack driver (the oracle's forward_mul_mat shape). out[M,N], +// a[M,K], b a repacked Q4_K/Q6_K weight (N % 8 == 0, K % 256 == 0). +void KQuantRepackMatmul(Tensor& out, const Tensor& a, const Tensor& b) { + const int64_t m = a.shape[0]; + const int64_t k = a.shape[1]; + const int64_t n = b.shape[0]; + VT_CHECK(n % 8 == 0 && k % kQK_K == 0, + "quant_repack_matmul: K-quant repack requires N%8 and K%256"); + const int64_t nblocks = k / kQK_K; + const int64_t a_rs = a.stride[0]; + + // Output: f32 directly when possible, else through an f32 scratch (the + // layout mirrors the Q8_0 driver; MatmulBTQuant guarantees `out` contiguous). + const bool out_is_f32 = (out.dtype == DType::kF32); + std::vector out_scratch; + float* s; + if (out_is_f32) { + s = out.Ptr(); + } else { + out_scratch.resize(static_cast(m) * n); + s = out_scratch.data(); + } + const int64_t bs = n; + const int64_t ncol_groups = n / 8; + const bool is_q4k = (b.dtype == DType::kQ4_K); + + // Rows > 3: the i8mm gemm over 4-row groups. + const int64_t mgroups = m / 4; + if (mgroups > 0) { + const size_t group_bytes = static_cast(nblocks) * sizeof(BlockQ8Kx4); + std::vector act(static_cast(mgroups) * group_bytes); + std::vector rows(static_cast(4) * k); + for (int64_t g = 0; g < mgroups; ++g) { + for (int r = 0; r < 4; ++r) { + const int64_t i = g * 4 + r; + float* row = rows.data() + static_cast(r) * k; + for (int64_t p = 0; p < k; ++p) row[p] = LoadActF32(a, i * a_rs + p); + } + QuantizeRowQ8K4x8Fused(rows.data(), + act.data() + static_cast(g) * group_bytes, + k); + } + const void* wgroups = b.data; + if (is_q4k) { + ParallelForRows(CurrentThreadpool(), ncol_groups, + [&](int64_t xg0, int64_t xg1) { + GemmQ4K8x8(s, bs, + reinterpret_cast(wgroups), + reinterpret_cast(act.data()), + mgroups, nblocks, xg0, xg1); + }); + } else { + ParallelForRows(CurrentThreadpool(), ncol_groups, + [&](int64_t xg0, int64_t xg1) { + GemmQ6K8x8(s, bs, + reinterpret_cast(wgroups), + reinterpret_cast(act.data()), + mgroups, nblocks, xg0, xg1); + }); + } + } + + // Leftover rows (m % 4) AND the whole decode regime (m <= 3): the dotprod + // gemv, one plain-q8_K activation row at a time (the oracle's fused + // QuantizeRowQ8KFused, the arm that reproduces the oracle binary's bytes). + const int64_t gemm_rows = mgroups * 4; + if (gemm_rows < m) { + const size_t act_row_bytes = static_cast(nblocks) * sizeof(BlockQ8_K); + std::vector arow(act_row_bytes); + std::vector row(static_cast(k)); + for (int64_t i = gemm_rows; i < m; ++i) { + for (int64_t p = 0; p < k; ++p) row[p] = LoadActF32(a, i * a_rs + p); + QuantizeRowQ8KFused(row.data(), arow.data(), k); + float* s_row = s + i * bs; + if (is_q4k) { + ParallelForRows(CurrentThreadpool(), ncol_groups, + [&](int64_t xg0, int64_t xg1) { + GemvQ4K8x8(s_row, + reinterpret_cast(b.data), + reinterpret_cast(arow.data()), + nblocks, xg0, xg1); + }); + } else { + ParallelForRows(CurrentThreadpool(), ncol_groups, + [&](int64_t xg0, int64_t xg1) { + GemvQ6K8x8(s_row, + reinterpret_cast(b.data), + reinterpret_cast(arow.data()), + nblocks, xg0, xg1); + }); + } + } + } + + if (!out_is_f32) { + for (int64_t i = 0; i < m; ++i) { + for (int64_t j = 0; j < n; ++j) { + StoreOutF32(out, i * n + j, out_scratch[static_cast(i) * n + j]); + } + } + } +} + } // namespace bool QuantRepackActive() { @@ -183,6 +1080,16 @@ bool QuantRepackActive() { } void QuantRepackMatmul(Tensor& out, const Tensor& a, const Tensor& b) { + if (b.dtype == DType::kQ4_K || b.dtype == DType::kQ6_K) { + // QUANT-GGUF-CIQ-GEMM: the K-quant twins mirror the pinned oracle's + // dispatch exactly — rows <= 3 the dotprod gemv over plain q8_K rows, + // rows > 3 the i8mm 4-row gemm over BlockQ8Kx4 groups with the leftover + // rows back on the gemv. The activation quantizers are the oracle-binary + // fused-nearest_int arms (see vt/quant.h). + VT_CHECK(b.repacked, "quant_repack_matmul: weight must be repacked"); + KQuantRepackMatmul(out, a, b); + return; + } VT_CHECK(b.repacked && b.dtype == DType::kQ8_0, "quant_repack_matmul: weight must be a repacked q8_0 tensor"); const int64_t m = a.shape[0]; diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 25d401d788..4509c987c8 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -3532,6 +3532,15 @@ vllm_cpp_add_test(test_qwen3_dflash2_nvfp4 vllm/models/test_qwen3_dflash2_nvfp4. # coherently elsewhere). Reaches src/ for the block/repack/threadpool headers. vllm_cpp_add_test(test_ops_quant_repack vt/test_ops_quant_repack.cpp) target_include_directories(test_ops_quant_repack PRIVATE ${CMAKE_SOURCE_DIR}/src) +# QUANT-GGUF-CIQ-GEMM (q4k/q6k repack seam): the Q4_K/Q6_K repack twins and the +# oracle-contract (fused) Q8_K quantizer arms, pinned BYTE-FOR-BYTE to the tap +# build at llama.cpp 5f4d22289 (tests/fixtures/quant-q4k-q6k-repack-oracle- +# f32.bin, generated by docs/bench-evidence/quant-q4k-seam-20261129). Reaches +# src/ for the block/repack headers; skips coherently off aarch64 i8mm. +vllm_cpp_add_test(test_quant_repack_kq_repack vt/test_quant_repack_kq_repack.cpp) +target_include_directories(test_quant_repack_kq_repack PRIVATE ${CMAKE_SOURCE_DIR}/src) +target_compile_definitions(test_quant_repack_kq_repack PRIVATE + VLLM_CPP_SOURCE_DIR="${CMAKE_SOURCE_DIR}") # QUANT-GGUF-CIQ-GEMM-CUDA: the CUDA keep-quant GEMM (kCUDA provider for # kMatmulBTQuant). Gates the GPU dequant-in-kernel dot against the landed CPU # keep-quant oracle + an f64 dequant reference on the Q8_K family (DeepSeek-V4's diff --git a/tests/fixtures/quant-q4k-q6k-repack-oracle-f32.bin b/tests/fixtures/quant-q4k-q6k-repack-oracle-f32.bin new file mode 100644 index 0000000000..3370f0ccfc Binary files /dev/null and b/tests/fixtures/quant-q4k-q6k-repack-oracle-f32.bin differ diff --git a/tests/fixtures/quant-q4k-q6k-repack-oracle-f32.bin.idx b/tests/fixtures/quant-q4k-q6k-repack-oracle-f32.bin.idx new file mode 100644 index 0000000000..d8b4868e1a --- /dev/null +++ b/tests/fixtures/quant-q4k-q6k-repack-oracle-f32.bin.idx @@ -0,0 +1,51 @@ +q8k|blk.4.attn_output.weight 11 7008 +q8k|blk.0.attn_output.weight 7019 7008 +q8k|blk.4.attn_q.weight 14027 2920 +q8k|blk.4.attn_k.weight 16947 2920 +q8k|blk.0.ffn_gate.weight 19867 2920 +q8k4x8|k2560 22787 11680 +q8k4x8|x 34467 40960 +repk|g12|plain 75427 737280 +repk|g12|repacked 812707 737280 +repk|g14|plain 1549987 1075200 +repk|g14|repacked 2625187 1075200 +blk.4.attn_output.weight|g12|n2560|k6144|m1 3700387 34840 +blk.4.attn_output.weight|g12|n2560|k6144|m4 3735227 139288 +blk.0.attn_output.weight|g12|n2560|k6144|m1 3874515 34840 +blk.0.attn_output.weight|g12|n2560|k6144|m4 3909355 139288 +blk.4.attn_q.weight|g12|n6144|k2560|m1 4048643 34840 +blk.4.attn_q.weight|g12|n6144|k2560|m4 4083483 139288 +blk.4.attn_k.weight|g12|n512|k2560|m1 4222771 12312 +blk.4.attn_k.weight|g12|n512|k2560|m4 4235083 49176 +blk.0.ffn_gate.weight|g12|n3584|k2560|m1 4284259 24600 +blk.0.ffn_gate.weight|g12|n3584|k2560|m4 4308859 98328 +rnd|g12|n512|k2560|m1 4407187 12312 +rnd|g12|n512|k2560|m2 4419499 24600 +rnd|g12|n512|k2560|m3 4444099 36888 +rnd|g12|n512|k2560|m4 4480987 49176 +rnd|g12|n512|k2560|m5 4530163 61464 +rnd|g12|n512|k2560|m8 4591627 98328 +rnd|g12|n256|k512|m1 4689955 3096 +rnd|g12|n256|k512|m2 4693051 6168 +rnd|g12|n256|k512|m3 4699219 9240 +rnd|g12|n256|k512|m4 4708459 12312 +rnd|g12|n256|k512|m5 4720771 15384 +rnd|g12|n256|k512|m8 4736155 24600 +rnd|g14|n512|k2560|m1 4760755 12312 +rnd|g14|n512|k2560|m2 4773067 24600 +rnd|g14|n512|k2560|m3 4797667 36888 +rnd|g14|n512|k2560|m4 4834555 49176 +rnd|g14|n512|k2560|m5 4883731 61464 +rnd|g14|n512|k2560|m8 4945195 98328 +rnd|g14|n128|k512|m1 5043523 2584 +rnd|g14|n128|k512|m2 5046107 5144 +rnd|g14|n128|k512|m3 5051251 7704 +rnd|g14|n128|k512|m4 5058955 10264 +rnd|g14|n128|k512|m5 5069219 12824 +rnd|g14|n128|k512|m8 5082043 20504 +rnd|g12|n1024|k2048|m1 5102547 12312 +rnd|g12|n1024|k2048|m2 5114859 24600 +rnd|g12|n1024|k2048|m3 5139459 36888 +rnd|g12|n1024|k2048|m4 5176347 49176 +rnd|g12|n1024|k2048|m5 5225523 61464 +rnd|g12|n1024|k2048|m8 5286987 98328 diff --git a/tests/vt/test_ops_quant_repack.cpp b/tests/vt/test_ops_quant_repack.cpp index f3f80707ff..e743469335 100644 --- a/tests/vt/test_ops_quant_repack.cpp +++ b/tests/vt/test_ops_quant_repack.cpp @@ -97,13 +97,28 @@ TEST_CASE("G7 InterleaveQ8_0Rows4 matches make_block_q8_0x4 and round-trips") { } TEST_CASE("G7 repack eligibility gating is total") { - // q8_0 only, N%4==0, K%32==0, and only when the i8mm tier is live. + // q8_0: N%4==0, K%32==0; Q4_K/Q6_K (the q4k/q6k repack seam): N%8==0, + // K%256==0 — all only when the i8mm tier is live, mirroring the pinned + // oracle's repack selection (repack.cpp:5011-5017/:5052-5059 @ 5f4d22289). const bool live = vt::cpu::QuantRepackActive(); CHECK(vt::cpu::QuantRepackEligible(vt::DType::kQ8_0, 8, 64) == live); + // The Q4_K/Q6_K repack is OPT-IN (VT_CPU_QUANT_REPACK_KQ) until every + // consumer is re-proofed against the repacked class (see vt/quant.h). + CHECK_FALSE(vt::cpu::QuantRepackEligible(vt::DType::kQ4_K, 8, 256)); + CHECK_FALSE(vt::cpu::QuantRepackEligible(vt::DType::kQ6_K, 16, 512)); + if (live) { + ::setenv("VT_CPU_QUANT_REPACK_KQ", "1", 1); + CHECK(vt::cpu::QuantRepackEligible(vt::DType::kQ4_K, 8, 256)); + CHECK(vt::cpu::QuantRepackEligible(vt::DType::kQ6_K, 16, 512)); + ::unsetenv("VT_CPU_QUANT_REPACK_KQ"); + } // Never eligible regardless of the tier: - CHECK_FALSE(vt::cpu::QuantRepackEligible(vt::DType::kQ4_K, 8, 256)); // wrong dtype + CHECK_FALSE(vt::cpu::QuantRepackEligible(vt::DType::kQ3_K, 8, 256)); // no repack layout CHECK_FALSE(vt::cpu::QuantRepackEligible(vt::DType::kQ8_0, 6, 64)); // N%4!=0 CHECK_FALSE(vt::cpu::QuantRepackEligible(vt::DType::kQ8_0, 8, 48)); // K%32!=0 + CHECK_FALSE(vt::cpu::QuantRepackEligible(vt::DType::kQ4_K, 12, 256)); // N%8!=0 + CHECK_FALSE(vt::cpu::QuantRepackEligible(vt::DType::kQ4_K, 8, 384)); // K%256!=0 + CHECK_FALSE(vt::cpu::QuantRepackEligible(vt::DType::kQ6_K, 12, 512)); // N%8!=0 if (!live) { // On a non-i8mm box the transform is unreachable and must fail loud, never // silently produce a mis-laid buffer. diff --git a/tests/vt/test_quant_repack_kq_repack.cpp b/tests/vt/test_quant_repack_kq_repack.cpp new file mode 100644 index 0000000000..c3611f3b25 --- /dev/null +++ b/tests/vt/test_quant_repack_kq_repack.cpp @@ -0,0 +1,401 @@ +// QUANT-GGUF-CIQ-GEMM q4k/q6k repack seam — bit-proof gate (the shared seam). +// +// The pinned oracle (llama.cpp 5f4d22289) on a NEON+i8mm host repacks EVERY +// Q4_K and Q6_K weight with ne[1] % 8 == 0 (ggml-cpu/repack.cpp:5011-5017 +// /:5052-5059) and computes mul_mat through the repacked kernels: rows <= 3 +// the dotprod gemv ggml_gemv_{q4_K,q6_K}_8x8_q8_K, rows > 3 the i8mm 4-row +// ggml_gemm_{q4_K,q6_K}_8x8_q8_K over ggml_quantize_mat_q8_K_4x8 activations. +// Before this seam the tree's QuantRepackMatmul was Q8_0-only and every +// consumer either kept the vec_dot class (a different fp order — measured up +// to 3.5e-3 relRMS from the oracle on blk.4.attn_output) or transcribed the +// kernels model-locally (kolibri11-u3, 5838c608b). +// +// This test pins the SHARED seam byte-for-byte against the tap build's +// exported kernels (fixture generated by the scratch generator at +// docs/bench-evidence/quant-q4k-seam-20261129, tap +// /tmp/llamacpp-kolibri11-32891-build): +// +// 1. QuantizeRowQ8KFused — the oracle binary's -ffp-contract=fast +// quantize_row_q8_K_ref (the 396/7008-byte contract divergence, +// ISSUE-LOCAL-01M8M4B648PC33WK7K3ANACVVP) — must reproduce the tap's +// quantize_row_q8_K bytes exactly, while the DEFAULT from_float +// (contract=off) must DIFFER on at least one live row (the discriminating +// control; random rows coincide). +// 2. QuantizeRowQ8K4x8Fused — the tap's ggml_quantize_mat_q8_K_4x8 bytes. +// 3. QuantRepackWeight — the tap's repacked block bytes (make_block_q4_Kx8 / +// make_block_q6_Kx8), on weights synthesized from the shared LCG. +// 4. The seam end-to-end — vt::MatmulBTQuant over a repacked Q4_K/Q6_K +// weight must reproduce the tap's gemv (m<=3) and gemm (m>3) outputs +// byte-for-byte, including the m=5 mixed case (4-row gemm + gemv +// leftover), through the PRODUCTION entry point (b.repacked flag). +// +// Weights are synthesized deterministically from a shared xorshift32 LCG (the +// generator holds the identical body); leg 3 doubles as the drift tripwire. +#include "vllm/model_executor/models/dense_device_glue.h" +#include "vt/ops.h" +#include "vt/quant.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(__aarch64__) +#include +#endif + +namespace fs = std::filesystem; + +namespace { + +constexpr uint32_t kQK_K = 256; + +// Identical body to the fixture generator (docs/bench-evidence/ +// quant-q4k-seam-20261129/gen_fixture.cpp) — leg 3 catches any drift. +struct Lcg { + uint32_t s; + explicit Lcg(uint32_t seed) : s(seed) {} + uint32_t next() { + uint32_t x = s; + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + s = x; + return x; + } + uint8_t byte() { return static_cast(next() >> 24); } + void fill(uint8_t* p, size_t n) { + for (size_t i = 0; i < n; ++i) p[i] = byte(); + } +}; + +uint16_t RandF16(Lcg& lcg) { + uint16_t bits = static_cast(lcg.next() >> 16); + bits &= 0x83FF; + return bits; +} + +size_t PlainRowBytes(int gtype, int64_t k) { + const int64_t nb = k / static_cast(kQK_K); + return gtype == 12 ? static_cast(nb) * 144 : static_cast(nb) * 210; +} + +void SynthWeight(int gtype, int64_t n, int64_t k, uint32_t seed, + std::vector& w) { + w.resize(PlainRowBytes(gtype, k) * static_cast(n)); + Lcg lcg(seed); + const int64_t nb = k / static_cast(kQK_K); + size_t off = 0; + for (int64_t r = 0; r < n; ++r) { + for (int64_t b = 0; b < nb; ++b) { + if (gtype == 12) { + uint16_t d = RandF16(lcg); + std::memcpy(w.data() + off, &d, 2); + off += 2; + uint16_t dmin = RandF16(lcg); + std::memcpy(w.data() + off, &dmin, 2); + off += 2; + lcg.fill(w.data() + off, 12); + off += 12; + lcg.fill(w.data() + off, 128); + off += 128; + } else { + lcg.fill(w.data() + off, 128); + off += 128; + lcg.fill(w.data() + off, 64); + off += 64; + lcg.fill(w.data() + off, 16); + off += 16; + uint16_t d = RandF16(lcg); + std::memcpy(w.data() + off, &d, 2); + off += 2; + } + } + } +} + +struct Entry { + std::string name; + uint64_t offset; + uint64_t bytes; +}; + +std::vector LoadIndex(const std::string& idx_path) { + std::ifstream in(idx_path); + REQUIRE(in.good()); + std::vector out; + std::string line; + while (std::getline(in, line)) { + if (line.empty()) continue; + const auto sp1 = line.find(' '); + const auto sp2 = line.rfind(' '); + const bool ok = sp1 != std::string::npos && sp2 > sp1; + REQUIRE(ok); + out.push_back({line.substr(0, sp1), + std::strtoull(line.c_str() + sp1 + 1, nullptr, 10), + std::strtoull(line.c_str() + sp2 + 1, nullptr, 10)}); + } + REQUIRE(out.size() > 0); + return out; +} + +std::vector ReadAt(std::ifstream& in, const Entry& e) { + std::vector v(e.bytes); + in.clear(); + in.seekg(static_cast(e.offset)); + in.read(reinterpret_cast(v.data()), + static_cast(e.bytes)); + REQUIRE(in.gcount() == static_cast(e.bytes)); + return v; +} + +const Entry* Find(const std::vector& idx, const std::string& name) { + for (const auto& e : idx) { + if (e.name == name) return &e; + } + return nullptr; +} + +} // namespace + +TEST_CASE("quant_repack_q4k_q6k: shared seam is bit-exact to the oracle tap") { + const char* fixture_env = std::getenv("QUANT_Q4K_Q6K_FIXTURE"); + const std::string fpath = + fixture_env != nullptr && fixture_env[0] != '\0' + ? std::string(fixture_env) + : std::string(VLLM_CPP_SOURCE_DIR) + + "/tests/fixtures/quant-q4k-q6k-repack-oracle-f32.bin"; if (!fs::exists(fpath)) { + MESSAGE("SKIP: fixture missing: " << fpath); + return; + } + + // Runtime gate: this TU is baseline-march (no __ARM_FEATURE_MATMUL_INT8), + // the kernels live in the lib's per-file i8mm TU behind QuantRepackActive(). +#if !defined(__aarch64__) + MESSAGE("SKIP: seam kernels are aarch64-only"); + return; +#else + if (!vt::cpu::QuantRepackActive()) { + MESSAGE("SKIP: i8mm repack tier not live on this host"); + return; + } + // The K-quant repack eligibility is opt-in (VT_CPU_QUANT_REPACK_KQ); the + // bit-proof legs exercise the seam with it selected, as the oracle does. + ::setenv("VT_CPU_QUANT_REPACK_KQ", "1", 1); + REQUIRE(vt::cpu::QuantRepackEligible(vt::DType::kQ4_K, 8, 256)); + + std::ifstream in(fpath, std::ios::binary); + REQUIRE(in.good()); + char hdr[11]; + in.read(hdr, 11); + REQUIRE(std::memcmp(hdr, "VTQ4K6KREP1", 11) == 0); + const auto idx = LoadIndex(fpath + ".idx"); + + // ---- Leg 1: the fused Q8_K contract arm vs the tap's quantize_row_q8_K. + int fused_checked = 0; + bool default_differs = false; + for (const auto& e : idx) { + if (e.name.rfind("q8k|", 0) != 0) continue; + const auto tap = ReadAt(in, e); + // x row: the live row is k long; recover k from the tap byte count: + // 292*k/256 = 4*k/256 + k + 2*k/256 => k = tap.size() * 256 / 292. + const int64_t k = static_cast(tap.size()) * 256 / 292; + const size_t expect = static_cast(k) / 256 * 292; + REQUIRE(expect == tap.size()); + std::vector x(static_cast(k)); + // regenerate x? not stored per-leg; the fused arm is x-independent only in + // bytes... x IS needed. Reuse the stored kernel-case x instead: the leg + // pairs with the first kernel case of the same k. Simpler: the generator + // stored x in the kernel cases; find a case whose k matches and whose row + // 0 is the SAME live row (the kolibri live cases used the live row for + // m=1). Match by k and use its x row 0. + bool paired = false; + const std::string tensor_name = e.name.substr(4); + for (const auto& kc : idx) { + const auto bar = kc.name.find('|'); + if (bar == std::string::npos || kc.name.substr(0, bar) != tensor_name) { + continue; + } + // kernel case name: |g|n|k|m + size_t p = kc.name.find("|k"); + size_t q = kc.name.find("|m"); + if (p == std::string::npos || q == std::string::npos) continue; + const int64_t kk = std::atoll(kc.name.c_str() + p + 2); + const int64_t mm = std::atoll(kc.name.c_str() + q + 2); + if (kk != k || mm != 1) continue; + const auto data = ReadAt(in, kc); + int64_t dk = 0, dn = 0, dm = 0; + std::memcpy(&dk, data.data(), 8); + std::memcpy(&dn, data.data() + 8, 8); + std::memcpy(&dm, data.data() + 16, 8); + const bool dims_ok = dk == k && dm == 1; + if (!dims_ok) { FAIL("leg1 pairing failed: ", kc.name); } + REQUIRE(dims_ok); + std::memcpy(x.data(), data.data() + 24, static_cast(k) * 4); + paired = true; + break; + } + if (!paired) continue; + + std::vector fused(tap.size()); + vt::cpu::QuantizeRowQ8KFused(x.data(), fused.data(), k); + CHECK(std::memcmp(fused.data(), tap.data(), tap.size()) == 0); + ++fused_checked; + + // Discriminating control: the DEFAULT (contract=off) arm must differ on + // the live rows — the 396/7008 measured divergence. + std::vector def(tap.size()); + const auto from_float = vt::cpu::QuantTraits(vt::DType::kQ8_K).from_float; + REQUIRE(from_float != nullptr); + from_float(x.data(), def.data(), k); + for (size_t i = 0; i < tap.size(); ++i) { + if (tap[i] != def[i]) { default_differs = true; } + } + } + // The default (contract=off) arm must differ from the oracle on at least one + // live row — the measured 396/7008 contract divergence (random rows and some + // live rows coincide; the fixture must discriminate on at least one). + CHECK_MESSAGE(default_differs, + "default contract=off quantizer never differs from the oracle; " + "the fixture does not discriminate the contract arms"); + CHECK(fused_checked == 5); + + // ---- Leg 2: the fused 4x8 mat quantizer vs the tap's + // ggml_quantize_mat_q8_K_4x8. + { + const Entry* e = Find(idx, "q8k4x8|k2560"); + const Entry* ex = Find(idx, "q8k4x8|x"); + REQUIRE(e != nullptr); + REQUIRE(ex != nullptr); + const auto tap = ReadAt(in, *e); + const auto xv = ReadAt(in, *ex); + REQUIRE(xv.size() == 4 * 2560 * 4); + std::vector ours(tap.size()); + vt::cpu::QuantizeRowQ8K4x8Fused( + reinterpret_cast(xv.data()), ours.data(), 2560); + CHECK(std::memcmp(ours.data(), tap.data(), tap.size()) == 0); + } + + // ---- Leg 3: QuantRepackWeight vs the tap's repacked block bytes. + for (int g : {12, 14}) { + const std::string base = "repk|g" + std::to_string(g); + const Entry* ep = Find(idx, base + "|plain"); + const Entry* er = Find(idx, base + "|repacked"); + REQUIRE(ep != nullptr); + REQUIRE(er != nullptr); + const auto plain = ReadAt(in, *ep); + const auto repacked = ReadAt(in, *er); + const int64_t n = 512, k = 2560; + std::vector ours; + SynthWeight(g, n, k, g == 12 ? 0x4B455931u : 0x4B455932u, ours); + REQUIRE(ours.size() == plain.size()); + CHECK(std::memcmp(ours.data(), plain.data(), plain.size()) == 0); + vt::DType dt = g == 12 ? vt::DType::kQ4_K : vt::DType::kQ6_K; + vt::cpu::QuantRepackWeight(dt, ours.data(), n, k); + CHECK(std::memcmp(ours.data(), repacked.data(), repacked.size()) == 0); + } + + // ---- Leg 4: the seam end-to-end through the production entry point. + vt::Queue q{vt::DeviceType::kCPU}; + int gemv_cases = 0, gemm_cases = 0, mixed_cases = 0, plain_cases = 0; + bool plain_differs = false; + for (const auto& e : idx) { + // kernel case name: |g|n|k|m + const auto bar = e.name.find('|'); + if (bar == std::string::npos) continue; + const std::string suffix = e.name.substr(bar + 1); + if (suffix.rfind("g", 0) != 0) continue; + const auto p1 = suffix.find('|'); + const auto p2 = suffix.find('|', p1 + 1); + const auto p3 = suffix.find('|', p2 + 1); + if (p1 == std::string::npos || p2 == std::string::npos || + p3 == std::string::npos) { + continue; + } + const int gtype = std::atoi(suffix.c_str() + 1); + const int64_t n = std::atoll(suffix.c_str() + p1 + 2); + const int64_t k = std::atoll(suffix.c_str() + p2 + 2); + const int64_t m = std::atoll(suffix.c_str() + p3 + 2); + + const auto data = ReadAt(in, e); + int64_t dk = 0, dn = 0, dm = 0; + std::memcpy(&dk, data.data(), 8); + std::memcpy(&dn, data.data() + 8, 8); + std::memcpy(&dm, data.data() + 16, 8); + const bool dims_ok = dk == k && dn == n && dm == m; + REQUIRE(dims_ok); + const float* x = reinterpret_cast(data.data() + 24); + const float* y_want = x + m * k; + + std::vector w; + SynthWeight(gtype, n, k, 0x1234567u + (gtype == 12 ? 11u : 29u), w); + const vt::DType dt = gtype == 12 ? vt::DType::kQ4_K : vt::DType::kQ6_K; + REQUIRE(vt::cpu::QuantRepackEligible(dt, n, k)); + vt::cpu::QuantRepackWeight(dt, w.data(), n, k); + + vt::Tensor wt = vllm::dense_attn::MakeTensor(w.data(), dt, q.device, {n, k}); + wt.repacked = true; // the loader's flag: route through QuantRepackMatmul + vt::Tensor xt = vllm::dense_attn::MakeTensor( + const_cast(x), vt::DType::kF32, q.device, {m, k}); + std::vector got(static_cast(m) * n, 0.0f); + vt::Tensor ot = + vllm::dense_attn::MakeTensor(got.data(), vt::DType::kF32, q.device, {m, n}); + vt::MatmulBTQuant(q, ot, xt, wt); + + size_t mismatches = 0; + for (size_t i = 0; i < got.size(); ++i) { + if (std::memcmp(&got[i], &y_want[i], 4) != 0) ++mismatches; + } + if (mismatches != 0) { + const std::string msg = e.name + ": " + std::to_string(mismatches) + + "/" + std::to_string(got.size()) + + " output bytes differ"; + CHECK_MESSAGE(mismatches == 0, msg.c_str()); + } else { + CHECK(mismatches == 0); + } + if (m <= 3) ++gemv_cases; + else if (m % 4 == 0) ++gemm_cases; + else ++mixed_cases; + + // Eligibility guards: the exact pinned predicate. + CHECK(vt::cpu::QuantRepackEligible(dt, n, k)); + CHECK_FALSE(vt::cpu::QuantRepackEligible(dt, n + 1, k)); // N%8 fails + CHECK_FALSE(vt::cpu::QuantRepackEligible(dt, n, k + 128)); // K%256 fails + + // Discriminating control (m == 1 cases only): the PLAIN (unrepacked) + // vec_dot class — the pre-existing path this seam replaces — must DIFFER + // from the oracle's repacked number somewhere in the aggregate. The class + // difference is data-dependent (the kolibri comparator measured + // 1e-7..5e-7 on some ops, 3.5e-3 relRMS on others), so never per case. + if (m == 1) { + std::vector w_plain; + SynthWeight(gtype, n, k, 0x1234567u + (gtype == 12 ? 11u : 29u), w_plain); + vt::Tensor wt_plain = + vllm::dense_attn::MakeTensor(w_plain.data(), dt, q.device, {n, k}); + std::vector got_plain(static_cast(m) * n, 0.0f); + vt::Tensor ot_plain = vllm::dense_attn::MakeTensor( + got_plain.data(), vt::DType::kF32, q.device, {m, n}); + vt::MatmulBTQuant(q, ot_plain, xt, wt_plain); + for (size_t i = 0; i < got_plain.size(); ++i) { + if (std::memcmp(&got_plain[i], &y_want[i], 4) != 0) plain_differs = true; + } + ++plain_cases; + } + } + CHECK(gemv_cases > 0); + CHECK(gemm_cases > 0); + CHECK(mixed_cases > 0); + CHECK_MESSAGE(plain_differs, + "the plain vec_dot class never differs from the oracle's " + "repacked outputs; the fixture does not discriminate the " + "classes"); + CHECK(plain_cases > 0); +#endif +}