kernel_ab alternate: calibration chain that LLVM cannot fold, Rust cells without pool spin, per-record sibling_idle and clock bounds, rustc version fallback

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-10-28 21:25:56 +01:00
co-authored by Claude Sonnet 5.5
parent e80528ac7a
commit 6d1adfa78c
+49 -27
View File
@@ -1024,14 +1024,14 @@ fn sibling_idle(cpu: usize) -> bool {
}
fn rustc_info() -> (String, String) {
let rustc = std::env::var("RUSTC").unwrap_or_else(|_| "rustc".to_owned());
// $RUSTC, then `rustc` on the PATH, then the rustup shim of the user (a non-login shell has no cargo bin directory on its PATH)
let home = std::env::var("HOME").or_else(|_| std::env::var("USERPROFILE")).unwrap_or_default();
let shim = format!("{home}/.cargo/bin/{}", if cfg!(windows) { "rustc.exe" } else { "rustc" });
let candidates = [std::env::var("RUSTC").unwrap_or_else(|_| "rustc".to_owned()), "rustc".to_owned(), shim];
let triple = if cfg!(windows) { "x86_64-pc-windows-msvc" } else { "x86_64-unknown-linux-gnu" };
let version = Command::new(rustc)
.arg("--version")
.output()
.ok()
.filter(|o| o.status.success())
.and_then(|o| String::from_utf8(o.stdout).ok())
let version = candidates
.iter()
.find_map(|rustc| Command::new(rustc).arg("--version").output().ok().filter(|o| o.status.success()).and_then(|o| String::from_utf8(o.stdout).ok()))
.map_or_else(|| "unknown (rustc not runnable at record time)".to_owned(), |s| s.trim().to_owned());
(version, triple.to_owned())
}
@@ -1221,31 +1221,33 @@ const CLOCK_MOVED_FRACTION: f64 = 0.05;
/// An SMT sibling busier than this fraction is not idle (the 5 percent rule of `sibling_idle`).
const SIBLING_BUSY_LIMIT: f64 = 0.05;
const ALIGN: usize = 4096;
/// Latency of a dependent 64-bit multiply in cycles on every core the A/B runs on (Intel Skylake to Golden Cove, AMD Zen 1 to 5).
const MUL_LATENCY_CYCLES: f64 = 3.0;
const CLOCK_METHOD: &str = "chain of dependent 64-bit multiplies (latency 3 cycles), 1000000 iterations of 4, ghz = 3 * 4e6 / (elapsed ns); before and after every slice";
/// Cycles of one step of the calibration chain `x = (x * k) ^ (x >> 17)`: a 64-bit multiply (3 cycles on Intel Skylake to Golden Cove
/// and AMD Zen 1 to 5) then an xor (1 cycle); the shift runs beside the multiply.
const CHAIN_STEP_CYCLES: f64 = 4.0;
const CLOCK_METHOD: &str = "chain of dependent steps x = (x * k) ^ (x >> 17), 4 cycles per step (3 multiply + 1 xor), 1000000 iterations of 4 steps, ghz = 4 * 4e6 / (elapsed ns); before and after every slice";
fn mono_ns() -> u64 {
static ORIGIN: OnceLock<Instant> = OnceLock::new();
ORIGIN.get_or_init(Instant::now).elapsed().as_nanos() as u64
}
/// The core clock in GHz from a chain of dependent multiplies (safe code: the C++ chain of dependent adds needs inline assembly). The
/// constant is opaque to the optimiser, so the four multiplies per iteration stay four dependent instructions.
/// The core clock in GHz from a chain of dependent steps (safe code: the C++ chain of dependent adds needs inline assembly). A plain
/// chain of multiplies by an opaque constant is folded by LLVM (measured: 175 GHz), so every step also xors in a shifted copy of the
/// running value, which no reassociation can remove.
fn core_ghz() -> f64 {
let k = std::hint::black_box(0x9E37_79B9_7F4A_7C15u64 | 1);
let mut x = std::hint::black_box(1u64);
let n = 1_000_000u64;
let t0 = mono_ns();
for _ in 0..n {
x = x.wrapping_mul(k);
x = x.wrapping_mul(k);
x = x.wrapping_mul(k);
x = x.wrapping_mul(k);
x = x.wrapping_mul(k) ^ (x >> 17);
x = x.wrapping_mul(k) ^ (x >> 17);
x = x.wrapping_mul(k) ^ (x >> 17);
x = x.wrapping_mul(k) ^ (x >> 17);
}
let dt = mono_ns().saturating_sub(t0).max(1);
std::hint::black_box(x);
MUL_LATENCY_CYCLES * 4.0 * n as f64 / dt as f64
CHAIN_STEP_CYCLES * 4.0 * n as f64 / dt as f64
}
fn median_of(v: &[f64]) -> f64 {
@@ -1863,8 +1865,10 @@ fn procs_for(trees: &[&'static str]) -> Vec<Proc> {
v
}
/// The environment a cell needs and nothing else: the Rust cells keep the pool from re-pinning its caller (the pin is the requested
/// one); the avx2 trees set `STRATA_FORCE_AVX2=1`, which both implementations honour.
/// The environment a cell needs and nothing else. The avx2 trees set `STRATA_FORCE_AVX2=1`, which both implementations honour. The
/// Rust cells run `DirectCpuPool::new(1)`, a worker thread plus the draining caller, both confined to the one pinned CPU: the pool must
/// not re-pin its caller (`LELEKA_CPU_POOL_PIN_HOST=off`, so the pin is the requested one) and its worker must not spin after a batch
/// (`STRATA_POOL_SPIN_US=0`; with the 20 ms default the worker spins on the caller's only CPU and costs it half its time).
fn cell_env(p: &Proc) -> Vec<(String, String)> {
let mut v = Vec::new();
if p.tree == "avx2" {
@@ -1872,6 +1876,7 @@ fn cell_env(p: &Proc) -> Vec<(String, String)> {
}
if p.imp == Impl::Rust {
v.push(("LELEKA_CPU_POOL_PIN_HOST".to_owned(), "off".to_owned()));
v.push(("STRATA_POOL_SPIN_US".to_owned(), "0".to_owned()));
}
v.sort();
v
@@ -2236,8 +2241,10 @@ fn round_records(ctx: &BatchCtx, round_no: u32, done: &[ProcOut]) -> Result<Vec<
let c = ctx.case;
let cpp_tool = Tool { compiler: p.compiler_id.clone(), version: p.compiler_version.clone(), triple: p.target_triple.clone(), flags: p.reference_flags.clone() };
let (gu, down) = (gate_up_row(c.gu).map_or("?", |x| x.4), down_row(c.down).map_or("?", |x| x.4));
let sibling_idle = done.iter().all(|d| d.sibling_idle == Some(true));
let (first, last) = (done.first().ok_or("empty round")?, done.last().ok_or("empty round")?);
if done.is_empty() {
return Err("empty round".to_owned());
}
let position = |p: &ProcOut| done.iter().position(|d| d.proc == p.proc).unwrap_or(0);
let mut files = Vec::new();
let trees: Vec<&'static str> = TREES.iter().copied().filter(|t| done.iter().any(|d| d.proc.tree == *t)).collect();
for tree in trees {
@@ -2275,6 +2282,9 @@ fn round_records(ctx: &BatchCtx, round_no: u32, done: &[ProcOut]) -> Result<Vec<
reference.tree_text
);
let drift = o.max_drift.max(r.max_drift);
// the two processes of this record, earliest first: the clock before the earlier one, after the later one
let (earlier, later) = if position(ours) <= position(reference) { (ours, reference) } else { (reference, ours) };
let sibling_idle = ours.sibling_idle == Some(true) && reference.sibling_idle == Some(true);
let streamed = if regime == "STREAMED" { format!(",\n \"streamed\": {{\"copies\": {}, \"expert_bytes\": {}, \"llc_bytes\": {}}}", o.copies_k, o.expert_bytes, o.llc_bytes) } else { String::new() };
let rowtype = |unit: &str| format!("{gu}+{down} rows={} {} [{unit}]", c.rows, regime.to_ascii_lowercase());
let json = format!(
@@ -2296,9 +2306,9 @@ fn round_records(ctx: &BatchCtx, round_no: u32, done: &[ProcOut]) -> Result<Vec<
pin = ctx.pin,
sib = sibling_idle,
commit = jstr(&p.engine_strata_pin),
method = jstr(&format!("{CLOCK_METHOD}; ghz_before is the first process's ghz_at_start of the round ({}), ghz_after the last process's ghz_at_end ({}); max_drift_fraction is the largest |g1 - g0| / g0 over every slice of the two processes of this record, slices_total and slices_dropped count their requested and dropped slices", first.proc.name(), last.proc.name())),
g0 = jnum(first.ghz_start, 6),
g1 = jnum(last.ghz_end, 6),
method = jstr(&format!("{CLOCK_METHOD}; ghz_before is the ghz_at_start of the earlier process of this record ({}), ghz_after the ghz_at_end of the later one ({}); sibling_idle: the SMT sibling stayed under 5 percent busy during both processes; max_drift_fraction is the largest |g1 - g0| / g0 over every slice of the two processes of this record, slices_total and slices_dropped count their requested and dropped slices", earlier.proc.name(), later.proc.name())),
g0 = jnum(earlier.ghz_start, 6),
g1 = jnum(later.ghz_end, 6),
drift = jnum(drift, 6),
total = o.requested + r.requested,
dropped = o.dropped + r.dropped,
@@ -3055,14 +3065,17 @@ mod tests {
#[test]
fn environment_scrubbing_removes_a_planted_strata_variable_and_keeps_only_the_cell() {
let cell = cell_env(&Proc { imp: Impl::Rust, tree: "avx2", rep: 'a' });
assert_eq!(cell, vec![("LELEKA_CPU_POOL_PIN_HOST".to_owned(), "off".to_owned()), ("STRATA_FORCE_AVX2".to_owned(), "1".to_owned())]);
assert_eq!(
cell,
vec![("LELEKA_CPU_POOL_PIN_HOST".to_owned(), "off".to_owned()), ("STRATA_FORCE_AVX2".to_owned(), "1".to_owned()), ("STRATA_POOL_SPIN_US".to_owned(), "0".to_owned())]
);
assert!(cell_env(&Proc { imp: Impl::Cpp, tree: "avx512", rep: 'b' }).is_empty());
let out = run_cell(&mut child("tests::env_probe_child", "probe", &[("STRATA_X", "planted"), ("LELEKA_Y", "planted"), ("strata_lower", "planted")], &cell), "rust-avx2-a").unwrap();
let text = String::from_utf8_lossy(&out.stdout);
// libtest prints "test <name> ... " before the child's own output on the same line
let mut probes: Vec<&str> = text.lines().flat_map(|l| l.split("PROBE ").skip(1)).collect();
probes.sort_unstable();
assert_eq!(probes, vec!["LELEKA_CPU_POOL_PIN_HOST=off", "STRATA_FORCE_AVX2=1"], "only the cell's variables survive:\n{text}");
assert_eq!(probes, vec!["LELEKA_CPU_POOL_PIN_HOST=off", "STRATA_FORCE_AVX2=1", "STRATA_POOL_SPIN_US=0"], "only the cell's variables survive:\n{text}");
// the cpp avx512 cell sets nothing at all
let out = run_cell(&mut child("tests::env_probe_child", "probe", &[("STRATA_X", "planted")], &[]), "cpp-avx512-a").unwrap();
assert!(!String::from_utf8_lossy(&out.stdout).contains("PROBE "));
@@ -3110,7 +3123,9 @@ mod tests {
assert_eq!((parse_size("32768K"), parse_size("32M"), parse_size("512")), (32 << 20, 32 << 20, 512));
assert_eq!(busy_fraction(Some((10, 100)), Some((30, 200))), Some(0.2));
assert_eq!(busy_fraction(None, Some((1, 1))), None);
assert!(core_ghz() > 0.0);
// the calibrated clock of any x86-64 core is in this range (the chain must not be folded away: 175 GHz was the folded multiply chain)
let ghz = core_ghz();
assert!((0.3..12.0).contains(&ghz), "{ghz}");
}
#[test]
@@ -3228,6 +3243,7 @@ mod tests {
};
let mut done: Vec<ProcOut> = procs_for(&TREES).into_iter().enumerate().map(|(i, p)| fake_proc(p, 100.0 + i as f64)).collect();
done.reverse(); // the order of execution does not matter to the records
done.iter_mut().find(|p| p.proc == Proc { imp: Impl::Cpp, tree: "avx2", rep: 'b' }).unwrap().sibling_idle = Some(false);
let files = round_records(&ctx, 31, &done).unwrap();
assert_eq!(files.len(), 12, "2 trees x 2 regimes x (A/B + A/A cpp + A/A rust)");
let names: BTreeSet<_> = files.iter().map(|f| f.0.as_str()).collect();
@@ -3263,6 +3279,12 @@ mod tests {
let aa = parse_json(files.iter().find(|f| f.0 == "r00031.aa-cpp.avx512.resident.json").unwrap().1.as_bytes()).unwrap();
assert!(aa.str("kernel").unwrap().contains("ours-slot process cpp-avx512-a, reference-slot process cpp-avx512-b"));
assert_eq!(aa.req("equality").unwrap().str("mode").unwrap(), "bitwise");
// sibling_idle belongs to the two processes of a record: only the A/A cpp avx2 records see the busy sibling of cpp-avx2-b
for (name, json) in &files {
let rec = parse_json(json.as_bytes()).unwrap();
let busy = name.contains(".aa-cpp.avx2.");
assert_eq!(matches!(rec.req("pin").unwrap().get("sibling_idle"), Some(Json::Bool(false))), busy, "{name}");
}
// a streamed set that differs between the two sides of a record is refused
let mut skewed = done.clone();
skewed.iter_mut().find(|p| p.proc == Proc { imp: Impl::Cpp, tree: "avx2", rep: 'a' }).unwrap().regimes.get_mut("STREAMED").unwrap().copies_k = 4;