Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
171 lines
6.7 KiB
Plaintext
171 lines
6.7 KiB
Plaintext
Here is a Rust module.
|
|
|
|
```
|
|
//! expert_source.cpp `RouterLookahead` for the file-mapped expert source (the Original's `--mmap-experts`):
|
|
//! when the CPU tier starts layer `l`, a background thread applies layer `l + 1`'s router (BF16 host copy) to
|
|
//! layer `l`'s MoE input (the residual stream changes little from one layer to the next), takes each row's
|
|
//! top-10, drops the experts the VRAM tier holds and advises the kernel to read the rest's pages
|
|
//! (`MADV_WILLNEED`), so they are on the way while layer `l` computes. A prediction only warms pages: it
|
|
//! never changes which experts are computed or how. `submit` never waits: a prediction still running for an
|
|
//! earlier layer makes this one skip.
|
|
use std::sync::{Arc, Condvar, Mutex, atomic::{AtomicU64, Ordering}};
|
|
use std::thread::JoinHandle;
|
|
|
|
const HIDDEN: usize = 2560;
|
|
const EXPERTS: usize = 512;
|
|
const TOP_K: usize = 10;
|
|
const MAX_ROWS: usize = 8;
|
|
|
|
/// Where layer `l`'s routed experts live in the mapped bank: per role (gate, up, down) the address of
|
|
/// expert 0 and the bytes of one expert (experts are contiguous and uniform, `checked_descriptor`).
|
|
pub(in crate::qwen_forward) type LayerLayout = [(usize, usize); 3];
|
|
|
|
#[derive(Default)]
|
|
struct Mail {
|
|
pending: bool,
|
|
busy: bool,
|
|
quit: bool,
|
|
layer: usize,
|
|
rows: usize,
|
|
x: Vec<f32>,
|
|
resident: Vec<bool>,
|
|
}
|
|
|
|
#[derive(Default)]
|
|
pub(in crate::qwen_forward) struct LookaheadStats {
|
|
pub(in crate::qwen_forward) submitted: AtomicU64,
|
|
pub(in crate::qwen_forward) skipped: AtomicU64,
|
|
pub(in crate::qwen_forward) predicted: AtomicU64,
|
|
pub(in crate::qwen_forward) busy_us: AtomicU64,
|
|
}
|
|
|
|
pub(in crate::qwen_forward) struct RouterLookahead {
|
|
shared: Arc<(Mutex<Mail>, Condvar)>,
|
|
stats: Arc<LookaheadStats>,
|
|
thread: Option<JoinHandle<()>>,
|
|
}
|
|
|
|
impl RouterLookahead {
|
|
/// `routers[l]`: layer l's `ffn_gate_inp` as BF16 bits, 512 rows of 2560; `layouts[l]`: its bank layout.
|
|
pub(in crate::qwen_forward) fn start(routers: Vec<Box<[u16]>>, layouts: Vec<LayerLayout>) -> Option<Self> {
|
|
if routers.len() != layouts.len() || routers.iter().any(|r| r.len() != EXPERTS * HIDDEN) {
|
|
return None;
|
|
}
|
|
let mut mail = Mail::default();
|
|
mail.x.try_reserve_exact(MAX_ROWS * HIDDEN).ok()?;
|
|
mail.resident.try_reserve_exact(EXPERTS).ok()?;
|
|
let shared = Arc::new((Mutex::new(mail), Condvar::new()));
|
|
let stats = Arc::new(LookaheadStats::default());
|
|
let (worker_shared, worker_stats) = (Arc::clone(&shared), Arc::clone(&stats));
|
|
let thread = std::thread::Builder::new()
|
|
.name("leleka-lookahead".into())
|
|
.spawn(move || run(&worker_shared, &worker_stats, &routers, &layouts))
|
|
.ok()?;
|
|
Some(Self { shared, stats, thread: Some(thread) })
|
|
}
|
|
|
|
/// Layer `layer`'s MoE input (`rows` x 2560): predict and warm layer `layer + 1`, leaving out the experts
|
|
/// `resident` (of layer `layer + 1`) says the VRAM tier holds.
|
|
pub(in crate::qwen_forward) fn submit(&self, layer: usize, x: &[f32], resident: impl Fn(usize) -> bool) {
|
|
let rows = (x.len() / HIDDEN).min(MAX_ROWS);
|
|
if rows == 0 {
|
|
return;
|
|
}
|
|
let (lock, wake) = &*self.shared;
|
|
let Ok(mut mail) = lock.try_lock() else {
|
|
self.stats.skipped.fetch_add(1, Ordering::Relaxed);
|
|
return;
|
|
};
|
|
if mail.busy || mail.pending || mail.quit {
|
|
self.stats.skipped.fetch_add(1, Ordering::Relaxed);
|
|
return;
|
|
}
|
|
mail.x.clear();
|
|
mail.x.extend_from_slice(&x[..rows * HIDDEN]);
|
|
mail.resident.clear();
|
|
mail.resident.extend((0..EXPERTS).map(&resident));
|
|
mail.layer = layer + 1;
|
|
mail.rows = rows;
|
|
mail.pending = true;
|
|
drop(mail);
|
|
self.stats.submitted.fetch_add(1, Ordering::Relaxed);
|
|
wake.notify_one();
|
|
}
|
|
|
|
pub(in crate::qwen_forward) fn stats(&self) -> &LookaheadStats {
|
|
&self.stats
|
|
}
|
|
}
|
|
|
|
impl Drop for RouterLookahead {
|
|
fn drop(&mut self) {
|
|
let (lock, wake) = &*self.shared;
|
|
if let Ok(mut mail) = lock.lock() {
|
|
mail.quit = true;
|
|
}
|
|
wake.notify_all();
|
|
if let Some(thread) = self.thread.take() {
|
|
let _ = thread.join();
|
|
}
|
|
}
|
|
}
|
|
|
|
fn run(shared: &(Mutex<Mail>, Condvar), stats: &LookaheadStats, routers: &[Box<[u16]>], layouts: &[LayerLayout]) {
|
|
let (lock, wake) = shared;
|
|
let mut x = vec![0.0f32; MAX_ROWS * HIDDEN];
|
|
let mut resident = vec![false; EXPERTS];
|
|
let mut logits = vec![0.0f32; MAX_ROWS * EXPERTS];
|
|
let mut order: Vec<usize> = (0..EXPERTS).collect();
|
|
let mut want: Vec<usize> = Vec::with_capacity(MAX_ROWS * TOP_K);
|
|
loop {
|
|
let (layer, rows) = {
|
|
let Ok(mut mail) = lock.lock() else { return };
|
|
while !mail.quit && !mail.pending {
|
|
mail = match wake.wait(mail) {
|
|
Ok(mail) => mail,
|
|
Err(_) => return,
|
|
};
|
|
}
|
|
if mail.quit {
|
|
return;
|
|
}
|
|
mail.pending = false;
|
|
mail.busy = true;
|
|
let rows = mail.rows;
|
|
x[..rows * HIDDEN].copy_from_slice(&mail.x[..rows * HIDDEN]);
|
|
resident.copy_from_slice(&mail.resident);
|
|
(mail.layer, rows)
|
|
};
|
|
let started = std::time::Instant::now();
|
|
if let (Some(router), Some(layout)) = (routers.get(layer), layouts.get(layer)) {
|
|
let out = &mut logits[..rows * EXPERTS];
|
|
if leleka_native_cpu_expert::bf16_rows_multi(router, EXPERTS, HIDDEN, &x[..rows * HIDDEN], rows, out).is_ok() {
|
|
want.clear();
|
|
for t in 0..rows {
|
|
let lt = &out[t * EXPERTS..(t + 1) * EXPERTS];
|
|
order.iter_mut().enumerate().for_each(|(i, o)| *o = i);
|
|
order.select_nth_unstable_by(TOP_K - 1, |&a, &b| lt[b].total_cmp(<[a]));
|
|
for &e in &order[..TOP_K] {
|
|
if !resident[e] && !want.contains(&e) {
|
|
want.push(e);
|
|
}
|
|
}
|
|
}
|
|
for &e in &want {
|
|
for &(base, bytes) in layout {
|
|
leleka_native_cpu_expert::advise_will_need(base + e * bytes, bytes);
|
|
}
|
|
}
|
|
stats.predicted.fetch_add(want.len() as u64, Ordering::Relaxed);
|
|
}
|
|
}
|
|
stats.busy_us.fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed);
|
|
if let Ok(mut mail) = lock.lock() {
|
|
mail.busy = false;
|
|
}
|
|
}
|
|
}
|
|
```
|
|
|
|
Add a thorough set of unit tests for the public functions of this module and show the final test module. Then reprint the module's public API.
|