STRA-338 size-fn: trim the new helpers that were a line or two over

This commit is contained in:
Pavlo Ratushnyi
2026-11-06 17:49:45 +01:00
parent a5d789f635
commit c94a001beb
7 changed files with 59 additions and 36 deletions
+1 -2
View File
@@ -106,8 +106,7 @@ impl Speculation {
self.drafter.observe(batch.len(), pass.elapsed().as_secs_f64());
times.pass(batch.len(), pass);
self.logits = logits.next();
self.round_drafted = drafts.len();
self.round_accepted = 0;
(self.round_drafted, self.round_accepted) = (drafts.len(), 0);
self.drafted_total += drafts.len() as u64;
self.batches += 1;
self.pending = drafts.into_iter().zip(logits).collect();
@@ -43,6 +43,17 @@ fn left_to_primary(
|| primary_res.is_some_and(|pr| pr[layer as usize * plan.n_expert as usize + e as usize] >= 0)
}
/// The group of expert `e`, opened with its helper `slot` if it has none yet.
fn group_index(d: &mut Dispatch, e: i32, slot: i32) -> i32 {
match d.groups.iter().position(|grp| grp.expert == e) {
Some(g) => g as i32,
None => {
d.groups.push(Group { expert: e, slot });
d.groups.len() as i32 - 1
}
}
}
/// Mark the entries the helper computes (`owned`), open a group per distinct expert, and return each entry's
/// group (-1 when not owned).
#[allow(clippy::needless_range_loop)] // the loop indices are begin()'s entry numbers
@@ -65,14 +76,7 @@ pub(super) fn assign_groups(
continue;
}
d.owned[i] = 1;
let group = match d.groups.iter().position(|grp| grp.expert == e) {
Some(g) => g as i32,
None => {
d.groups.push(Group { expert: e, slot });
d.groups.len() as i32 - 1
}
};
group_of[i] = group;
group_of[i] = group_index(d, e, slot);
d.computed += 1;
}
group_of
+7 -6
View File
@@ -100,15 +100,16 @@ fn openvino_dirs(root: &Path) -> (PathBuf, PathBuf) {
(bin, tbb)
}
/// The `PATH` for the service: the OpenVINO folders in front of the current one.
fn search_path(folders: [PathBuf; 2]) -> Result<std::ffi::OsString, String> {
let current = std::env::var_os("PATH").unwrap_or_default();
std::env::join_paths(folders.into_iter().chain(std::env::split_paths(&current))).map_err(|e| e.to_string())
}
/// The service process, ready to spawn: OpenVINO's folders on its `PATH`, the model, the shared region and the device.
fn service_command(config: &ServiceConfig, path: &Path) -> Result<Command, String> {
let (bin, tbb) = openvino_dirs(&config.openvino_root);
let search = std::env::join_paths(
[bin.clone(), tbb]
.into_iter()
.chain(std::env::split_paths(&std::env::var_os("PATH").unwrap_or_default())),
)
.map_err(|e| e.to_string())?;
let search = search_path([bin.clone(), tbb])?;
let library = if cfg!(windows) {
"openvino_c.dll"
} else {
+11 -8
View File
@@ -14,6 +14,15 @@ fn add_bias(data: &mut [f32], width: usize, bias: &[f32]) {
});
}
/// Convert the `width`-wide rows of `values` to half precision into the cache rows `cache`.
fn store_halves(dispatch: &Dispatch, cache: &mut [u16], values: &[f32], width: usize) {
par::for_chunks(cache, width, |t, out| {
dispatch
.f32_to_f16(&values[t * width..(t + 1) * width], out)
.expect("equal lengths");
});
}
impl NpuPrefill {
/// Rows `b0..b0 + m` of the chunk through one layer; `xs` is the residual stream of the whole chunk.
pub(super) fn prefill_batch(
@@ -90,14 +99,8 @@ impl NpuPrefill {
ctx.rotate(&mut q, qw, b0);
ctx.rotate(&mut k, kw, b0);
let at = (ctx.pos0 + b0) * kw;
let dispatch = ctx.dispatch;
for (cache, values) in [(&mut kv.kc, &k), (&mut kv.vc, &v)] {
par::for_chunks(&mut cache[at..at + m * kw], kw, |t, out| {
dispatch
.f32_to_f16(&values[t * kw..(t + 1) * kw], out)
.expect("equal lengths");
});
}
store_halves(&ctx.dispatch, &mut kv.kc[at..at + m * kw], &k, kw);
store_halves(&ctx.dispatch, &mut kv.vc[at..at + m * kw], &v, kw);
self.timings.part(1, t1.elapsed());
Ok(q)
}
+11 -4
View File
@@ -22,16 +22,23 @@ impl Replay {
}
}
impl Replay {
/// A count of nothing yet for an output of `tokens` tokens.
fn of(tokens: usize) -> Self {
Self {
tokens,
..Self::default()
}
}
}
/// Run `policy` over a known output the way the worker's loop does (it emits `output` after `prompt`, verifies each
/// draft against it, and charges `cost[n - 1]` single steps for a pass over n tokens) without a model, to compare
/// policies on recorded greedy outputs. `cost` needs `policy.max_draft + 1` entries.
pub fn replay(policy: Policy, prompt: &[u32], output: &[u32], cost: &[f64]) -> Replay {
let mut drafter = Drafter::with_policy(policy);
let mut history = prompt.to_vec();
let mut r = Replay {
tokens: output.len(),
..Replay::default()
};
let mut r = Replay::of(output.len());
let mut round = DraftRound::default();
for (i, &token) in output.iter().enumerate() {
if i + 1 == output.len() {
+10 -4
View File
@@ -19,6 +19,15 @@ fn matrix_blocks(kind: WeightKind, rows: usize, cols: usize, len: usize) -> Resu
Ok(blocks)
}
/// The tokens routed to each expert, in choice order.
fn tokens_per_expert(chosen: &[u32], (used, experts): (usize, usize)) -> Vec<Vec<u32>> {
let mut per_expert: Vec<Vec<u32>> = vec![Vec::new(); experts];
for (i, expert) in chosen.iter().enumerate() {
per_expert[*expert as usize].push((i / used) as u32);
}
per_expert
}
/// The expert tiles (expert, first compact row, rows, 0), the compact row to token map and each choice's
/// compact row, for choices grouped by expert in tiles of `rows_per_tile` rows.
fn group_entries(
@@ -26,10 +35,7 @@ fn group_entries(
(used, experts): (usize, usize),
rows_per_tile: usize,
) -> (Vec<u32>, Vec<u32>, Vec<u32>) {
let mut per_expert: Vec<Vec<u32>> = vec![Vec::new(); experts];
for (i, expert) in chosen.iter().enumerate() {
per_expert[*expert as usize].push((i / used) as u32);
}
let per_expert = tokens_per_expert(chosen, (used, experts));
let mut rowmap = Vec::with_capacity(chosen.len());
let mut tiles = Vec::new();
let mut first = vec![0usize; experts];
+7 -4
View File
@@ -72,10 +72,7 @@ impl Engine {
profile.infer += lap.elapsed();
*scratch = buffer;
profile.calls += 1;
outcome.map(|mut done| {
done.micros = started.elapsed().as_micros() as u64;
done
})
outcome.map(|done| stamped(done, started))
}
/// Where the time of all products so far went, one line.
@@ -93,6 +90,12 @@ impl Engine {
}
}
/// The result with the time since `started`.
fn stamped(mut done: Done, started: Instant) -> Done {
done.micros = started.elapsed().as_micros() as u64;
done
}
/// The product's activations from the shared region into `buffer`.
fn read_activations(shm: &Shared, profile: &mut Profile, p: &Product, buffer: &mut [u8]) -> Result<(), String> {
let lap = Instant::now();