Skip to content

The 80B Qwen3-Coder-Next on a 16 GB Mac, about 13 tok/s, fully offline. A mixture-of-experts inference engine for Apple silicon.

Rust

Early guess: a later layer's router, run early, picks the experts to read ahead (v0.3.0)

1picassoaibb0a181f95de
diff --git a/Cargo.toml b/Cargo.toml
index 455d2a9..28fb46f 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -3,7 +3,7 @@ members = ["crates/engine", "crates/server", "crates/cli"]
resolver = "2"
[workspace.package]
-version = "0.2.1"
+version = "0.3.0"
edition = "2021"
license = "Apache-2.0"
publish = false
diff --git a/README.md b/README.md
index a93d5ef..7bdf21a 100644
--- a/README.md
+++ b/README.md
@@ -20,7 +20,7 @@ Coachwhip is built around that fact:
- **Streams experts, not files.** The small, always-used part of the model lives on the GPU. The experts stay on the SSD, and for each word Coachwhip reads exactly the experts the router picked.
- **An expert bank on the GPU.** Recently used experts stay in a bank in the GPU's memory and are reused, so the SSD is only touched for experts the bank does not hold.
-- **The hot path.** While the GPU works on one layer, Coachwhip predicts which experts the next layer will want and fetches them in parallel. The predictions are learned from the routes the model has taken before, and every chat teaches it more.
+- **The early guess.** While the GPU works on one layer, Coachwhip runs the router of a layer four steps ahead on the same input, so it already knows most of the experts that layer will want, and reads them in while the GPU is busy. A guess that would land too late is dropped rather than evicting an expert still in use. The last few layers, which have no later router, use the routes the model has taken before, and every chat teaches that table more.
- **One GPU dispatch per layer.** All the experts a layer picked run together in a single fused kernel.
- **Reads while it computes.** When a prompt needs more experts than the bank holds, the GPU starts on each expert the moment its bytes land, while the rest are still being read.
- **Unified memory, used properly.** On Apple silicon the CPU and GPU share one memory, so an expert read from the SSD lands straight where the GPU reads it. No copies.
@@ -152,7 +152,9 @@ cd ~/coachwhip
| `--chat 8090` | Serve the chat page on that port, on this machine only |
| `--max-tokens 4000` | Longest answer |
| `--temperature 0` | Always pick the likeliest word (same answer every time) |
-| `--bank 44` | Expert slots kept on the GPU per layer (56 for the 80B) |
+| `--bank 44` | Expert slots kept on the GPU per layer (56 for the 80B, 70 for its Q3_K_M file) |
+| `--prefetch 10` | Experts guessed and read in ahead, per layer; 0 turns the guess off |
+| `--ahead 4` | How many layers ahead the guess looks |
| `--profile` | Print where the time went after each answer |
| `--help` | Everything else |
@@ -165,7 +167,7 @@ cd ~/coachwhip
## Credits
-Built on [Candle](https://github.com/huggingface/candle). `src/model.rs` is derived from Candle's Qwen3 model, and the fused expert kernel is ggml's `mul_mv_id`, which ships inside Candle. The block-at-a-time linear attention follows [Gated Delta Networks](https://arxiv.org/abs/2412.06464) (Yang, Kautz and Hatamizadeh, ICLR 2025).
+Built on [Candle](https://github.com/huggingface/candle). `crates/engine/src/model.rs` is derived from Candle's Qwen3 model, and the fused expert kernel is ggml's `mul_mv_id`, which ships inside Candle. The block-at-a-time linear attention follows [Gated Delta Networks](https://arxiv.org/abs/2412.06464) (Yang, Kautz and Hatamizadeh, ICLR 2025).
## Licence
diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs
index 80d7b91..7346ceb 100644
--- a/crates/cli/src/main.rs
+++ b/crates/cli/src/main.rs
@@ -52,10 +52,14 @@ struct Args {
#[arg(long, default_value_t = 44)]
bank: usize,
- /// Experts fetched ahead for the next layer; 0 turns prefetch off.
- #[arg(long, default_value_t = 2)]
+ /// Experts guessed and fetched ahead per layer; 0 turns prefetch off.
+ #[arg(long, default_value_t = 10)]
prefetch: usize,
+ /// How many layers ahead the guess looks (each layer is about 2 ms of GPU work to read in).
+ #[arg(long, default_value_t = 4)]
+ ahead: usize,
+
/// Reader threads for the prefetch.
#[arg(long, default_value_t = 3)]
readers: usize,
@@ -85,7 +89,7 @@ fn main() -> Result<()> {
let settings = experts::Settings {
bank: args.bank,
prefetch: args.prefetch,
- ahead: 1,
+ ahead: args.ahead.max(1),
readers: args.readers,
routes: routes.is_dir().then_some(routes),
learned: Some(learned.clone()),
diff --git a/crates/engine/src/experts.rs b/crates/engine/src/experts.rs
index 7a58a76..d11c898 100644
--- a/crates/engine/src/experts.rs
+++ b/crates/engine/src/experts.rs
@@ -21,7 +21,7 @@ use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
use std::os::unix::fs::FileExt;
use rayon::prelude::*;
use std::path::Path;
-use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
use std::sync::{mpsc, Arc, Mutex, Weak};
use std::time::Instant;
@@ -162,9 +162,10 @@ pub fn next_scores(routes: &Counts, layer: usize, now: &[(u32, f32)]) -> Vec<(u3
pub struct Settings {
/// Expert slots kept per layer (one expert each: about 3 MB for the 30B, 2 MB for the 80B, at Q4_K_M).
pub bank: usize,
- /// Experts predicted and fetched ahead for the next layer; 0 turns prefetch off.
+ /// Experts guessed and fetched ahead per layer; 0 turns prefetch off.
pub prefetch: usize,
- /// How many layers ahead to predict.
+ /// How many layers ahead the guess looks: layer n runs layer n + ahead's own router on its
+ /// input, so the reads have that many layers of GPU work to land in.
pub ahead: usize,
/// Reader threads that fetch predicted experts.
pub readers: usize,
@@ -178,7 +179,7 @@ pub struct Settings {
impl Default for Settings {
fn default() -> Self {
- Self { bank: 44, prefetch: 2, ahead: 1, readers: 3, routes: None, learned: None, profile: false }
+ Self { bank: 44, prefetch: 10, ahead: 4, readers: 3, routes: None, learned: None, profile: false }
}
}
@@ -259,6 +260,12 @@ struct Stats {
fresh_build_seconds: f64,
prefetch_copies: u64,
prefetch_hits: u64,
+ /// Guessed reads thrown away because the word had moved past their layer.
+ stale_dropped: u64,
+ /// Time a forward spent waiting for a guessed expert still being read in.
+ prefetch_wait_seconds: f64,
+ /// Forwards that fit the bank but found too few free slots (guesses still landing).
+ crowded: u64,
words: u64,
word_started: Option<Instant>,
word_seconds: f64,
@@ -287,7 +294,25 @@ pub struct ExpertStore {
trail: Mutex<Trail>,
learned: Option<std::path::PathBuf>,
learned_file: String,
- prefetch_tx: Mutex<Option<mpsc::Sender<(usize, Vec<u32>)>>>,
+ /// Prefetch jobs: the layer to fill, the word they were guessed for, the experts.
+ prefetch_tx: Mutex<Option<mpsc::Sender<(usize, u64, Vec<u32>)>>>,
+ /// The word being written (one-word steps only) and the layer it has reached.
+ word: AtomicU64,
+ now_layer: AtomicUsize,
+}
+
+/// Expert ids ordered by a router's scores, best first. Equal scores keep expert order, so the
+/// same scores always give the same guess.
+pub fn rank(scores: &[f32]) -> Vec<u32> {
+ let mut ids: Vec<u32> = (0..scores.len() as u32).collect();
+ ids.sort_by(|&a, &b| scores[b as usize].partial_cmp(&scores[a as usize]).unwrap_or(std::cmp::Ordering::Equal).then(a.cmp(&b)));
+ ids
+}
+
+/// A guessed read is stale once its word is over, or the word has reached its layer: from then
+/// on that layer reads its own misses, and a late guess would only evict experts still to be used.
+pub fn is_stale(job_layer: usize, job_word: u64, now_layer: usize, now_word: u64) -> bool {
+ job_word != now_word || job_layer <= now_layer
}
impl ExpertStore {
@@ -347,10 +372,12 @@ impl ExpertStore {
learned: settings.learned.clone(),
learned_file: format!("{started}.log"),
prefetch_tx: Mutex::new(None),
+ word: AtomicU64::new(0),
+ now_layer: AtomicUsize::new(0),
});
- // The prefetch thread reads predicted experts into free slots while the GPU works on the
- // current layer. It holds only a weak handle, so the store still shuts down when the model does.
- let (tx, rx) = mpsc::channel::<(usize, Vec<u32>)>();
+ // The prefetch threads read guessed experts into free slots while the GPU works on the
+ // current layer. They hold only a weak handle, so the store still shuts down with the model.
+ let (tx, rx) = mpsc::channel::<(usize, u64, Vec<u32>)>();
*store.prefetch_tx.lock().unwrap() = Some(tx);
let rx = Arc::new(Mutex::new(rx));
for _ in 0..settings.readers {
@@ -358,8 +385,12 @@ impl ExpertStore {
let rx = rx.clone();
std::thread::spawn(move || loop {
let job = rx.lock().unwrap().recv();
- let Ok((layer, experts)) = job else { break };
+ let Ok((layer, word, experts)) = job else { break };
let Some(st) = weak.upgrade() else { break };
+ if is_stale(layer, word, st.now_layer.load(Ordering::Acquire), st.word.load(Ordering::Acquire)) {
+ st.stats.lock().unwrap().stale_dropped += experts.len() as u64;
+ continue;
+ }
if let Err(e) = st.prefetch(layer, &experts) {
eprintln!("coachwhip: prefetch failed: {e}");
}
@@ -390,14 +421,35 @@ impl ExpertStore {
.collect()
}
- /// Hand the next layer's predicted experts to the prefetch thread.
+ /// Hand a layer's guessed experts to the prefetch threads.
fn request_prefetch(&self, layer: usize, predicted: Vec<u32>) {
if predicted.is_empty() {
return;
}
if let Some(tx) = self.prefetch_tx.lock().unwrap().as_ref() {
- let _ = tx.send((layer, predicted));
+ let _ = tx.send((layer, self.word.load(Ordering::Acquire), predicted));
+ }
+ }
+
+ /// Prefetch those of the top `k` experts in `guess` (best first) that `layer`'s bank does not
+ /// hold, in pairs across the reader threads so they are read side by side.
+ fn prefetch_guess(&self, layer: usize, guess: &[u32], k: usize) {
+ let missing: Vec<u32> = {
+ let banks = self.banks.lock().unwrap();
+ let present = banks.get(&layer);
+ guess.iter().take(k).copied().filter(|e| present.map_or(true, |b| !b.slots.slot_of.contains_key(e))).collect()
+ };
+ for pair in missing.chunks(2) {
+ self.request_prefetch(layer, pair.to_vec());
+ }
+ }
+
+ /// Mark where the word being written has got to; layer 0 starts a new word.
+ fn reached(&self, layer: usize) {
+ if layer == 0 {
+ self.word.fetch_add(1, Ordering::AcqRel);
}
+ self.now_layer.store(layer, Ordering::Release);
}
/// Prefetch thread: reserve free slots for the predicted experts, then read them in with the
@@ -516,18 +568,25 @@ impl ExpertStore {
// layer's misses, read them fresh instead, before the bank is touched.
let ready = &bank.ready;
let Some(plan) = bank.slots.assign(needed, |s| ready[s].load(Ordering::Acquire)) else {
+ self.stats.lock().unwrap().crowded += 1;
return Ok(None);
};
// A prefetch may still be reading a hit in; wait for it rather than read it twice.
+ let mut waited = 0.0;
for &(_, slot) in &plan.hits {
- while !bank.ready[slot].load(Ordering::Acquire) {
- std::thread::yield_now();
+ if !bank.ready[slot].load(Ordering::Acquire) {
+ let wait = Instant::now();
+ while !bank.ready[slot].load(Ordering::Acquire) {
+ std::thread::yield_now();
+ }
+ waited += wait.elapsed().as_secs_f64();
}
}
{
let mut st = self.stats.lock().unwrap();
st.hits += plan.hits.len() as u64;
st.prefetch_hits += plan.prefetch_hits;
+ st.prefetch_wait_seconds += waited;
}
let misses = plan.misses;
if !misses.is_empty() {
@@ -639,6 +698,10 @@ impl ExpertStore {
s.prefetch_copies,
s.prefetch_hits
);
+ eprintln!(
+ "coachwhip: waited {:.2} s on guesses still landing; dropped {} stale guessed reads; {} layers read fresh because the bank was crowded",
+ s.prefetch_wait_seconds, s.stale_dropped, s.crowded
+ );
if s.fresh > 0 {
eprintln!(
"coachwhip: prompt experts: {} read outside the bank, {:.2} s reading, {:.2} s copying to the GPU",
@@ -748,6 +811,10 @@ pub fn route(logits: &Tensor, top_k: usize, norm: bool) -> Result<(Tensor, Tenso
pub struct StreamedMoe {
pub layer: usize,
pub gate: Linear,
+ /// A later layer's router (`ahead` layers on), run early on this layer's input to guess
+ /// that layer's experts while there is still time to read them in.
+ pub next_gate: Option<Linear>,
+ pub ahead: usize,
pub store: Arc<ExpertStore>,
pub top_k: usize,
pub norm_topk_prob: bool,
@@ -809,9 +876,17 @@ impl StreamedMoe {
let started = Instant::now();
let dtype = xs.dtype();
let n = b * s;
+ if n == 1 {
+ self.store.reached(self.layer);
+ }
let xs = xs.reshape((n, h))?.to_dtype(DType::F32)?.contiguous()?;
let (top_ids, top_w) = route(&self.gate.forward(&xs)?, self.top_k, self.norm_topk_prob)?;
+ // The guess for a later layer is queued before the read-back below, so it costs no wait.
+ let early = match &self.next_gate {
+ Some(g) if n == 1 && self.prefetch_k > 0 => Some(g.forward(&xs)?),
+ _ => None,
+ };
// Reading the picks back waits for the GPU to finish everything queued so far, so no
// kernel is still reading a bank slot when `ensure` and the prefetchers overwrite it.
// Keep this wait if this code ever changes.
@@ -821,7 +896,10 @@ impl StreamedMoe {
needed.sort_unstable();
needed.dedup();
let slot_of = self.store.ensure(self.layer, &needed)?;
- if n == 1 && self.prefetch_k > 0 {
+ if let Some(logits) = early {
+ let scores: Vec<f32> = logits.flatten_all()?.to_dtype(DType::F32)?.to_vec1()?;
+ self.store.prefetch_guess(self.layer + self.ahead, &rank(&scores), self.prefetch_k);
+ } else if n == 1 && self.prefetch_k > 0 {
for ahead in 1..=self.store.ahead {
if self.layer + ahead < self.store.slices.len() {
let predicted = self.store.predict_missing(self.layer, &needed, ahead, self.prefetch_k);
diff --git a/crates/engine/src/model.rs b/crates/engine/src/model.rs
index 9b68b2e..d12a375 100644
--- a/crates/engine/src/model.rs
+++ b/crates/engine/src/model.rs
@@ -144,6 +144,8 @@ impl Qwen3Moe {
let moe = StreamedMoe {
layer,
gate: Linear::new(gate, None),
+ next_gate: None,
+ ahead: settings.ahead.max(1),
store: store.clone(),
top_k,
norm_topk_prob,
@@ -170,6 +172,12 @@ impl Qwen3Moe {
ffn_norm: gg.rms_norm(&format!("{p}.ffn_norm.weight"), rms_norm_eps)?,
});
}
+ // Each layer gets the router of the layer `ahead` on, to guess its experts early; the last
+ // `ahead` layers have no later router and use the learned route table.
+ let ahead = settings.ahead.max(1);
+ for i in ahead..layers.len() {
+ layers[i - ahead].moe.next_gate = Some(layers[i].moe.gate.clone());
+ }
Ok(Self { embeddings: Embedding::new(embeddings, embedding_length), layers, norm, output, store, dtype, device: device.clone(), thinks, progress: None })
}
diff --git a/crates/engine/src/model_next.rs b/crates/engine/src/model_next.rs
index 3eaff58..8cdad05 100644
--- a/crates/engine/src/model_next.rs
+++ b/crates/engine/src/model_next.rs
@@ -22,6 +22,15 @@ fn l2_norm(x: &Tensor, eps: f64) -> Result<Tensor> {
x.broadcast_div(&n)
}
+/// Give each layer the router of the layer `ahead` on, so it can guess that layer's experts early.
+/// The last `ahead` layers have no later router and fall back to the learned route table.
+fn wire_lookahead(layers: &mut [Layer], ahead: usize) {
+ let ahead = ahead.max(1);
+ for i in ahead..layers.len() {
+ layers[i - ahead].moe.next_gate = Some(layers[i].moe.gate.clone());
+ }
+}
+
fn softplus(x: &Tensor) -> Result<Tensor> {
(x.exp()? + 1.0)?.log()
}
@@ -383,6 +392,8 @@ impl Qwen3Next {
let moe = StreamedMoe {
layer,
gate: Linear::new(gate, None),
+ next_gate: None,
+ ahead: settings.ahead.max(1),
store: store.clone(),
top_k,
norm_topk_prob: true,
@@ -402,6 +413,7 @@ impl Qwen3Next {
shared,
});
}
+ wire_lookahead(&mut layers, settings.ahead);
Ok(Self { embeddings: Embedding::new(embeddings, embedding_length), layers, norm, output, store, device: device.clone(), thinks, progress: None })
}
diff --git a/crates/engine/tests/lookahead.rs b/crates/engine/tests/lookahead.rs
new file mode 100644
index 0000000..4a22215
--- /dev/null
+++ b/crates/engine/tests/lookahead.rs
@@ -0,0 +1,51 @@
+//! The early guess: ranking a later layer's router scores, and dropping guesses that arrive too late.
+//! No GPU, no model file.
+
+use coachwhip_engine::experts::{is_stale, rank};
+
+#[test]
+fn rank_puts_the_best_scores_first() {
+ assert_eq!(rank(&[0.1, 3.0, 2.0, -1.0, 1.0]), vec![1, 2, 4, 0, 3]);
+}
+
+#[test]
+fn rank_breaks_ties_by_expert_id_so_a_guess_is_repeatable() {
+ assert_eq!(rank(&[1.0, 1.0, 2.0, 1.0]), vec![2, 0, 1, 3]);
+ for _ in 0..10 {
+ assert_eq!(rank(&[0.5; 6]), vec![0, 1, 2, 3, 4, 5]);
+ }
+}
+
+#[test]
+fn rank_covers_every_expert_once() {
+ let scores: Vec<f32> = (0..512).map(|i| ((i * 7919) % 97) as f32 * 0.01).collect();
+ let mut ids = rank(&scores);
+ assert_eq!(ids.len(), 512);
+ assert!(ids.windows(2).all(|p| scores[p[0] as usize] >= scores[p[1] as usize]));
+ ids.sort_unstable();
+ assert_eq!(ids, (0..512).collect::<Vec<u32>>());
+}
+
+#[test]
+fn rank_does_not_panic_on_nan() {
+ let ids = rank(&[1.0, f32::NAN, 2.0]);
+ assert_eq!(ids.len(), 3);
+}
+
+#[test]
+fn a_guess_for_a_later_layer_of_the_same_word_is_fresh() {
+ assert!(!is_stale(12, 7, 8, 7));
+ assert!(!is_stale(9, 7, 8, 7));
+}
+
+#[test]
+fn a_guess_is_stale_once_the_word_reaches_its_layer() {
+ assert!(is_stale(8, 7, 8, 7), "the layer is reading its own misses now");
+ assert!(is_stale(5, 7, 8, 7), "the word has passed that layer");
+}
+
+#[test]
+fn a_guess_from_an_earlier_word_is_stale_whatever_its_layer() {
+ assert!(is_stale(40, 6, 3, 7));
+ assert!(is_stale(0, 0, 0, 1));
+}
diff --git a/tests-mac/same_answers.sh b/tests-mac/same_answers.sh
index cdbead0..235b637 100644
--- a/tests-mac/same_answers.sh
+++ b/tests-mac/same_answers.sh
@@ -1,6 +1,6 @@
#!/bin/bash
# Speed settings must never change what the model says. Runs one prompt at temperature 0 with
-# different banks and prefetch settings and checks every answer is byte-identical.
+# different banks, prefetch sizes and look-aheads and checks every answer is byte-identical.
# Needs a Mac with the model: tests-mac/same_answers.sh /path/to/model.gguf /path/to/tokenizer.json
set -u
MODEL=${1:?model.gguf}
@@ -18,10 +18,11 @@ run() {
run bank44 --bank 44
run bank56 --bank 56
run no-prefetch --bank 56 --prefetch 0
-run prefetch8 --bank 56 --prefetch 8
+run ahead1 --bank 56 --ahead 1
+run ahead4-k20 --bank 56 --ahead 4 --prefetch 20
ref=$(shasum -a 256 < "$OUT/bank44.txt" | cut -c1-16)
-for t in bank56 no-prefetch prefetch8; do
+for t in bank56 no-prefetch ahead1 ahead4-k20; do
got=$(shasum -a 256 < "$OUT/$t.txt" | cut -c1-16)
if [ "$got" = "$ref" ]; then echo "same $t"; else echo "DIFF $t (see $OUT)"; fail=1; fi
done