# tools/kernel-ab - the C++ reference half of the CPU kernel A/B (STRA-248, S0.8a) Out-of-tree measurement tooling in the pattern of `scripts/cuda-q5-oracle`, `scripts/cuda-qsa-oracle` and `scripts/cuda-projection-family-oracle`: the kernels are the **unchanged** `engine/strata` sources, built outside the tree, and every output goes to a private run directory outside Git. Nothing here is a Cargo package, nothing is linked into production, and Python is used offline only (`verify_manifest.py`, standard library, Python >= 3.9). | Path | What | | --- | --- | | `cpp/Makefile` | builds `kab` from the pin's CPU-kernel translation units and the pinned ggml with `g++`/`gcc`/`make` (below: why not CMake) | | `cpp/kab.cpp` | the driver: `gen`, internal `run-tree`, and `poolcheck` | | `cpp/avxvnni_probe.cpp` | the engine's own `STRATA_HAVE_AVXVNNI_INTRINSICS` probe, run by the Makefile | | `verify_manifest.py` | the KAB1 reader rule (exit 0 / 1 / 2) | | `smoke.sh` | build, gen, verify, negative tests, poolcheck in one command; last line `SMOKE OK` | | `cpp/kab_time.cpp` | the `time` sub-command (STRA-317); `#include`d by `kab.cpp`, one translation unit | | `aa.sh` | the C++ A/A control: N rounds of two fresh `kab time` processes, per-round ratios only (STRA-317) | | `time_smoke.sh` | STRA-317 acceptance in one command (time, verify, A/A); last line `TIME SMOKE OK` | The `time` mode (resident / streamed regimes, clock calibration, A/A control) is STRA-317 (S0.8a2): section "Timing" below. The Rust half (`examples/kernel_ab.rs`, reader, comparison, alternation) is STRA-289. ## Why a Makefile and not CMake The leaf was written as a CMake project that `add_subdirectory(engine/strata)`. The Linux server has no `cmake` (attempt 1 of the leaf stopped there). By the orchestrator's decision of 2026-10-28 (comment `49943e61` on STRA-248) the driver is built from the needed translation units with the server's `g++` 15.2.0 / `make`, in a user-space directory, with no installation, no container and no change to the host. The KAB1 contract is unchanged; only the build recipe differs. What "the flags are the engine's by construction" becomes: the Makefile transcribes the Release flags and per-file options of `engine/strata/CMakeLists.txt` and of ggml 3cf03257f's own CMake files, and `make check-pin` greps both CMake trees for every transcribed string (the five per-file option lists, `CMAKE_CXX_STANDARD 20`, `CMAKE_CXX_EXTENSIONS OFF`, Release, `GGML_NATIVE ON`, the source lists, the ggml `-march=native` / `GGML_USE_CPU_REPACK` / `_XOPEN_SOURCE` / `_GNU_SOURCE` lines, the llama.cpp `GIT_TAG`). A drift of the engine's flags makes `check-pin` fail instead of being copied silently. This is a transcription with a drift check, **not** a CMake run: a reader who needs bit-for-bit CMake provenance still has to build with CMake somewhere. Recorded in `manifest.json` (`provenance`) and printed by the build: compiler id/version/banner, target triple, the flag strings (`strata_cxx_flags`, `strata_per_file_flags`, `ggml_c_flags`, `ggml_cxx_flags`, `ggml_cpu_arch_flags`), `GGML_NATIVE=ON` (ggml-cpu is built with `-march=native` for the **build host**, so build and run on the same machine), `STRATA_PORTABLE=OFF`, `STRATA_ISA_FLOOR` empty, `STRATA_ENABLE_CUDA=OFF`, the ggml commit (pin + the checkout's actual HEAD), the `engine/strata` pin from `docs/upstream.md`, and the tools commit. The comparator flags are the **pin's CMake flags**, not those of upstream's release packaging (`docs/upstream.md`: the packaging recipes were not run here). The Makefile's `STRATA_AVXVNNI` define comes from running the engine's own probe (`cpp/avxvnni_probe.cpp`); ggml's own generated header `ggml-version.h` is regenerated from `ggml/CMakeLists.txt` and the pin. ## Commands ``` make -C tools/kernel-ab/cpp BUILD= [GGML_DIR=] # builds /kab, /build-info.txt make -C tools/kernel-ab/cpp BUILD= check-pin # drift check /kab gen --run-dir D --seed 1 --cases all # D = /kernel-ab/ python3 tools/kernel-ab/verify_manifest.py D [--ids] /kab poolcheck --run-dir D [--workers N] # stage composition vs the real ExpertPool bash tools/kernel-ab/smoke.sh # everything above, ends with SMOKE OK ``` `BUILD` must lie outside the repository (the Makefile refuses otherwise). Without `GGML_DIR` the Makefile does one shallow fetch of the pinned commit `3cf03257f219afbe7334045ff7c6a06ac68c627d` from `github.com/ggml-org/llama.cpp` into `/llama.cpp` (what `FetchContent` in `CMakeLists.txt` does) and refuses a checkout whose HEAD is not the pin. `TMPDIR` is pointed into `BUILD` so a full root file system is not touched. Run `kab` and `make` under `nice -n 19` on a machine that carries a timing job: a build is timing load (SC14). `--cases all` is 40 cases: every (gate/up, down) pair of the row-type list, gate/up in {18, 21, 22, 23, 42} x down in {20, 42}, at 1, 2, 3 and 8 tokens (one token takes the single-token dot paths; two and three take the multi-token kernels of the #152 rule; 8 is `MAXT`). `--cases ext` (STRA-329, not yet run: the C++ driver needs the pinned ggml, see the leaf) adds 72 cases and leaves the 40 of `all` untouched: the token counts 4, 5, 6 and 7 for the 10 pairs of the row-type list, and the gate/up types IQ2_XXS (16) and IQ2_XS (17) with both down types at 1..8 tokens. 16 tokens are not covered: KAB1 `rows` is 1..8 (`MAXT`). `verify_manifest.py --ids` accepts the id set of `all` or that set plus {16, 17}. `--cases gu:down:rows[,...]` selects others. Data is synthetic and the seed is informational (KAB1: inputs are always the dumped bytes). ## Contract KAB1 (normative copy of the leaf text; files only, no FFI) All integers little-endian, hashes sha256 lowercase hex, run directory `D` outside Git. * `D/case-.in` (id = `--r`): 64-byte header = `u32 magic 0x4942414B ("KABI")`, `u32 version = 1`, `i32 gu_type`, `i32 down_type` (ggml ids as `lib.rs kind()`: gate/up 18 IQ3_XXS, 21 IQ3_S, 22 IQ2_S, 23 IQ4_XS, 42 Q2_0; down 20 IQ4_NL, 42 Q2_0), `u32 rows` (1..8), `u32 n_embd = 2560`, `u32 n_ff = 640`, `u32 gate_bytes`, `u32 up_bytes`, `u32 down_bytes`, zero padding to 64; then gate bytes, up bytes, down bytes (argument order of `PreparedJob::new`), then `rows x 2560` finite f32. The file length equals the header-derived length exactly; the three byte counts equal `2560 / block_elems x block_bytes x 640` (gate, up) and `640 / block_elems x block_bytes x 2560` (down); every block's leading FP16 header is finite. * `D/case-.cpp-.out` (tree `avx512` | `avx2`): `u32 magic 0x4F42414B ("KABO")`, `u32 version = 1`, `u32 rows`, `u32 n_embd`, `u32 tree id` (0 = avx512, 1 = avx2), then `rows x 2560` f32 raw bit patterns (header = 20 bytes, no padding). The Rust writer uses `rust-` in the same positions. * `D/manifest.json`, written **last** by tmp + rename (its presence means the directory is complete): `format: "KAB1"`, `provenance` (above, plus `avx2_ok` / `avx512_ok` as computed by the default-dispatch process on this host, `trees.{avx512,avx2}` with each process's own probes and effective `STRATA_*` environment, `host_cpu_brand`, CPUID leaf 7 sub-leaf 0 and 1 registers, `strata_env_seen`), `cases[]` (id, type ids and names, rows, informational `seed`, `equality: "bitwise"`, `tolerance: null`, file names with sha256 and byte length of the `.in` and of both `.out`), and a flat `files` table `name -> {sha256, bytes}`. * Equality verdict: bitwise on the f32 bit patterns (NaN absent by construction; -0 and +0 differ). **This leaf chooses no tolerance.** A tolerance would be written into the case (`tolerance`, with its basis) before the run, by ARCHITECT/TL. * Reader rule: verify the manifest, recompute every sha256 and length, check header-derived sizes, then use; any mismatch refuses the whole directory. `verify_manifest.py`: exit 0 `OK files`; exit 1 naming the file; exit 2 `incomplete directory` (no manifest.json). It also refuses an extra or missing file, a manifest older than another file, non-finite values, and (with `--ids`) an id set other than {18, 20, 21, 22, 23, 42}. The two trees are two **processes**: `kab gen` runs itself twice with every `STRATA_*` / `LELEKA_*` variable scrubbed, `avx512` with nothing set and `avx2` with only `STRATA_FORCE_AVX2=1` (`expert_layout.cpp cpu_avx512_ok()` reads it once per process). If the host has no AVX-512, `avx512_ok` is recorded `false` and the two trees are identical by construction. ## Stage composition (parent AC7 / this leaf's AC6) `kab` computes nothing itself. `compose_expert()` in `cpp/kab.cpp` calls the stage entry points declared in `engine/strata/include/strata/kernels/cpu/native_expert.hpp` (`native_fmt` line 49, `native_quant_act` line 52, `native_quant_h` line 54, `native_gu_rows` line 60, `native_down_rows` line 63) and the Q2_0 kernels of `expert_layout.hpp` (`q2_native_kernels` line 81, `q2_rows_any`, `act_quant_any`), in the order and with the branches the engine's pool uses for one routed expert over `nt` tokens: | Step | Engine C++ (pin, `engine/strata`) | `kab.cpp` | | --- | --- | --- | | layer format | `crates/native-cpu-expert/src/miss_abi.cpp:91` `native_fmt(gu, down, H, FF, ...)` | `format_for()` (also asserts the engine's `up_off` / `bytes - down_off` equal the KAB1 sizes) | | quantize each token | `miss_abi.cpp:108-109`: `gu_type == 42 ? act_quant_any : native_quant_act` | first loop of `compose_expert()` | | gate/up rows + SwiGLU | `src/kernels/cpu/pool.cpp:1219-1234` (mode 5): `q2_native_kernels(gu)` -> two `q2_rows_any` + `(g / (1.f + std::exp(-g))) * u` (line 1230), else `native_gu_rows` | same branch, rows [0, 640) | | quantize the hidden | `pool.cpp:1374-1375` (`run_split_multi_native`): `q2_native_kernels(d) ? act_quant_any : native_quant_h` | second loop | | down rows | `pool.cpp:1235-1244` (mode 6): `q2_native_kernels(d)` -> `q2_rows_any`, else `native_down_rows` | same branch, rows [0, 2560) | Rows are independent in every kernel, so splitting the row range across the pool's threads does not change a bit; `kab poolcheck` checks exactly that on every case by running the **real** `ExpertPool::run_split_multi_native` (miss_abi's sequence, 1 and 4 workers) and comparing bitwise with `compose_expert()` in the same process and tree (see the smoke output). The Rust side the A/B compares against: `DirectCpuPool::compute_group` (`crates/native-cpu-expert/src/lib.rs:155`) -> `ffi::NativePool::compute_borrowed` -> `rust_pool.rs:134` `compute_borrowed` (token quantization line 155: `f.gu == 42` -> `q8_one_*`, else `q8_k`) -> `run_published` (`rust_pool.rs:109-113`: `phase(5, ...)` gate/up + `silu`, hidden requantization, `phase(6, ...)`; the row kernels are lines 62-72). Same stage order and same branch keys (`gu == 42` / `down == 42`) as the engine C++ above. **Not shown**: that the Rust arithmetic is bit-equal to the C++; that is the A/B itself (STRA-289). In this tree the Rust crate no longer calls `miss_abi.cpp` (`ffi.rs`: "Closed Rust replacement for the former C++ miss ABI"); `miss_abi.cpp` is read here only as the engine-side description of the sequence. For one `PreparedJob`-shaped group (one expert, `rows` tokens, pairs `(t, 0)`, stride 1) the Rust job has `rows` tokens per expert, which is the C++ `ExpertJobMulti.nt`; the dispatch keys on `nt` (`mt_min`, #152), so the case's `rows` is the token count of the A/B cell. ## Not covered here * Rust reader, comparison, alternation: STRA-289; the Rust `time` mode: STRA-318. MSVC build: STRA-255. The A/A class (slower/equal/faster): STRA-313. * Row types outside the KAB1 list (the K-quants, NVFP4, the trellis types, IQ1_*): not generated. IQ2_XXS / IQ2_XS only in `--cases ext`. * CMake itself was not run (see above). `GGML_NATIVE=ON` ties the ggml-cpu half to the build host's CPU. ## Timing (`kab time`, `aa.sh`; STRA-317 / S0.8a2) ``` /kab time --run-dir D --case --slices N --pin --out F.json [--slice-ms 60] [--regime both|resident|streamed] [--llc-bytes B] bash tools/kernel-ab/aa.sh D # env: E2E_ROOT, KAB, AA_CELL=avx512|avx2, AA_SLICES, AA_SLICE_MS, AA_OUT bash tools/kernel-ab/time_smoke.sh # time + verify_manifest + A/A (TS_ROUNDS shortens the A/A) ``` The command line is the same as the Rust half's (STRA-318), so one runner can alternate both programs. `D` is never written to (`verify_manifest.py D` still prints `OK` after a run); `F.json` and the A/A output go next to it, outside the repository. * **What is timed.** One routed expert for the case's `rows` tokens: the activation quantization, the gate/up rows + SwiGLU, the hidden quantization and the down rows, i.e. the stage sequence of `compose_expert()` (same code path, kernels unchanged) with all scratch pre-allocated. `selfcheck_bitwise_equal_compose_expert` in the output proves, before any slice, that its output equals the reference composition's on the resident copy and the first/last streamed copy. Pool = 1 worker: one thread, pinned with `sched_setaffinity` to `--pin` (verified with `sched_getcpu` before every slice; a migrated slice makes the run exit 3). Buffers and scratch are 4096-aligned. * **Regimes** (both in one run by default, labelled `RESIDENT` / `STREAMED` in `regimes[]`): RESIDENT cycles one copy of the expert; STREAMED cycles K distinct 4096-aligned copies with K x stride >= 2 x the last-level cache of the pinned CPU, read at run time from `/sys/devices/system/cpu/cpu/cache/index*/size` (the highest-level data/unified cache; `--llc-bytes` overrides and is recorded). The factor 2 is a design choice recorded in the file, not a drop threshold. STREAMED does one untimed pass over all copies first. * **Slices.** Each slice runs calls for `--slice-ms` (default 60, `tq_cpu_parity.cpp:461`), at least 2, and records monotonic ns (`CLOCK_MONOTONIC`) and TSC ticks (lfence-serialised `rdtsc`) per call, plus the dependent-add core-clock calibration before and after. * **Dropped slices.** The method and the constant are `tq_cpu_parity --bench`'s: `core_ghz()` (`tq_cpu_parity.cpp` lines 273-284) and `time_slice()` (lines 290-304); a slice is dropped when `std::fabs(g1 - g0) > 0.05 * g0`, i.e. the clock moved by more than 5 percent (**`engine/strata/src/kernels/cpu/tq_cpu_parity.cpp`, line 303**, copied, no new threshold). `slices[]` holds the kept slices, `dropped[]` the dropped ones, `dropped_count` and `slices_kept` the counts; the median of the kept slices is in `median_ns_per_call` / `median_tsc_per_call`. * **Recorded in `F.json`**: `manifest_sha256` and the case's `input_sha256` (checked against the manifest before use; a mismatch refuses the run), `tree` (`avx512` | `avx2`, from `cpu_avx512_ok()`) with its probes, `effective_env` (every `STRATA_*` / `LELEKA_*` variable the process saw), the pin (CPU, `thread_siblings_list`, sibling CPU, the sibling's and the pin's busy fraction from `/proc/stat` over the run, governor, boost, load average at start and end), `clock_calibration` (method, the cited drop rule with file and line, GHz at start and end, `tsc_invariant`), and the build record of `kab`. * **The runner scrubs the environment**, not `kab time`: `aa.sh` removes every `STRATA_*` and `LELEKA_*` variable and sets only what the cell needs (`AA_CELL=avx2` sets `STRATA_FORCE_AVX2=1`, which `expert_layout.cpp cpu_avx512_ok()` honours; the default cell `avx512` sets nothing). * **Exit codes**: 0 ok; 1 usage / refused input; 3 a regime kept no slice, or a slice migrated off the pin; 4 the final output differs from the reference. * **A/A (`aa.sh`).** A seeded schedule (balanced a-first / b-first, SplitMix64 Fisher-Yates) is written to `schedule.tsv` before the first run; each round runs two fresh `kab time` processes in that order; `ratios.tsv` holds exactly `` data lines (`#` lines are comments) with, per regime, the ratio of the median slice ns of process b over process a. No verdict and no class: the A/A class belongs to the S0.10b classifier (STRA-313). * **Noise.** On a shared host the numbers are not evidence by themselves; every record carries the load average and the SMT sibling's busy fraction. The leaf's acceptance is correctness (builds, runs, shape of the records), not a timing claim.