git mv of the files and of the module directories next to them, mod declarations, #[path] attributes and the paths that name the modules, rewritten by scripts/dev/rename_mechanical.py from a reviewed name table. Two files lost one to two lines so the 400-line limit holds again (qsa_prompt_index, original_verify_expert_probe). limits-baseline.json: test fn_lines 0 -> 1 is --allow-increase for crates/deploy builtin_profiles.rs:149 (37 lines, the speed-vs-strata session's file, not touched here); the prod params census falls 108 -> 1 (w_launch, extern C ABI). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
203 lines
7.4 KiB
Rust
203 lines
7.4 KiB
Rust
//! Moved out of the parent module by STRA-338: fn llc_of_cpu, fn proc_stat_cpu, fn busy_fraction, fn current_cpu, fn
|
|
//! observed_threads, fn is_managed_name ....
|
|
|
|
#[allow(unused_imports)]
|
|
use super::*;
|
|
|
|
/// Linux: the highest-level data or unified cache of `cpu` from sysfs. Elsewhere: None (the caller passes
|
|
/// `--llc-bytes`).
|
|
pub(super) fn llc_of_cpu(cpu: usize) -> Option<Llc> {
|
|
let mut best: Option<Llc> = None;
|
|
for i in 0..16 {
|
|
let d = format!("/sys/devices/system/cpu/cpu{cpu}/cache/index{i}");
|
|
let (level, kind, size) =
|
|
(read_text(&format!("{d}/level")), read_text(&format!("{d}/type")), read_text(&format!("{d}/size")));
|
|
if level.is_empty() || size.is_empty() || kind == "Instruction" {
|
|
continue;
|
|
}
|
|
let level_n = level.parse::<u32>().unwrap_or(0);
|
|
if best.as_ref().is_none_or(|b| level_n >= b.level) {
|
|
best = Some(Llc { level: level_n, bytes: parse_size(&size), source: format!("{d}/size = {size}") });
|
|
}
|
|
}
|
|
best.filter(|l| l.bytes > 0)
|
|
}
|
|
|
|
/// (busy, total) jiffies of one logical CPU from /proc/stat (Linux).
|
|
pub(super) fn proc_stat_cpu(cpu: usize) -> Option<(u64, u64)> {
|
|
let stat = fs::read_to_string("/proc/stat").ok()?;
|
|
let line = stat.lines().find(|l| l.starts_with(&format!("cpu{cpu} ")))?;
|
|
let f: Vec<u64> = line.split_whitespace().skip(1).filter_map(|x| x.parse().ok()).collect();
|
|
let total: u64 = f.iter().take(8).sum();
|
|
Some((total - f.get(3)? - f.get(4).copied().unwrap_or(0), total))
|
|
}
|
|
|
|
pub(super) fn busy_fraction(before: Option<(u64, u64)>, after: Option<(u64, u64)>) -> Option<f64> {
|
|
let (b, a) = (before?, after?);
|
|
(a.1 > b.1).then(|| (a.0.saturating_sub(b.0)) as f64 / (a.1 - b.1) as f64)
|
|
}
|
|
|
|
/// Linux: the logical CPU the calling thread last ran on (field 39 of /proc/thread-self/stat). Elsewhere: None.
|
|
pub(super) fn current_cpu() -> Option<usize> {
|
|
if !cfg!(target_os = "linux") {
|
|
return None;
|
|
}
|
|
let s = fs::read_to_string("/proc/thread-self/stat").ok()?;
|
|
let rest = &s[s.rfind(')')? + 1..];
|
|
rest.split_whitespace().nth(36)?.parse().ok()
|
|
}
|
|
|
|
/// Linux: every thread of this process with the CPU it last ran on (the pool's worker is one of them).
|
|
pub(super) fn observed_threads() -> Vec<(String, Option<usize>)> {
|
|
let mut v = Vec::new();
|
|
if let Ok(dir) = fs::read_dir("/proc/self/task") {
|
|
for e in dir.flatten() {
|
|
let p = e.path();
|
|
let name = read_text(&format!("{}/comm", p.display()));
|
|
let cpu = fs::read_to_string(p.join("stat"))
|
|
.ok()
|
|
.and_then(|s| s.get(s.rfind(')')? + 1..)?.split_whitespace().nth(36)?.parse().ok());
|
|
v.push((name, cpu));
|
|
}
|
|
}
|
|
v.sort();
|
|
v
|
|
}
|
|
|
|
pub(super) fn is_managed_name(name: &str) -> bool {
|
|
let up = name.to_ascii_uppercase();
|
|
up.starts_with("STRATA_") || up.starts_with("LELEKA_")
|
|
}
|
|
|
|
/// Every STRATA_* / LELEKA_* variable the process sees.
|
|
pub(super) fn managed_env_now() -> BTreeMap<String, String> {
|
|
std::env::vars_os()
|
|
.filter_map(|(k, v)| Some((k.into_string().ok()?, v.into_string().ok()?)))
|
|
.filter(|(k, _)| is_managed_name(k))
|
|
.collect()
|
|
}
|
|
|
|
pub(super) fn json_env(env: &BTreeMap<String, String>) -> String {
|
|
format!("{{{}}}", env.iter().map(|(k, v)| format!("{}: {}", jstr(k), jstr(v))).collect::<Vec<_>>().join(", "))
|
|
}
|
|
|
|
/// The command line of `kab time` (STRA-317), checked the same way.
|
|
pub(super) fn parse_time_args(args: &[String]) -> Result<TimeArgs, String> {
|
|
let f = Flags::parse(args, &TIME_FLAGS)?;
|
|
let (slices, pin, slice_ms) = time_counts(&f)?;
|
|
let regime = parse_regime_sel(f.get("regime").unwrap_or("both"))?;
|
|
let case = f.req("case")?.to_owned();
|
|
if !valid_id(&case) {
|
|
return Err(format!("--case {case:?} is not a plain identifier"));
|
|
}
|
|
Ok(TimeArgs {
|
|
dir: PathBuf::from(f.req("run-dir")?),
|
|
case,
|
|
slices,
|
|
pin,
|
|
out: PathBuf::from(f.req("out")?),
|
|
slice_ms,
|
|
regime,
|
|
llc_bytes: f.number::<u64>("llc-bytes")?,
|
|
})
|
|
}
|
|
|
|
/// `--slices`, `--pin` and `--slice-ms`, range checked.
|
|
fn time_counts(f: &Flags) -> Result<(usize, usize, f64), String> {
|
|
let slices = f.number::<usize>("slices")?.ok_or("--slices is required")?;
|
|
let pin = f.number::<usize>("pin")?.ok_or("--pin is required")?;
|
|
let slice_ms = f.number::<f64>("slice-ms")?.unwrap_or(DEFAULT_SLICE_MS);
|
|
if !(1..=100_000).contains(&slices) {
|
|
return Err("--slices must be 1..100000".to_owned());
|
|
}
|
|
if !(1.0..=10_000.0).contains(&slice_ms) {
|
|
return Err("--slice-ms must be 1..10000".to_owned());
|
|
}
|
|
Ok((slices, pin, slice_ms))
|
|
}
|
|
|
|
fn parse_regime_sel(s: &str) -> Result<RegimeSel, String> {
|
|
match s {
|
|
"both" => Ok(RegimeSel::Both),
|
|
"resident" => Ok(RegimeSel::Resident),
|
|
"streamed" => Ok(RegimeSel::Streamed),
|
|
_ => Err("--regime must be both, resident or streamed".to_owned()),
|
|
}
|
|
}
|
|
impl<T: Copy + Default> Arena<T> {
|
|
pub(super) fn new(len: usize) -> Self {
|
|
let size = std::mem::size_of::<T>();
|
|
let buf = vec![T::default(); len + ALIGN / size];
|
|
let misalign = buf.as_ptr() as usize % ALIGN;
|
|
let off = if misalign == 0 { 0 } else { (ALIGN - misalign) / size };
|
|
Self { buf, off }
|
|
}
|
|
pub(super) fn slice(&self, len: usize) -> &[T] {
|
|
&self.buf[self.off..self.off + len]
|
|
}
|
|
pub(super) fn slice_mut(&mut self, len: usize) -> &mut [T] {
|
|
&mut self.buf[self.off..self.off + len]
|
|
}
|
|
}
|
|
|
|
impl Timed<'_> {
|
|
pub(super) fn call(&mut self, weights: &[u8]) -> Result<(), String> {
|
|
let (g, u) = (self.header.gate, self.header.up);
|
|
let expert = BorrowedExpert {
|
|
gate: &weights[..g],
|
|
up: &weights[g..g + u],
|
|
down: &weights[g + u..g + u + self.header.down_bytes],
|
|
pairs: &self.pairs,
|
|
};
|
|
let experts = [expert];
|
|
let group = BorrowedGroup { tokens: self.tokens, experts: &experts, stride: 1 };
|
|
self.pool
|
|
.compute_group(self.gu, self.down, &group, &mut self.out)
|
|
.map_err(|e| format!("compute_group failed: {e:?}"))
|
|
}
|
|
}
|
|
|
|
/// One slice of `ms` milliseconds cycling over the copies; the shape of `time_slice()` in tq_cpu_parity.cpp (lines
|
|
/// 290-304).
|
|
pub(super) fn time_slice(t: &mut Timed, copies: &[&[u8]], ms: f64, next: &mut usize) -> Result<Slice, String> {
|
|
let ghz_before = core_ghz();
|
|
let mut calls = 0u64;
|
|
let ns0 = mono_ns();
|
|
let mut ns1;
|
|
loop {
|
|
t.call(copies[*next % copies.len()])?;
|
|
*next += 1;
|
|
calls += 1;
|
|
ns1 = mono_ns();
|
|
if (ns1 - ns0) as f64 >= ms * 1e6 && calls >= 2 {
|
|
break;
|
|
}
|
|
}
|
|
let ghz_after = core_ghz();
|
|
let wall = ns1 - ns0;
|
|
let ns_per_call = wall as f64 / calls as f64;
|
|
let ghz_mean = 0.5 * (ghz_before + ghz_after);
|
|
Ok(Slice {
|
|
calls,
|
|
wall_ns: wall,
|
|
ns_per_call,
|
|
ghz_before,
|
|
ghz_after,
|
|
cycles_per_call: ns_per_call * ghz_mean,
|
|
moved: ghz_mean > 0.0 && (ghz_after - ghz_before).abs() > CLOCK_MOVED_FRACTION * ghz_before,
|
|
})
|
|
}
|
|
|
|
pub(super) fn slice_json(s: &Slice, idx: usize) -> String {
|
|
format!(
|
|
"{{\"i\": {idx}, \"calls\": {}, \"wall_ns\": {}, \"ns_per_call\": {}, \"ghz_before\": {}, \"ghz_after\": {}, \
|
|
\"cycles_per_call\": {}}}",
|
|
s.calls,
|
|
s.wall_ns,
|
|
jnum(s.ns_per_call, 3),
|
|
jnum(s.ghz_before, 6),
|
|
jnum(s.ghz_after, 6),
|
|
jnum(s.cycles_per_call, 1)
|
|
)
|
|
}
|