diff --git a/tools/kernel-ab/README.md b/tools/kernel-ab/README.md
index d0cd499c..a799fbbd 100644
--- a/tools/kernel-ab/README.md
+++ b/tools/kernel-ab/README.md
@@ -12,8 +12,11 @@ production, and Python is used offline only (`verify_manifest.py`, standard libr
| `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, A/A, clock calibration) is **not** here: it is STRA-317 (S0.8a2).
+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
@@ -122,6 +125,45 @@ the C++ `ExpertJobMulti.nt`; the dispatch keys on `nt` (`mt_min`, #152), so the
## Not covered here
-* Timing, A/A, clock calibration, regimes: STRA-317. Rust reader, comparison, alternation: STRA-289. MSVC build: STRA-255.
+* 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, IQ2_XXS / IQ2_XS / IQ1_*): not generated.
* 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.
diff --git a/tools/kernel-ab/aa.sh b/tools/kernel-ab/aa.sh
new file mode 100755
index 00000000..83b556c7
--- /dev/null
+++ b/tools/kernel-ab/aa.sh
@@ -0,0 +1,144 @@
+#!/usr/bin/env bash
+# tools/kernel-ab/aa.sh - STRA-317 (S0.8a2): the C++ A/A control of the CPU kernel A/B timing.
+#
+# bash tools/kernel-ab/aa.sh D
+#
+# D a KAB1 run directory written by `kab gen` (STRA-248); never written to (an extra file would make verify_manifest.py refuse it)
+# case case id, e.g. 18-20-r1
+# rounds number of rounds (30 for the A/A control of the plan)
+# seed integer; writes the order schedule BEFORE the first run (balanced: half of the rounds "a first", half "b first", shuffled by the seed)
+# cpu the logical CPU both processes are pinned to (a physical core whose SMT sibling is idle)
+#
+# One round = two FRESH `kab time` processes of the SAME binary, labelled a and b, run one after the other in the scheduled order,
+# both pinned to , STRATA_* / LELEKA_* scrubbed from their environment (the cell avx2 sets only STRATA_FORCE_AVX2=1). Per round
+# and regime the ratio is median slice ns of b / median slice ns of a (the same statistic the Rust/C++ comparison uses). Only the
+# ratios are written: NO verdict and no class (the A/A class is computed later by the S0.10b classifier, STRA-313).
+#
+# Output (default: next to D, never inside it): /aa---s/
+# schedule.tsv written first: roundfirst (a|b)pincell
+# rounds/rNN-a.json, rNN-b.json the full `kab time` records
+# ratios.tsv "#" comment lines (the column header is one of them), then EXACTLY data lines:
+# round first ratio_resident ratio_streamed median_ns_a_resident median_ns_b_resident median_ns_a_streamed median_ns_b_streamed
+# kept_a_resident kept_b_resident kept_a_streamed kept_b_streamed dropped_total
+#
+# Environment: KAB (binary; default $E2E_ROOT/build/kernel-ab/kab) E2E_ROOT (default $HOME/work/leleka-e2e)
+# AA_CELL avx512|avx2 (default avx512) AA_SLICES (default 50) AA_SLICE_MS (default: kab's 60) AA_OUT (output dir)
+# PYTHON (default python3; stdlib only, offline arithmetic and JSON reading)
+# CPU only, no GPU, nothing installed. Timing taken on a shared host is noisy and is not evidence by itself: each record carries the
+# load average and the SMT sibling's busy fraction.
+set -euo pipefail
+
+if [ "$#" -ne 5 ]; then
+ echo "usage: bash tools/kernel-ab/aa.sh D " >&2
+ exit 2
+fi
+d="${1%/}"; cas="$2"; rounds="$3"; seed="$4"; cpu="$5"
+here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+repo="$(cd "${here}/../.." && pwd)"
+root="${E2E_ROOT:-${HOME}/work/leleka-e2e}"
+kab="${KAB:-${root}/build/kernel-ab/kab}"
+cell="${AA_CELL:-avx512}"
+slices="${AA_SLICES:-50}"
+py="${PYTHON:-python3}"
+export PYTHONDONTWRITEBYTECODE=1
+
+case "${rounds}" in ''|*[!0-9]*) echo "aa.sh: rounds must be a positive integer" >&2; exit 2;; esac
+case "${seed}" in ''|*[!0-9]*) echo "aa.sh: seed must be a non-negative integer" >&2; exit 2;; esac
+case "${cpu}" in ''|*[!0-9]*) echo "aa.sh: cpu must be a logical CPU number" >&2; exit 2;; esac
+[ "${rounds}" -ge 1 ] || { echo "aa.sh: rounds must be >= 1" >&2; exit 2; }
+case "${cell}" in avx512|avx2) ;; *) echo "aa.sh: AA_CELL must be avx512 or avx2" >&2; exit 2;; esac
+[ -f "${d}/manifest.json" ] || { echo "aa.sh: ${d} has no manifest.json (not a complete KAB1 run directory)" >&2; exit 2; }
+[ -f "${d}/case-${cas}.in" ] || { echo "aa.sh: ${d}/case-${cas}.in does not exist" >&2; exit 2; }
+[ -x "${kab}" ] || { echo "aa.sh: ${kab} is not an executable (build with make -C tools/kernel-ab/cpp BUILD=...)" >&2; exit 2; }
+
+dabs="$(cd "${d}" && pwd)"
+out="${AA_OUT:-$(dirname "${dabs}")/aa-$(basename "${dabs}")-${cas}-s${seed}}"
+case "${out}/" in "${repo}/"*) echo "aa.sh: output directory ${out} is inside the repository" >&2; exit 1;; esac
+case "${out}/" in "${dabs}/"*) echo "aa.sh: output directory ${out} is inside the KAB1 run directory" >&2; exit 1;; esac
+[ ! -e "${out}" ] || { echo "aa.sh: ${out} exists; remove it or set AA_OUT" >&2; exit 1; }
+mkdir -p "${out}/rounds"
+
+# ---- the schedule, written BEFORE the first run -------------------------------------------------------------------------------
+"${py}" -I - "${rounds}" "${seed}" "${cpu}" "${cell}" > "${out}/schedule.tsv" <<'PY'
+import sys
+rounds, seed, cpu, cell = int(sys.argv[1]), int(sys.argv[2]), sys.argv[3], sys.argv[4]
+M = (1 << 64) - 1
+state = seed & M
+def nxt(): # SplitMix64: the same sequence on every host and Python version
+ global state
+ state = (state + 0x9E3779B97F4A7C15) & M
+ z = state
+ z = ((z ^ (z >> 30)) * 0xBF58476D1CE4E5B9) & M
+ z = ((z ^ (z >> 27)) * 0x94D049BB133111EB) & M
+ return z ^ (z >> 31)
+order = ["a"] * ((rounds + 1) // 2) + ["b"] * (rounds // 2) # balanced
+for i in range(len(order) - 1, 0, -1): # Fisher-Yates
+ j = nxt() % (i + 1)
+ order[i], order[j] = order[j], order[i]
+print("# seed=%d rounds=%d (balanced: %d a-first, %d b-first)" % (seed, rounds, order.count("a"), order.count("b")))
+print("round\tfirst\tpin\tcell")
+for r, f in enumerate(order, 1):
+ print("%d\t%s\t%s\t%s" % (r, f, cpu, cell))
+PY
+echo "aa: schedule written to ${out}/schedule.tsv"
+
+# ---- the scrubbed environment of the cell -------------------------------------------------------------------------------------
+scrub=()
+while IFS= read -r v; do scrub+=(-u "$v"); done < <(compgen -e | grep -E '^(STRATA_|LELEKA_)' || true)
+cellenv=()
+[ "${cell}" = "avx2" ] && cellenv=(STRATA_FORCE_AVX2=1)
+extra=()
+[ -z "${AA_SLICE_MS:-}" ] || extra=(--slice-ms "${AA_SLICE_MS}")
+
+run_one() { #
+ local r label f
+ r="$(printf '%02d' "$1")"; label="$2"; f="${out}/rounds/r${r}-${label}.json"
+ env ${scrub[@]+"${scrub[@]}"} ${cellenv[@]+"${cellenv[@]}"} "${kab}" time --run-dir "${dabs}" --case "${cas}" --slices "${slices}" --pin "${cpu}" \
+ --out "${f}" ${extra[@]+"${extra[@]}"} > "${out}/rounds/r${r}-${label}.log" 2>&1 \
+ || { echo "aa.sh: round ${r} process ${label} failed:" >&2; cat "${out}/rounds/r${r}-${label}.log" >&2; exit 1; }
+}
+
+while IFS=$'\t' read -r r first _; do
+ case "${r}" in '#'*|round) continue;; esac
+ second=b; [ "${first}" = "b" ] && second=a
+ run_one "${r}" "${first}"
+ run_one "${r}" "${second}"
+ printf 'aa: round %s done (%s first)\n' "${r}" "${first}"
+done < "${out}/schedule.tsv"
+
+# ---- the ratios (arithmetic only) -----------------------------------------------------------------------------------------------
+"${py}" -I - "${out}" "${rounds}" "${cas}" "${cell}" "${cpu}" "${slices}" > "${out}/ratios.tsv" <<'PY'
+import json, sys
+out, rounds, cas, cell, cpu, slices = sys.argv[1], int(sys.argv[2]), sys.argv[3], sys.argv[4], sys.argv[5], sys.argv[6]
+sched = {}
+for line in open(out + "/schedule.tsv"):
+ if line.startswith("#") or line.startswith("round"):
+ continue
+ p = line.rstrip("\n").split("\t")
+ sched[int(p[0])] = p[1]
+def regimes(path):
+ d = json.load(open(path))
+ r = {x["regime"]: x for x in d["regimes"]}
+ return d, r["RESIDENT"], r["STREAMED"]
+print("# KAB1 A/A (C++ vs C++), STRA-317. ratio = median slice ns of process b / process a, per regime. NO verdict and no class here (S0.10b, STRA-313).")
+print("# case=%s cell=%s pin=%s slices_per_regime=%s rounds=%d" % (cas, cell, cpu, slices, rounds))
+print("# round\tfirst\tratio_resident\tratio_streamed\tmedian_ns_a_resident\tmedian_ns_b_resident\tmedian_ns_a_streamed\tmedian_ns_b_streamed\t"
+ "kept_a_resident\tkept_b_resident\tkept_a_streamed\tkept_b_streamed\tdropped_total")
+for r in range(1, rounds + 1):
+ da, ra, sa = regimes("%s/rounds/r%02d-a.json" % (out, r))
+ db, rb, sb = regimes("%s/rounds/r%02d-b.json" % (out, r))
+ for x in (ra, rb, sa, sb):
+ if not x["slices_kept"]:
+ sys.exit("round %d: a regime has no kept slice" % r)
+ dropped = ra["dropped_count"] + rb["dropped_count"] + sa["dropped_count"] + sb["dropped_count"]
+ print("%d\t%s\t%.6f\t%.6f\t%.3f\t%.3f\t%.3f\t%.3f\t%d\t%d\t%d\t%d\t%d" % (
+ r, sched[r], rb["median_ns_per_call"] / ra["median_ns_per_call"], sb["median_ns_per_call"] / sa["median_ns_per_call"],
+ ra["median_ns_per_call"], rb["median_ns_per_call"], sa["median_ns_per_call"], sb["median_ns_per_call"],
+ ra["slices_kept"], rb["slices_kept"], sa["slices_kept"], sb["slices_kept"], dropped))
+PY
+n="$(grep -vc "^#" "${out}/ratios.tsv" || true)"
+data="${n}"
+[ "${data}" = "${rounds}" ] || { echo "aa.sh: ratios.tsv has ${data} data lines, expected ${rounds}" >&2; exit 1; }
+echo "--- ratios.tsv (${data} per-round ratios; no verdict) ---"
+cat "${out}/ratios.tsv"
+echo "AA OK rounds=${data} out=${out}"
diff --git a/tools/kernel-ab/cpp/Makefile b/tools/kernel-ab/cpp/Makefile
index 1ee04e4e..ec1cf17b 100644
--- a/tools/kernel-ab/cpp/Makefile
+++ b/tools/kernel-ab/cpp/Makefile
@@ -130,7 +130,8 @@ $(BUILD)/libstrata_kernels_cpu.a: $(KOBJ)
rm -f $@ && ar rcs $@ $^
# ---- the driver ----------------------------------------------------------------------------------------------------------
-$(BUILD)/kab.o: kab.cpp $(GG)/include/ggml.h | $(BUILD)/dirs.stamp
+# kab_time.cpp (STRA-317, the `time` sub-command) is #included by kab.cpp: one translation unit
+$(BUILD)/kab.o: kab.cpp kab_time.cpp $(GG)/include/ggml.h | $(BUILD)/dirs.stamp
$(CXX) $(STRATA_CXX_FLAGS) $(STRATA_INC) -MMD -MP -Wall -Wextra -c $< -o $@
$(BUILD)/kab: $(BUILD)/kab.o $(BUILD)/libstrata_kernels_cpu.a $(BUILD)/libggml-cpu.a $(BUILD)/libggml-base.a
$(CXX) -O3 $< -o $@ -L$(BUILD) -lstrata_kernels_cpu -lggml-cpu -lggml-base -pthread -lm
diff --git a/tools/kernel-ab/cpp/kab.cpp b/tools/kernel-ab/cpp/kab.cpp
index 7f633232..225820ab 100644
--- a/tools/kernel-ab/cpp/kab.cpp
+++ b/tools/kernel-ab/cpp/kab.cpp
@@ -5,6 +5,7 @@
// D/case-.cpp-{avx512,avx2}.out, then manifest.json LAST
// kab run-tree --run-dir D --tree avx512|avx2 (internal) one tree's .out files; prints one JSON probe line
// kab poolcheck --run-dir D [--workers N] stage composition vs the real ExpertPool (bitwise), same process
+// kab time --run-dir D --case ID --slices N --pin CPU --out F.json STRA-317: timing, resident + streamed regimes (cpp/kab_time.cpp)
//
// The kernels are engine/strata's, UNCHANGED, built by ../cpp/Makefile. Nothing here is kernel arithmetic: the driver only
// COMPOSES the stage entry points of include/strata/kernels/cpu/native_expert.hpp (+ the Q2_0 kernels of expert_layout.hpp)
@@ -18,6 +19,9 @@
#include
#include
#include
+#include // STRA-317 (time mode): sched_setaffinity / sched_getcpu
+#include // clock_gettime
+#include // __rdtsc, _mm_lfence
#include
#include
#include
@@ -623,18 +627,22 @@ int cmd_gen(const Args& a, const std::string& exe) {
return 0;
}
+// STRA-317 (S0.8a2): the `time` sub-command lives in kab_time.cpp, included here so it shares this file's reader and composition
+#define KAB_TIME_INCLUDED_FROM_KAB 1
+#include "kab_time.cpp"
+
} // namespace
int main(int argc, char** argv) {
- if (argc < 2) die("usage: kab gen|run-tree|poolcheck ...");
+ if (argc < 2) die("usage: kab gen|run-tree|poolcheck|time ...");
const std::string cmd = argv[1];
const Args a = parse(argc, argv, 2);
- if (cmd == "gen") {
+ if (cmd == "gen" || cmd == "time") {
char self[4096];
const ssize_t n = readlink("/proc/self/exe", self, sizeof self - 1);
if (n <= 0) die("cannot resolve /proc/self/exe");
self[n] = 0;
- return cmd_gen(a, self);
+ return cmd == "gen" ? cmd_gen(a, self) : cmd_time(a, self);
}
if (cmd == "run-tree") return cmd_run_tree(a);
if (cmd == "poolcheck") return cmd_poolcheck(a);
diff --git a/tools/kernel-ab/cpp/kab_time.cpp b/tools/kernel-ab/cpp/kab_time.cpp
new file mode 100644
index 00000000..b33a39e3
--- /dev/null
+++ b/tools/kernel-ab/cpp/kab_time.cpp
@@ -0,0 +1,489 @@
+// tools/kernel-ab/cpp/kab_time.cpp - STRA-317 (S0.8a2): the `time` sub-command of the C++ reference driver `kab`.
+//
+// kab time --run-dir D --case ID --slices N --pin CPU --out F.json [--slice-ms 60] [--regime both|resident|streamed]
+// [--llc-bytes B] [--build-info FILE]
+//
+// The SAME command line the Rust half (STRA-318) implements, so one runner alternates both programs. One case of a KAB1 run
+// directory (written by `kab gen`, STRA-248) is timed in two regimes, both labelled in F.json:
+// RESIDENT one expert repeated (the case's blob, in cache after the first call);
+// STREAMED K distinct copies of the blob cycled, K x expert bytes above the last-level cache size read at run time from the
+// pinned CPU's sysfs cache table (the decode miss case: every call streams its weights from DRAM).
+// Per slice: monotonic ns (CLOCK_MONOTONIC), TSC ticks (lfence-serialised rdtsc), and a dependent-add core-clock calibration
+// before and after the slice (the method of engine/strata/src/kernels/cpu/tq_cpu_parity.cpp --bench: core_ghz(), lines 273-284,
+// and time_slice(), lines 290-304). A slice whose calibrated clock moved is DROPPED (not averaged in) with the threshold copied
+// from that file, no new threshold:
+// engine/strata/src/kernels/cpu/tq_cpu_parity.cpp:303 `std::fabs(g1 - g0) > 0.05 * g0` (5 percent)
+// The slice length (60 ms) is copied from the same file, line 461 (`slice_ms = quick ? 40 : 60`).
+//
+// This file is textually included at the end of the anonymous namespace of kab.cpp (one translation unit), so it shares the
+// KAB1 reader (`load_case`, validated before use), the stage entry points and `compose_expert()` (the reference composition)
+// with `gen`/`poolcheck`. The timed composition below is the same stage sequence with pre-allocated scratch (no allocation in
+// the timed loop); `selfcheck` compares its output bitwise with `compose_expert()` before any slice is taken.
+//
+// Pool = 1 worker: one thread, pinned to --pin; rows are independent in every kernel, so one thread over the whole row range is
+// bitwise the engine pool's output for any worker count (poolcheck, STRA-248). Buffers are 4096-aligned. The effective
+// STRATA_* / LELEKA_* environment is recorded as seen; the RUNNER (aa.sh, or the Rust alternator) scrubs it and sets only what the
+// cell needs (the cell avx2 sets STRATA_FORCE_AVX2=1, which cpu_avx512_ok() in expert_layout.cpp honours).
+#ifndef KAB_TIME_INCLUDED_FROM_KAB
+#error "kab_time.cpp is part of kab.cpp's translation unit: it is #included by kab.cpp, not compiled alone"
+#endif
+
+// ------------------------------------------------------------------------------------------------------------------------
+// clocks
+uint64_t mono_ns() {
+ timespec ts;
+ clock_gettime(CLOCK_MONOTONIC, &ts);
+ return (uint64_t) ts.tv_sec * 1000000000ull + (uint64_t) ts.tv_nsec;
+}
+inline uint64_t tsc_now() { // serialised on both sides so the read is neither hoisted into nor sunk out of the slice
+ _mm_lfence();
+ const uint64_t t = __rdtsc();
+ _mm_lfence();
+ return t;
+}
+// tq_cpu_parity.cpp:273-284 core_ghz(): a chain of dependent adds runs at one per cycle (GCC / Clang on x86-64)
+double core_ghz() {
+ uint64_t x = 0;
+ const long n = 1000000;
+ const double t0 = (double) mono_ns() * 1e-3; // us, as now_us() there
+ for (long i = 0; i < n; ++i) __asm__ volatile("add $1, %0\n\tadd $1, %0\n\tadd $1, %0\n\tadd $1, %0" : "+r"(x));
+ return 4.0 * n / (((double) mono_ns() * 1e-3 - t0) * 1e3);
+}
+constexpr double kClockMovedFraction = 0.05; // tq_cpu_parity.cpp:303 std::fabs(g1 - g0) > 0.05 * g0
+constexpr int kClockMovedSourceLine = 303;
+constexpr double kDefaultSliceMs = 60.0; // tq_cpu_parity.cpp:461 slice_ms = quick ? 40 : 60
+constexpr size_t kAlign = 4096;
+
+// ------------------------------------------------------------------------------------------------------------------------
+// sysfs / procfs facts about the pin
+std::string read_text(const std::string& path) {
+ FILE* f = std::fopen(path.c_str(), "r");
+ if (!f) return "";
+ char b[1024];
+ const size_t n = std::fread(b, 1, sizeof b - 1, f);
+ std::fclose(f);
+ std::string s(b, n);
+ while (!s.empty() && (s.back() == '\n' || s.back() == '\r' || s.back() == ' ')) s.pop_back();
+ return s;
+}
+std::vector parse_cpu_list(const std::string& s) { // "2,18" or "2-3" or "0-3,8"
+ std::vector v;
+ size_t at = 0;
+ while (at < s.size()) {
+ size_t comma = s.find(',', at);
+ if (comma == std::string::npos) comma = s.size();
+ const std::string tok = s.substr(at, comma - at);
+ const size_t dash = tok.find('-');
+ if (dash == std::string::npos) v.push_back(std::atoi(tok.c_str()));
+ else for (int c = std::atoi(tok.substr(0, dash).c_str()); c <= std::atoi(tok.substr(dash + 1).c_str()); ++c) v.push_back(c);
+ at = comma + 1;
+ }
+ return v;
+}
+uint64_t parse_size(const std::string& s) { // "98304K" "32M" "1G" "512"
+ char* end = nullptr;
+ const unsigned long long v = std::strtoull(s.c_str(), &end, 10);
+ uint64_t mul = 1;
+ if (end && (*end == 'K' || *end == 'k')) mul = 1024ull;
+ else if (end && (*end == 'M' || *end == 'm')) mul = 1024ull * 1024;
+ else if (end && (*end == 'G' || *end == 'g')) mul = 1024ull * 1024 * 1024;
+ return (uint64_t) v * mul;
+}
+struct Llc { int level = 0; uint64_t bytes = 0; std::string type; std::string source; };
+Llc llc_of_cpu(int cpu) { // the highest-level data/unified cache of the pinned CPU
+ Llc best;
+ for (int i = 0; i < 16; ++i) {
+ const std::string d = "/sys/devices/system/cpu/cpu" + std::to_string(cpu) + "/cache/index" + std::to_string(i);
+ const std::string lv = read_text(d + "/level"), ty = read_text(d + "/type"), sz = read_text(d + "/size");
+ if (lv.empty() || sz.empty() || ty == "Instruction") continue;
+ if (std::atoi(lv.c_str()) >= best.level) {
+ best.level = std::atoi(lv.c_str());
+ best.bytes = parse_size(sz);
+ best.type = ty;
+ best.source = d + "/size = " + sz;
+ }
+ }
+ return best;
+}
+struct CpuJiffies { uint64_t busy = 0, total = 0; bool ok = false; };
+CpuJiffies proc_stat_cpu(int cpu) {
+ CpuJiffies j;
+ const std::string want = "cpu" + std::to_string(cpu) + " ";
+ FILE* f = std::fopen("/proc/stat", "r");
+ if (!f) return j;
+ char line[512];
+ while (std::fgets(line, sizeof line, f)) {
+ if (std::strncmp(line, want.c_str(), want.size()) != 0) continue;
+ unsigned long long v[10] = {0};
+ std::sscanf(line + want.size(), "%llu %llu %llu %llu %llu %llu %llu %llu %llu %llu", &v[0], &v[1], &v[2], &v[3], &v[4], &v[5], &v[6], &v[7], &v[8], &v[9]);
+ uint64_t tot = 0;
+ for (int i = 0; i < 8; ++i) tot += v[i]; // user nice system idle iowait irq softirq steal (guest is inside user)
+ j.total = tot;
+ j.busy = tot - v[3] - v[4];
+ j.ok = true;
+ break;
+ }
+ std::fclose(f);
+ return j;
+}
+std::string loadavg() { return read_text("/proc/loadavg"); }
+
+std::string fmt_d(const char* f, double v) {
+ char b[64];
+ if (!std::isfinite(v)) return "null";
+ std::snprintf(b, sizeof b, f, v);
+ return b;
+}
+double median_of(std::vector v) { // the reference's median(): sorted, element size/2
+ if (v.empty()) return 0.0;
+ std::sort(v.begin(), v.end());
+ return v[v.size() / 2];
+}
+
+// ------------------------------------------------------------------------------------------------------------------------
+// aligned buffers
+struct Aligned {
+ void* p = nullptr;
+ size_t n = 0;
+ Aligned() = default;
+ explicit Aligned(size_t bytes) { reset(bytes); }
+ void reset(size_t bytes) {
+ std::free(p);
+ n = (bytes + kAlign - 1) / kAlign * kAlign;
+ p = std::aligned_alloc(kAlign, n);
+ if (!p) die("allocation of " + std::to_string(n) + " bytes failed");
+ std::memset(p, 0, n);
+ }
+ ~Aligned() { std::free(p); }
+ Aligned(const Aligned&) = delete;
+ Aligned& operator=(const Aligned&) = delete;
+ template T* as() const { return (T*) p; }
+};
+
+// ------------------------------------------------------------------------------------------------------------------------
+// The timed expert: compose_expert()'s stage sequence with all scratch pre-allocated (see the header).
+struct TimedExpert {
+ NativeFmt f;
+ int nt = 0;
+ const float* x = nullptr;
+ std::vector act, a2;
+ Aligned nact, hq, ff, g, u, out;
+ const void* nactp[MAXT];
+ const void* hqp[MAXT];
+ const ActQ* actp[MAXT];
+ const ActQ* a2p[MAXT];
+ float* ffp[MAXT];
+ float* outp[MAXT];
+ float* gp[MAXT];
+ float* up[MAXT];
+ bool q2_gu = false, q2_down = false;
+
+ void init(const NativeFmt& fmt, const float* x_, int nt_) {
+ f = fmt; x = x_; nt = nt_;
+ act.resize((size_t) nt); a2.resize((size_t) nt);
+ nact.reset((size_t) nt * kNativeActBytes);
+ hq.reset((size_t) nt * kNativeHBytes);
+ ff.reset((size_t) nt * FF * 4); g.reset((size_t) nt * FF * 4); u.reset((size_t) nt * FF * 4);
+ out.reset((size_t) nt * H * 4);
+ q2_gu = q2_native_kernels(f.gu_type);
+ q2_down = q2_native_kernels(f.d_type);
+ for (int t = 0; t < nt; ++t) {
+ nactp[t] = nact.as() + (size_t) t * kNativeActBytes;
+ hqp[t] = hq.as() + (size_t) t * kNativeHBytes;
+ actp[t] = &act[(size_t) t];
+ a2p[t] = &a2[(size_t) t];
+ ffp[t] = ff.as() + (size_t) t * FF;
+ gp[t] = g.as() + (size_t) t * FF;
+ up[t] = u.as() + (size_t) t * FF;
+ outp[t] = out.as() + (size_t) t * H;
+ }
+ }
+ void run(const uint8_t* blob) { // same order, branches and arithmetic as compose_expert() in kab.cpp
+ for (int t = 0; t < nt; ++t) {
+ if (f.gu_type == 42) act_quant_any(x + (size_t) t * H, H, act[(size_t) t]);
+ else native_quant_act(f, x + (size_t) t * H, (uint8_t*) nactp[t]);
+ }
+ if (q2_gu) {
+ const int nbk = (int) (f.n_embd / 64);
+ q2_rows_any(blob, f.gu_row, nbk, actp, nt, gp, 0, FF);
+ q2_rows_any(blob + f.up_off, f.gu_row, nbk, actp, nt, up, 0, FF);
+ for (int t = 0; t < nt; ++t)
+ for (int r = 0; r < FF; ++r) ffp[t][r] = (gp[t][r] / (1.f + std::exp(-gp[t][r]))) * up[t][r];
+ } else {
+ native_gu_rows(f, blob, nactp, nt, ffp, 0, FF);
+ }
+ for (int t = 0; t < nt; ++t) {
+ if (q2_down) act_quant_any(ffp[t], FF, a2[(size_t) t]);
+ else native_quant_h(f, ffp[t], (void*) hqp[t]);
+ }
+ if (q2_down) q2_rows_any(blob + f.down_off, f.d_row, (int) (f.n_ff / 64), a2p, nt, outp, 0, H);
+ else native_down_rows(f, blob, hqp, nt, outp, 0, H);
+ }
+};
+
+// ------------------------------------------------------------------------------------------------------------------------
+struct Slice {
+ double ns_per_call = 0, tsc_per_call = 0, ghz_before = 0, ghz_after = 0, ghz_mean = 0, cycles_per_call = 0, tsc_per_ns = 0;
+ int calls = 0;
+ uint64_t wall_ns = 0;
+ bool moved = false;
+};
+
+// one slice of `ms` milliseconds cycling over the copies; the shape of tq_cpu_parity.cpp time_slice() (lines 290-304)
+Slice time_slice(TimedExpert& te, const std::vector& copies, double ms, size_t& next) {
+ Slice s;
+ s.ghz_before = core_ghz();
+ int it = 0;
+ const uint64_t ns0 = mono_ns();
+ const uint64_t c0 = tsc_now();
+ uint64_t ns1 = ns0;
+ do {
+ te.run(copies[next++ % copies.size()]);
+ ++it;
+ ns1 = mono_ns();
+ } while ((double) (ns1 - ns0) < ms * 1e6 || it < 2);
+ const uint64_t c1 = tsc_now();
+ s.ghz_after = core_ghz();
+ s.calls = it;
+ s.wall_ns = ns1 - ns0;
+ s.ns_per_call = (double) (ns1 - ns0) / it;
+ s.tsc_per_call = (double) (c1 - c0) / it;
+ s.tsc_per_ns = (double) (c1 - c0) / (double) (ns1 - ns0);
+ s.ghz_mean = 0.5 * (s.ghz_before + s.ghz_after);
+ s.cycles_per_call = s.ns_per_call * s.ghz_mean;
+ s.moved = s.ghz_mean > 0 && std::fabs(s.ghz_after - s.ghz_before) > kClockMovedFraction * s.ghz_before; // tq_cpu_parity.cpp:303
+ return s;
+}
+
+std::string slice_json(const Slice& s, int idx) {
+ return "{\"i\": " + std::to_string(idx) + ", \"calls\": " + std::to_string(s.calls) + ", \"wall_ns\": " + std::to_string(s.wall_ns) +
+ ", \"ns_per_call\": " + fmt_d("%.3f", s.ns_per_call) + ", \"tsc_per_call\": " + fmt_d("%.3f", s.tsc_per_call) +
+ ", \"tsc_per_ns\": " + fmt_d("%.6f", s.tsc_per_ns) + ", \"ghz_before\": " + fmt_d("%.6f", s.ghz_before) +
+ ", \"ghz_after\": " + fmt_d("%.6f", s.ghz_after) + ", \"cycles_per_call\": " + fmt_d("%.1f", s.cycles_per_call) + "}";
+}
+
+struct RegimeResult {
+ std::string json;
+ size_t kept = 0;
+ bool ok = false;
+};
+
+RegimeResult run_regime(const char* label, TimedExpert& te, const std::vector& copies, size_t expert_bytes, size_t stride,
+ const Llc& llc, uint64_t llc_used, int nslices, double slice_ms, int pin, bool selfcheck_ok) {
+ size_t next = 0;
+ // warm-up (not recorded): tables, buffers, and for STREAMED one full pass over the copies so every page is mapped and resident
+ for (int i = 0; i < 3; ++i) te.run(copies[next++ % copies.size()]);
+ if (copies.size() > 1)
+ for (size_t i = 0; i < copies.size(); ++i) te.run(copies[next++ % copies.size()]);
+ std::vector kept, dropped;
+ std::vector kept_idx, dropped_idx;
+ int migrated = 0;
+ for (int i = 0; i < nslices; ++i) {
+ const int cpu_before = sched_getcpu();
+ Slice s = time_slice(te, copies, slice_ms, next);
+ if (cpu_before != pin || sched_getcpu() != pin) ++migrated;
+ if (s.moved) { dropped.push_back(s); dropped_idx.push_back(i); }
+ else { kept.push_back(s); kept_idx.push_back(i); }
+ }
+ std::vector ns, tsc, cyc;
+ for (const Slice& s : kept) { ns.push_back(s.ns_per_call); tsc.push_back(s.tsc_per_call); cyc.push_back(s.cycles_per_call); }
+ RegimeResult r;
+ r.kept = kept.size();
+ r.ok = !kept.empty() && migrated == 0;
+ std::string j = "{\"regime\": " + jstr(label) + ", \"copies_k\": " + std::to_string(copies.size()) + ", \"expert_bytes\": " + std::to_string(expert_bytes) +
+ ", \"copy_stride_bytes\": " + std::to_string(stride) + ", \"working_set_bytes\": " + std::to_string(expert_bytes * copies.size()) +
+ ", \"llc_level\": " + std::to_string(llc.level) + ", \"llc_bytes\": " + std::to_string(llc.bytes) + ", \"llc_source\": " + jstr(llc.source) +
+ ", \"working_set_over_llc\": " + (copies.size() > 1 ? "true" : "false") + ", \"slice_ms\": " + fmt_d("%.1f", slice_ms) +
+ ", \"slices_requested\": " + std::to_string(nslices) + ", \"slices_kept\": " + std::to_string(kept.size()) + ", \"dropped_count\": " +
+ std::to_string(dropped.size()) + ", \"selfcheck_bitwise_equal_compose_expert\": " + (selfcheck_ok ? "true" : "false") +
+ ", \"migrated_slices\": " + std::to_string(migrated) + ", \"median_ns_per_call\": " + (kept.empty() ? "null" : fmt_d("%.3f", median_of(ns))) +
+ ", \"median_tsc_per_call\": " + (kept.empty() ? "null" : fmt_d("%.3f", median_of(tsc))) + ", \"median_cycles_per_call\": " +
+ (kept.empty() ? "null" : fmt_d("%.1f", median_of(cyc))) + ",\n \"slices\": [";
+ (void) llc_used;
+ for (size_t i = 0; i < kept.size(); ++i) j += (i ? ",\n " : "\n ") + slice_json(kept[i], kept_idx[i]);
+ j += "],\n \"dropped\": [";
+ for (size_t i = 0; i < dropped.size(); ++i) j += (i ? ",\n " : "\n ") + slice_json(dropped[i], dropped_idx[i]);
+ j += "]}";
+ r.json = j;
+ return r;
+}
+
+// the manifest's record of one file: "": {"sha256": "<64 hex>", ...}
+std::string manifest_sha_of(const std::string& manifest_text, const std::string& name) {
+ const std::string key = "\"" + name + "\": {\"sha256\": \"";
+ const size_t at = manifest_text.find(key);
+ if (at == std::string::npos) return "";
+ const size_t b = at + key.size();
+ return manifest_text.substr(b, 64);
+}
+
+int cmd_time(const Args& a, const std::string& exe) {
+ const std::string dir = a.get("run-dir"), id = a.get("case"), out_path = a.get("out");
+ if (dir.empty() || id.empty() || out_path.empty() || !a.has("slices") || !a.has("pin"))
+ die("usage: kab time --run-dir D --case ID --slices N --pin CPU --out F.json [--slice-ms 60] [--regime both|resident|streamed] [--llc-bytes B]");
+ const int nslices = std::atoi(a.get("slices").c_str());
+ const int pin = std::atoi(a.get("pin").c_str());
+ const double slice_ms = std::atof(a.get("slice-ms", "60").c_str());
+ const std::string regime = a.get("regime", "both");
+ if (nslices < 1 || nslices > 100000) die("--slices must be 1..100000");
+ if (pin < 0 || !(a.get("pin").find_first_not_of("0123456789") == std::string::npos)) die("--pin must be a logical CPU number");
+ if (slice_ms < 1.0 || slice_ms > 10000.0) die("--slice-ms must be 1..10000");
+ if (regime != "both" && regime != "resident" && regime != "streamed") die("--regime must be both, resident or streamed");
+ if (!cpu_avx2_ok()) die("this CPU has no AVX2: the engine would not run its experts here");
+
+ // ---- pin first (before any buffer is touched), physical-core facts, sibling baseline
+ cpu_set_t set;
+ CPU_ZERO(&set);
+ CPU_SET(pin, &set);
+ if (sched_setaffinity(0, sizeof set, &set) != 0) die("sched_setaffinity(" + std::to_string(pin) + "): " + std::strerror(errno));
+ if (sched_getcpu() != pin) die("the process is not running on CPU " + std::to_string(pin) + " after sched_setaffinity");
+ const std::string cpu_dir = "/sys/devices/system/cpu/cpu" + std::to_string(pin);
+ const std::string sib_text = read_text(cpu_dir + "/topology/thread_siblings_list");
+ const std::vector siblings = parse_cpu_list(sib_text);
+ int sibling = -1;
+ for (int c : siblings) if (c != pin) sibling = c;
+ const CpuJiffies sib0 = sibling >= 0 ? proc_stat_cpu(sibling) : CpuJiffies();
+ const CpuJiffies pin0 = proc_stat_cpu(pin);
+ const std::string load0 = loadavg();
+ const uint64_t wall0 = mono_ns();
+
+ // ---- the case: KAB1 reader rule (validate, then use), manifest and case input hashes
+ const std::string mpath = dir + "/manifest.json";
+ const std::vector mraw = read_file(mpath);
+ const std::string manifest_sha = sha_of(mraw);
+ const std::string mtext(mraw.begin(), mraw.end());
+ if (mtext.find("\"format\": \"KAB1\"") == std::string::npos) die(mpath + ": not a KAB1 manifest");
+ const std::string in_name = "case-" + id + ".in";
+ const std::vector inraw = read_file(dir + "/" + in_name);
+ const std::string in_sha = sha_of(inraw);
+ const std::string want_sha = manifest_sha_of(mtext, in_name);
+ if (want_sha.empty()) die(in_name + " is not listed in the manifest");
+ if (want_sha != in_sha) die(in_name + ": sha256 differs from the manifest (the directory is refused; run verify_manifest.py)");
+ Loaded l = load_case(dir + "/" + in_name);
+ NativeFmt f;
+ if (!format_for(l.c, f)) return 2;
+ const size_t expert_bytes = l.blob.size();
+ if (l.blob.size() != 2 * gu_bytes(*fmt_of(l.c.gu)) + down_bytes(*fmt_of(l.c.down))) die("blob size differs from the KAB1 sizes");
+
+ // ---- environment, tree, build record
+ const std::map env = env_matching(environ);
+ const bool tree_avx512 = cpu_avx512_ok();
+ const std::string tree = tree_avx512 ? "avx512" : "avx2";
+ std::string bi_path = a.get("build-info");
+ if (bi_path.empty()) {
+ const size_t slash = exe.rfind('/');
+ bi_path = (slash == std::string::npos ? std::string(".") : exe.substr(0, slash)) + "/build-info.txt";
+ }
+ const std::map bi = read_build_info(bi_path);
+ auto g = [&](const char* k) { auto it = bi.find(k); return it == bi.end() ? std::string("unknown") : it->second; };
+
+ // ---- streamed set size: K copies, K x expert bytes above the LLC of the pinned CPU
+ Llc llc = llc_of_cpu(pin);
+ if (a.has("llc-bytes")) { llc.bytes = std::strtoull(a.get("llc-bytes").c_str(), nullptr, 10); llc.source = "--llc-bytes (override)"; }
+ if (llc.bytes == 0) die("cannot read the last-level cache size of CPU " + std::to_string(pin) + " from sysfs; pass --llc-bytes");
+ const size_t stride = (expert_bytes + kAlign - 1) / kAlign * kAlign;
+ constexpr uint64_t kStreamFactor = 2; // working set >= 2 x LLC: strictly above the LLC with margin (a design choice, recorded; not a drop threshold)
+ const size_t k_streamed = (size_t) ((kStreamFactor * llc.bytes) / stride) + 1;
+ if (k_streamed * stride > (4ull << 30)) die("the streamed working set would exceed 4 GiB; check --llc-bytes");
+
+ // ---- reference output and the timed expert
+ std::vector want((size_t) l.c.rows * H, 0.f);
+ compose_expert(f, l.blob.data(), l.x.data(), l.c.rows, want.data());
+ Aligned xin(l.x.size() * 4);
+ std::memcpy(xin.p, l.x.data(), l.x.size() * 4);
+ TimedExpert te;
+ te.init(f, xin.as(), l.c.rows);
+
+ // RESIDENT: one aligned copy. STREAMED: K aligned copies in one mapping (page-touched by the copy itself).
+ Aligned res(stride), stm(stride * k_streamed);
+ std::memcpy(res.p, l.blob.data(), expert_bytes);
+ for (size_t k = 0; k < k_streamed; ++k) std::memcpy(stm.as() + k * stride, l.blob.data(), expert_bytes);
+ std::vector res_copies = {res.as()}, stm_copies;
+ for (size_t k = 0; k < k_streamed; ++k) stm_copies.push_back(stm.as() + k * stride);
+
+ // selfcheck: the timed composition's output on every copy is bitwise compose_expert()'s
+ bool selfcheck = true;
+ for (const uint8_t* b : {res_copies[0], stm_copies.front(), stm_copies.back()}) {
+ te.run(b);
+ selfcheck = selfcheck && std::memcmp(te.out.p, want.data(), want.size() * 4) == 0;
+ }
+ if (!selfcheck) die("selfcheck failed: the timed composition differs from compose_expert()");
+
+ const double ghz0 = core_ghz(); // calibration at the start of the run (also recorded per slice)
+ std::vector regimes;
+ bool all_ok = true;
+ size_t kept_res = 0, kept_stm = 0;
+ if (regime != "streamed") {
+ RegimeResult r = run_regime("RESIDENT", te, res_copies, expert_bytes, stride, llc, expert_bytes, nslices, slice_ms, pin, selfcheck);
+ regimes.push_back(r.json);
+ all_ok = all_ok && r.ok;
+ kept_res = r.kept;
+ }
+ if (regime != "resident") {
+ RegimeResult r = run_regime("STREAMED", te, stm_copies, expert_bytes, stride, llc, expert_bytes * k_streamed, nslices, slice_ms, pin, selfcheck);
+ regimes.push_back(r.json);
+ all_ok = all_ok && r.ok;
+ kept_stm = r.kept;
+ }
+ const double ghz1 = core_ghz();
+ // the last output is still the reference (nothing in the loop changes the data)
+ te.run(res_copies[0]);
+ const bool final_same = std::memcmp(te.out.p, want.data(), want.size() * 4) == 0;
+
+ // ---- host facts after the run
+ const CpuJiffies sib1 = sibling >= 0 ? proc_stat_cpu(sibling) : CpuJiffies();
+ const CpuJiffies pin1 = proc_stat_cpu(pin);
+ const uint64_t wall1 = mono_ns();
+ auto busy_frac = [](const CpuJiffies& x, const CpuJiffies& y) -> std::string {
+ if (!x.ok || !y.ok || y.total <= x.total) return "null";
+ return fmt_d("%.4f", (double) (y.busy - x.busy) / (double) (y.total - x.total));
+ };
+ unsigned ea = 0, eb = 0, ec = 0, ed = 0;
+ __cpuid(0x80000007u, ea, eb, ec, ed);
+ const bool invariant_tsc = (ed >> 8) & 1;
+
+ std::string j = "{\n \"format\": \"KAB1-time\",\n \"version\": 1,\n \"mode\": \"time\",\n \"writer\": \"cpp\",\n";
+ j += " \"command_line\": " + jstr("time --run-dir " + dir + " --case " + id + " --slices " + std::to_string(nslices) + " --pin " + std::to_string(pin) +
+ " --out " + out_path + (a.has("slice-ms") ? " --slice-ms " + a.get("slice-ms") : "") +
+ (a.has("regime") ? " --regime " + regime : "")) + ",\n";
+ j += " \"run_dir\": " + jstr(dir) + ",\n \"manifest_sha256\": " + jstr(manifest_sha) + ",\n \"case\": {\"id\": " + jstr(id) + ", \"gu_type\": " +
+ std::to_string(l.c.gu) + ", \"down_type\": " + std::to_string(l.c.down) + ", \"gu_name\": " + jstr(fmt_of(l.c.gu)->name) + ", \"down_name\": " +
+ jstr(fmt_of(l.c.down)->name) + ", \"rows\": " + std::to_string(l.c.rows) + ", \"input_file\": " + jstr(in_name) + ", \"input_sha256\": " +
+ jstr(in_sha) + ", \"input_sha256_matches_manifest\": true, \"expert_bytes\": " + std::to_string(expert_bytes) + "},\n";
+ j += " \"tree\": " + jstr(tree) + ",\n \"tree_detail\": " + probe_json(tree.c_str()) + ",\n \"effective_env\": " + env_json(env) + ",\n";
+ j += " \"pool\": {\"workers\": 1, \"threads\": 1, \"note\": \"one thread over the whole row range, bitwise the engine pool's output for any worker count (poolcheck)\"},\n";
+ j += " \"pin\": {\"cpu\": " + std::to_string(pin) + ", \"thread_siblings_list\": " + jstr(sib_text) + ", \"sibling_cpu\": " +
+ (sibling >= 0 ? std::to_string(sibling) : "null") + ", \"physical_core_id\": " + jstr(read_text(cpu_dir + "/topology/core_id")) +
+ ", \"pin_busy_fraction_during_run\": " + busy_frac(pin0, pin1) + ", \"sibling_busy_fraction_during_run\": " + (sibling >= 0 ? busy_frac(sib0, sib1) : "null") +
+ ", \"sibling_busy_note\": \"/proc/stat jiffies of the sibling logical CPU between the start and the end of this process; it is recorded, no threshold is applied here\"" +
+ ", \"scaling_governor\": " + jstr(read_text(cpu_dir + "/cpufreq/scaling_governor")) + ", \"cpufreq_boost\": " +
+ jstr(read_text("/sys/devices/system/cpu/cpufreq/boost")) + ", \"loadavg_start\": " + jstr(load0) + ", \"loadavg_end\": " + jstr(loadavg()) +
+ ", \"final_cpu\": " + std::to_string(sched_getcpu()) + "},\n";
+ j += " \"buffers\": {\"alignment_bytes\": " + std::to_string(kAlign) + ", \"expert_copy_stride_bytes\": " + std::to_string(stride) +
+ ", \"activations_aligned\": true, \"scratch_aligned\": true},\n";
+ j += " \"clock_calibration\": {\"method\": \"chain of dependent adds, 1000000 iterations of 4 adds, ghz = 4e6 / (elapsed ns); before and after every slice\", " +
+ std::string("\"source\": \"engine/strata/src/kernels/cpu/tq_cpu_parity.cpp --bench: core_ghz() lines 273-284, time_slice() lines 290-304\", ") +
+ "\"drop_rule\": {\"source_file\": \"engine/strata/src/kernels/cpu/tq_cpu_parity.cpp\", \"source_line\": " + std::to_string(kClockMovedSourceLine) +
+ ", \"source_text\": \"std::fabs(g1 - g0) > 0.05 * g0\", \"fraction\": " + fmt_d("%.2f", kClockMovedFraction) +
+ ", \"meaning\": \"a slice whose calibrated clock moved by more than 5 percent between its before and after calibration is dropped\"}, " +
+ "\"slice_ms_source\": \"tq_cpu_parity.cpp:461 slice_ms = quick ? 40 : 60\", \"ghz_at_start\": " + fmt_d("%.6f", ghz0) + ", \"ghz_at_end\": " +
+ fmt_d("%.6f", ghz1) + ", \"tsc_invariant\": " + (invariant_tsc ? "true" : "false") + ", \"clocks\": \"CLOCK_MONOTONIC ns; lfence-serialised rdtsc ticks\"},\n";
+ j += " \"build\": {\"build_info_file\": " + jstr(bi_path) + ", \"tools_commit\": " + jstr(g("tools_commit")) + ", \"compiler_banner\": " + jstr(g("compiler_banner")) +
+ ", \"engine_strata_pin\": " + jstr(g("engine_strata_pin")) + ", \"ggml_commit\": " + jstr(g("ggml_commit")) + ", \"strata_cxx_flags\": " +
+ jstr(g("strata_cxx_flags")) + ", \"strata_per_file_flags\": " + jstr(g("strata_per_file_flags")) + ", \"ggml_cpu_arch_flags\": " +
+ jstr(g("ggml_cpu_arch_flags")) + "},\n";
+ j += " \"selfcheck_bitwise_equal_compose_expert\": " + std::string(selfcheck ? "true" : "false") + ",\n \"final_output_unchanged\": " +
+ (final_same ? "true" : "false") + ",\n \"duration_ns\": " + std::to_string(wall1 - wall0) + ",\n";
+ j += " \"timing_caveat\": \"numbers from a shared host are not evidence by themselves; loadavg and the sibling busy fraction are recorded above\",\n";
+ j += " \"regimes\": [\n ";
+ for (size_t i = 0; i < regimes.size(); ++i) j += (i ? ",\n " : "") + regimes[i];
+ j += "\n ]\n}\n";
+ // tmp + rename so a reader never sees a half-written file
+ write_file(out_path + ".tmp", j.data(), j.size());
+ if (rename((out_path + ".tmp").c_str(), out_path.c_str()) != 0) die("rename of " + out_path + " failed");
+ std::printf("kab time: case=%s tree=%s pin=%d slices=%d resident_kept=%zu streamed_kept=%zu K=%zu out=%s\n", id.c_str(), tree.c_str(), pin, nslices,
+ kept_res, kept_stm, k_streamed, out_path.c_str());
+ if (!all_ok) { std::fprintf(stderr, "kab time: a regime has no kept slice or a slice migrated off CPU %d\n", pin); return 3; }
+ if (!final_same) { std::fprintf(stderr, "kab time: the final output differs from the reference\n"); return 4; }
+ return 0;
+}
diff --git a/tools/kernel-ab/time_smoke.sh b/tools/kernel-ab/time_smoke.sh
new file mode 100755
index 00000000..bae05aad
--- /dev/null
+++ b/tools/kernel-ab/time_smoke.sh
@@ -0,0 +1,63 @@
+#!/usr/bin/env bash
+# tools/kernel-ab/time_smoke.sh - STRA-317 acceptance in one command: `kab time`, verify_manifest.py, aa.sh. Last line `TIME SMOKE OK`.
+#
+# E2E_ROOT run root (default $HOME/work/leleka-e2e; on rnr5090 the root file system is full: E2E_ROOT=/data/leleka-e2e)
+# KAB the built driver (default $E2E_ROOT/build/kernel-ab/kab; build with smoke.sh or make -C tools/kernel-ab/cpp BUILD=...)
+# KAB_RUN a KAB1 run directory written by `kab gen` (default $E2E_ROOT/runs/kernel-ab/final); it is only read
+# TS_CASE (18-20-r1) TS_PIN (cpu number, default 9) TS_SLICES (50) TS_ROUNDS (A/A rounds, default 30) TS_SEED (default 20261028)
+# TS_RUN_ID output directory name under $E2E_ROOT/runs/kernel-ab-time/ (default time-)
+# CPU only. Timing numbers from a shared host are noisy and are not evidence by themselves.
+set -euo pipefail
+here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+repo="$(cd "${here}/../.." && pwd)"
+root="${E2E_ROOT:-${HOME}/work/leleka-e2e}"
+kab="${KAB:-${root}/build/kernel-ab/kab}"
+d="${KAB_RUN:-${root}/runs/kernel-ab/final}"
+cas="${TS_CASE:-18-20-r1}"; pin="${TS_PIN:-9}"; slices="${TS_SLICES:-50}"; rounds="${TS_ROUNDS:-30}"; seed="${TS_SEED:-20261028}"
+py="${PYTHON:-python3}"
+out="${root}/runs/kernel-ab-time/${TS_RUN_ID:-time-$(date -u +%Y%m%dT%H%M%SZ)}"
+case "${out}/" in "${repo}/"*) echo "time_smoke: output ${out} is inside the repository" >&2; exit 1;; esac
+mkdir -p "${out}"
+export PYTHONDONTWRITEBYTECODE=1
+step() { printf '\n==== %s ====\n' "$*"; }
+
+step "AC1 kab time: resident + streamed, ${slices} slices, pin ${pin}"
+"${kab}" time --run-dir "${d}" --case "${cas}" --slices "${slices}" --pin "${pin}" --out "${out}/t.json"
+"${py}" -I - "${out}/t.json" "${slices}" "${pin}" <<'PY'
+import json, sys
+d = json.load(open(sys.argv[1])); n = int(sys.argv[2]); pin = int(sys.argv[3])
+assert d["format"] == "KAB1-time" and d["mode"] == "time" and d["writer"] == "cpp"
+assert len(d["manifest_sha256"]) == 64 and len(d["case"]["input_sha256"]) == 64 and d["case"]["input_sha256_matches_manifest"]
+assert d["tree"] in ("avx512", "avx2") and isinstance(d["effective_env"], dict)
+assert d["pin"]["cpu"] == pin and "thread_siblings_list" in d["pin"] and d["pool"]["workers"] == 1
+cal = d["clock_calibration"]; rule = cal["drop_rule"]
+assert rule["source_file"].endswith("tq_cpu_parity.cpp") and rule["source_line"] == 303 and rule["fraction"] == 0.05
+assert d["selfcheck_bitwise_equal_compose_expert"] and d["final_output_unchanged"]
+names = [r["regime"] for r in d["regimes"]]
+assert names == ["RESIDENT", "STREAMED"], names
+for r in d["regimes"]:
+ assert r["slices_requested"] == n and r["slices_kept"] + r["dropped_count"] == n
+ assert len(r["slices"]) == r["slices_kept"] and len(r["dropped"]) == r["dropped_count"] and r["slices_kept"] > 0
+ for s in r["slices"] + r["dropped"]:
+ for k in ("ns_per_call", "tsc_per_call", "ghz_before", "ghz_after"):
+ assert s[k] > 0, (r["regime"], s)
+ print("%-8s K=%-3d kept=%d dropped=%d working_set=%d llc=%d median_ns=%.0f" % (r["regime"], r["copies_k"], r["slices_kept"], r["dropped_count"],
+ r["working_set_bytes"], r["llc_bytes"], r["median_ns_per_call"]))
+st = d["regimes"][1]; assert st["working_set_bytes"] > st["llc_bytes"] and d["regimes"][0]["copies_k"] == 1
+print("t.json shape OK")
+PY
+
+step "AC2 verify_manifest.py after the run (the dump is untouched)"
+"${py}" "${here}/verify_manifest.py" "${d}"
+
+step "AC3 the cited drop threshold exists"
+sed -n '303p' "${repo}/engine/strata/src/kernels/cpu/tq_cpu_parity.cpp"
+sed -n '303p' "${repo}/engine/strata/src/kernels/cpu/tq_cpu_parity.cpp" | grep -q 'std::fabs(g1 - g0) > 0.05 \* g0'
+
+step "AC3 aa.sh ${d} ${cas} ${rounds} ${seed} ${pin}"
+AA_OUT="${out}/aa" E2E_ROOT="${root}" KAB="${kab}" bash "${here}/aa.sh" "${d}" "${cas}" "${rounds}" "${seed}" "${pin}"
+n="$(grep -vc '^#' "${out}/aa/ratios.tsv" || true)"
+echo "ratios.tsv data lines: ${n}"
+[ "${n}" = "${rounds}" ]
+"${py}" "${here}/verify_manifest.py" "${d}"
+echo "TIME SMOKE OK"