// 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; }