New crate leleka-offline-tools wired as 'strata-next tools ...'. Every output is byte-identical to the unmodified Python tool (scripts/offline/diff_tools.py: packs incl. refusal cases, 14 draft-vocab subsets x out/stats, make_profile at 512/256/8 experts with ranked bases and traces, mtp_rt at the real H/FF geometry). Committed tiny goldens + integration tests; mtp_rt's multi-MB input is regenerated from a shared splitmix64 rule. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
161 lines
5.4 KiB
Rust
161 lines
5.4 KiB
Rust
//! `tools/make_profile.py`: the expert-cache profile (`STRP` v1): every (layer, expert) pair, ranked. The order is
|
|
//! the base profile's ranking, then the pairs the routing traces used (most frequent first), then every pair still
|
|
//! missing, interleaved across the layers.
|
|
use std::{collections::HashMap, fs, path::Path};
|
|
|
|
use crate::Result;
|
|
|
|
pub const N_LAYER: usize = 48;
|
|
pub const N_EXPERT: usize = 512;
|
|
const MAGIC: &[u8; 4] = b"STRP";
|
|
const VERSION: u32 = 1;
|
|
|
|
pub fn read_profile(path: &Path, n_expert: usize) -> Result<Vec<(u16, u16)>> {
|
|
let blob = fs::read(path)?;
|
|
if blob.get(..4) != Some(MAGIC) {
|
|
return Err(format!("{}: not a Strata profile", path.display()).into());
|
|
}
|
|
let word = |i: usize| -> Result<u32> {
|
|
let at = 4 + 4 * i;
|
|
Ok(u32::from_le_bytes(
|
|
blob.get(at..at + 4)
|
|
.ok_or("truncated profile header")?
|
|
.try_into()?,
|
|
))
|
|
};
|
|
let (layers, experts, count) = (word(1)? as usize, word(2)? as usize, word(4)? as usize);
|
|
if (layers, experts) != (N_LAYER, n_expert) {
|
|
return Err(format!(
|
|
"{}: {layers}x{experts}, not {N_LAYER}x{n_expert}",
|
|
path.display()
|
|
)
|
|
.into());
|
|
}
|
|
(0..count)
|
|
.map(|i| {
|
|
let at = 24 + 4 * i;
|
|
let pair = blob.get(at..at + 4).ok_or("truncated profile")?;
|
|
Ok((
|
|
u16::from_le_bytes([pair[0], pair[1]]),
|
|
u16::from_le_bytes([pair[2], pair[3]]),
|
|
))
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
/// `(layer, expert) -> count` from a `--dump-routing` trace of `(layer i32, k i32, k expert ids, k weights)` records.
|
|
pub fn read_trace(path: &Path, n_expert: usize) -> Result<HashMap<(u16, u16), u64>> {
|
|
let blob = fs::read(path)?;
|
|
let mut frequency = HashMap::new();
|
|
let mut at = 0usize;
|
|
while at + 8 <= blob.len() {
|
|
let layer = i32::from_le_bytes(blob[at..at + 4].try_into()?);
|
|
let k = i32::from_le_bytes(blob[at + 4..at + 8].try_into()?);
|
|
at += 8;
|
|
let k = usize::try_from(k).map_err(|_| "negative routing record width")?;
|
|
let ids = blob.get(at..at + 4 * k).ok_or("truncated routing record")?;
|
|
for id in ids.as_chunks::<4>().0 {
|
|
let expert = i32::from_le_bytes(*id);
|
|
if (0..N_LAYER as i32).contains(&layer) && (0..n_expert as i32).contains(&expert) {
|
|
*frequency.entry((layer as u16, expert as u16)).or_insert(0) += 1;
|
|
}
|
|
}
|
|
at += 8 * k; // the ids and the weights
|
|
}
|
|
Ok(frequency)
|
|
}
|
|
|
|
pub fn write_profile(path: &Path, ranked: &[(u16, u16)], n_expert: usize) -> Result<()> {
|
|
let mut table = vec![vec![-1i32; n_expert]; N_LAYER];
|
|
for (slot, &(layer, expert)) in ranked.iter().enumerate() {
|
|
*table
|
|
.get_mut(layer as usize)
|
|
.and_then(|row| row.get_mut(expert as usize))
|
|
.ok_or("ranked pair outside the profile")? = slot as i32;
|
|
}
|
|
let mut out = MAGIC.to_vec();
|
|
for word in [
|
|
VERSION,
|
|
N_LAYER as u32,
|
|
n_expert as u32,
|
|
ranked.len() as u32,
|
|
ranked.len() as u32,
|
|
] {
|
|
out.extend_from_slice(&word.to_le_bytes());
|
|
}
|
|
for &(layer, expert) in ranked {
|
|
out.extend_from_slice(&layer.to_le_bytes());
|
|
out.extend_from_slice(&expert.to_le_bytes());
|
|
}
|
|
for row in &table {
|
|
for slot in row {
|
|
out.extend_from_slice(&slot.to_le_bytes());
|
|
}
|
|
}
|
|
fs::write(path, out)?;
|
|
Ok(())
|
|
}
|
|
|
|
pub struct Options<'a> {
|
|
pub traces: &'a [&'a Path],
|
|
/// `None` = rank by the traces only (`--no-base`).
|
|
pub base: Option<&'a Path>,
|
|
pub out: &'a Path,
|
|
pub n_expert: usize,
|
|
}
|
|
|
|
fn take(
|
|
ranked: &mut Vec<(u16, u16)>,
|
|
seen: &mut std::collections::HashSet<(u16, u16)>,
|
|
pairs: impl Iterator<Item = (u16, u16)>,
|
|
) {
|
|
for pair in pairs {
|
|
if seen.insert(pair) {
|
|
ranked.push(pair);
|
|
}
|
|
}
|
|
}
|
|
|
|
pub fn run(options: &Options) -> Result<String> {
|
|
let mut ranked: Vec<(u16, u16)> = Vec::new();
|
|
let mut seen = std::collections::HashSet::new();
|
|
if let Some(base) = options.base {
|
|
take(
|
|
&mut ranked,
|
|
&mut seen,
|
|
read_profile(base, options.n_expert)?.into_iter(),
|
|
);
|
|
}
|
|
let n_base = ranked.len();
|
|
let mut frequency: HashMap<(u16, u16), u64> = HashMap::new();
|
|
for trace in options.traces {
|
|
for (pair, count) in read_trace(trace, options.n_expert)? {
|
|
*frequency.entry(pair).or_insert(0) += count;
|
|
}
|
|
}
|
|
let mut by_use: Vec<_> = frequency.into_iter().collect();
|
|
by_use.sort_by_key(|&(pair, count)| (std::cmp::Reverse(count), pair));
|
|
take(
|
|
&mut ranked,
|
|
&mut seen,
|
|
by_use.into_iter().map(|(pair, _)| pair),
|
|
);
|
|
let n_trace = ranked.len() - n_base;
|
|
// the rest, across the layers
|
|
take(
|
|
&mut ranked,
|
|
&mut seen,
|
|
(0..options.n_expert).flat_map(|e| (0..N_LAYER).map(move |l| (l as u16, e as u16))),
|
|
);
|
|
write_profile(options.out, &ranked, options.n_expert)?;
|
|
if read_profile(options.out, options.n_expert)? != ranked {
|
|
return Err("the profile did not survive the round trip".into());
|
|
}
|
|
Ok(format!(
|
|
"wrote {}: {} ranked pairs ({n_base} from the base, {n_trace} from the traces, {} filled in)\n",
|
|
options.out.display(),
|
|
ranked.len(),
|
|
ranked.len() - n_base - n_trace
|
|
))
|
|
}
|