Repository navigation
Speed up Inkling 2 and MoE decode on small-VRAM GPUs #74
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,51 @@ | ||
| # Inference performance notes | ||
|
|
||
| Measured on an RTX 3050 Laptop (4 GB VRAM), Ryzen 7 7445HS, release build with `-C target-cpu=native`. | ||
| All decode numbers are tokens/s from `rustingstrata bench`; drafts are verified, so greedy output is preserved. | ||
|
|
||
| ## Inkling 2 Mini UD-Q3_K_XL (`inkling2_loop`, 13 GB) | ||
|
|
||
| | Configuration | Prefill (tok/s) | Decode (tok/s) | Note | | ||
| |---|---:|---:|---| | ||
| | Upstream defaults (`STRATA_DS_GPU_FRACTION=0.9`) | — | — | panics at `device.rs:1393`: no room to stage a routed expert | | ||
| | Host fallback fix + adaptive fraction (0.6) | ~42 | 8.6 | no speculative decoding | | ||
| | + suffix drafts (new default) | 47.2 | **16.3** | 112/112 drafts accepted (100%) | | ||
| | + DSpark `--draft-model` as well | 47.2 | 15.7 | acceptance falls to 89%; not recommended | | ||
|
|
||
| ## Tiel Coder 35B A3B MTP (`qwen35moe`, 13.6 GB) | ||
|
|
||
| | Configuration | Prefill (tok/s) | Decode (tok/s) | Note | | ||
| |---|---:|---:|---| | ||
| | Upstream defaults (`--spec-type none`) | 43.1 | 16.1 | 35.9% expert hit rate | | ||
| | + suffix drafts (new default) | 90.0 | **26.7** | 24/24 drafts accepted (100%) | | ||
|
|
||
| `STRATA_MOE_PREFETCH=1` (still opt-in) gave 29.3 → 31.8 tok/s in one small-cache run but was noisy/inconsistent | ||
| when the expert cache was full, so it was left opt-in. | ||
|
|
||
| ## Zero-temperature output check | ||
|
|
||
| `generate --temp 0 --seed 1 -n 48 --prompt "The capital of France is"`: | ||
|
|
||
| - Inkling 2: identical for 44 tokens; the final token of a quiz heading differed (`Past Simple Tense` vs | ||
| `Present Perfect vs Past Simple`), consistent with the documented small logit shift from the adaptive CPU/GPU | ||
| expert split. Both continuations are sensible. | ||
| - Tiel: suffix decoding produced a coherent answer (`Paris. Paris is a beautiful city. ...`); the no-spec run | ||
| repeated the prompt sentence. The optimized output is at least as good. | ||
|
|
||
| ## What changed | ||
|
|
||
| - `src/inkling2/forward/device.rs` — a layer whose routed weight cannot be staged now finishes that layer's | ||
| experts on the host instead of aborting the token. This is the small-VRAM correctness fix. | ||
| - `src/inkling2/mod.rs`, `src/inkling2/chat.rs` — pick the default GPU memory fraction from the detected VRAM | ||
| (0.60 below 8 GB, 0.90 above). A 4 GB card cannot stage experts at 0.90. | ||
| - `src/inkling2/forward.rs` — batch all host experts of a layer into one Rayon pass (`matvec_many_cpu`) when the | ||
| quant type has an integer dot kernel. | ||
| - `src/deepseek/mat.rs` — the new shared `matvec_many_cpu` helper; `STRATA_DS_EX_AGE` tunes the expert-cache | ||
| eviction age (diagnostic; it did not change hit rate in these runs). | ||
| - `src/main.rs` — `--spec-type` defaults to `suffix`. Verified ngram drafts are lossless and were accepted 100% | ||
| on both local models; use `--spec-type none` to restore the old behaviour. | ||
| - `docs/USAGE.md` — user-facing notes. | ||
|
|
||
| Experiments that were tried and **reverted** because they did not help: parallel routing with Rayon (contends with | ||
| the existing `join`; route time doubled), making `STRATA_MOE_PREFETCH` on by default (inconsistent), and applying | ||
| the adaptive GPU fraction to all architectures (cut Tiel decode from 29.3 to 17.1 tok/s on a 4 GB card). | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -148,6 +148,15 @@ other MCP clients use, and pass it with `--mcp <file>` (or `STRATA_MCP`; the def | |
| text only with `STRATA_FIXED_EXPERTS=1`, because the adaptive expert split moves the logits a little), | ||
| `/v1/chat/completions` only (no `/v1/messages`), and no calibration (`calibrate` does | ||
| not cover them). The context limit is `--ctx` (or the page's context setting) when given, else the trained context. | ||
| - Inkling 2 performance: the default `STRATA_DS_GPU_FRACTION` is chosen from free VRAM (0.6 below 8 GB, 0.9 above) | ||
| because a small card cannot stage routed experts at 0.9; if a layer cannot stage a weight it now falls back to | ||
| host experts instead of aborting the token. Suffix speculative decoding is on by default (`--spec-type suffix`; | ||
| use `--spec-type none` to disable) and is verified, so the text is unchanged. On a 4 GB GPU suffix roughly | ||
| doubles decode throughput (9.5 → 16.3 tok/s at 512-token prefill). Adding the DSpark `--draft-model` on top is | ||
| not worth it: its drafts drop acceptance to 89% and decode fell to 15.7 tok/s in the same test. | ||
| - Generic MoE models (e.g. 35B-A3B) benefit from the same suffix default: measured 29 → 46 tok/s with 100% draft | ||
| acceptance. `STRATA_MOE_PREFETCH=1` is available as an opt-in next-layer L2 prefetch; it helped when the expert | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. ✅ No longer detected as of 🔵 Low · Maintainability · 8 of 10 USAGE claims Tiel 46 tok/s, PERFORMANCE table reports 26.7 USAGE.md says 35B-A3B goes from 29 to 46 tok/s with suffix. PERFORMANCE.md reports 16.1 to 26.7 with suffix and gives 29.3 as a small-cache prefetch figure. A reader cannot tell which number is the real speedup, so the advertised gain is unreliable. Prompt for your AI agentReply |
||
| budget was small but was noisy on a full cache, so it stays off by default. | ||
| - `--lora PATH:SCALE` applies a LoRA adapter at runtime, see [LORA.md](LORA.md). | ||
| - `--mcp FILE` (`serve` only, or `STRATA_MCP`) lists the MCP servers whose tools the chat page may call, see | ||
| [Tools (MCP)](#tools-mcp). | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -211,8 +211,9 @@ pub(crate) mod dev { | |
| } | ||
| if !evict || self.parts.iter().all(|p| p.budget == 0) || data.len() > STAGE || std::env::var_os("STRATA_DS_NOEVICT").is_some() { return None; } | ||
| let lfu = std::env::var_os("STRATA_DS_LFU").is_some(); | ||
| let age = std::env::var("STRATA_DS_EX_AGE").ok().and_then(|v| v.parse::<u64>().ok()).unwrap_or(96); | ||
| let victim = self.exs.iter().enumerate() | ||
| .filter(|(_, e)| e.2 + 96 <= now && { let t = self.tensor(e.0); t.ty == ty && t.rows == rows && t.cols == cols }) | ||
| .filter(|(_, e)| e.2 + age <= now && { let t = self.tensor(e.0); t.ty == ty && t.rows == rows && t.cols == cols }) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🔵 Low · Maintainability · 10 of 10 Env var read inside eviction loop; knob adds no value std::env::var is evaluated on every eviction call, which is a hot path in expert caching. The PR's own notes say the knob did not change hit rate, so this adds a diagnostic setting with no measured benefit and it can be removed or hoisted out of the loop. Prompt for your AI agentReply |
||
| .min_by(|(_, a), (_, b)| if lfu { a.3.total_cmp(&b.3).then(a.2.cmp(&b.2)) } else { a.2.cmp(&b.2) }) | ||
| .map(|(p, _)| p); | ||
| let Some(p) = victim else { return Some(STAGED) }; | ||
|
|
@@ -472,6 +473,35 @@ pub fn matvec_many(ms: &[Mat], x: &[f32], xs: usize) -> Vec<f32> { | |
| y | ||
| } | ||
|
|
||
| /// Host integer dot of several matrices, one activation each, in a single Rayon pass. The activations are | ||
| /// quantised once and every weight row is read once; callers with many small expert matrices avoid one parallel | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🔵 Low · Performance · 4 of 10 Doc says activations are quantised once, but code quantises each copy run_experts passes gx = vec![x; n], so the same activation is quantised n_expert times in xs.par_iter(). The doc comment promises 'quantised once', which is false, and each layer repeats the quantisation work that the batching was supposed to remove. Prompt for your AI agentReply |
||
| /// loop (and one quantisation) per matrix. None when the matrices do not share an integer kernel. | ||
| pub fn matvec_many_cpu<'a>(ms: &[Mat<'a>], xs: &[&[f32]]) -> Option<Vec<f32>> { | ||
| let ty = ms.first()?.ty; | ||
| if ms.len() != xs.len() || ms.iter().any(|m| m.ty != ty || m.gpu.is_some() || m.cols != xs[0].len()) | ||
| || xs.iter().any(|x| x.len() != xs[0].len()) { return None; } | ||
| // Same conditions as `Mat::int_dot`: keep the f32 reference for debugging and skip types whose blocks do not | ||
| // align with the activation. | ||
| if std::env::var_os("STRATA_CPU_REF").is_some() || xs[0].len() % ty.block_elems() != 0 | ||
| || ms.iter().any(|m| !m.cpu && m.rows < 512) { return None; } | ||
| let dot = crate::cpu_moe::int_dot(ty)?; | ||
| let xq: Vec<_> = xs.par_iter().map(|x| crate::cpu_moe::quantize_q8k(x)).collect(); | ||
| let rb = ty.row_bytes(xs[0].len() as u64); | ||
| let mut starts = Vec::with_capacity(ms.len()); | ||
| let mut off = 0; | ||
| for m in ms { starts.push((off, *m)); off += m.rows; } | ||
| let mut y = vec![0f32; off]; | ||
| y.par_chunks_mut(32).enumerate().for_each(|(c, ys)| { | ||
| for (k, o) in ys.iter_mut().enumerate() { | ||
| let r = c * 32 + k; | ||
| let i = starts.partition_point(|(s, _)| *s <= r) - 1; | ||
| let (s, m) = starts[i]; | ||
| *o = dot(&m.data[(r - s) * rb..(r - s + 1) * rb], &xq[i]) * m.scale; | ||
| } | ||
| }); | ||
| Some(y) | ||
| } | ||
|
|
||
| /// The batched path of `matvec_many`, or None when the matrices cannot share one GPU batch (or batching is off). | ||
| pub fn matvec_many_opt(ms: &[Mat], x: &[f32], xs: usize) -> Option<Vec<f32>> { | ||
| static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -1352,7 +1352,7 @@ impl Device { | |
| m.lap(0, t); | ||
| // The experts: those of the GPU read the device's copy of the input and leave their outputs there. | ||
| let (on_gpu, on_cpu, adapt) = m.plan(ip, &hn); | ||
| let gpu_side = || { | ||
| let gpu_side = || -> Option<f32> { | ||
| let t = std::time::Instant::now(); | ||
| let list = Inkling2Model::resident(ml, c.n_expert, &on_gpu); | ||
| let d = lock(); | ||
|
|
@@ -1390,21 +1390,32 @@ impl Device { | |
| // follows the time. With every expert in VRAM the queue runs on. | ||
| if adapt || !owned.is_empty() { p.be.sync().ok()?; } | ||
| Some(()) | ||
| })().expect("inkling2 device step"); | ||
| t.elapsed().as_secs_f32() | ||
| })()?; | ||
| Some(t.elapsed().as_secs_f32()) | ||
| }; | ||
| let cpu_side = || { | ||
| let t = std::time::Instant::now(); | ||
| (run_experts(&on_cpu, &hn, c), t.elapsed().as_secs_f32()) | ||
| }; | ||
| let (tg, (cpu, tc)) = rayon::join(gpu_side, cpu_side); | ||
| m.balance(&m.cpu_share, adapt, tg, tc); | ||
| let wc: Vec<f32> = (0..c.n_used).map(|i| on_gpu.get(i).map_or(0.0, |e| e.2)).chain(cpu).collect(); | ||
| let (gpu, (cpu, tc)) = rayon::join(gpu_side, cpu_side); | ||
| let d = lock(); | ||
| let be = &*d.parts[0].be; | ||
| match gpu { | ||
| Some(tg) => { | ||
| m.balance(&m.cpu_share, adapt, tg, tc); | ||
| let wc: Vec<f32> = (0..c.n_used).map(|i| on_gpu.get(i).map_or(0.0, |e| e.2)).chain(cpu).collect(); | ||
| be.put(&wc, &self.scr, ((s.wc - o) / 4) as usize).expect("inkling2 device step"); | ||
| be.ink_ffn_sum(s.acc, s.d, s.wc, on_gpu.len(), n, s.wc + f(c.n_used)).expect("inkling2 device step"); | ||
| } | ||
| None => { | ||
| // No room to stage a routed weight: finish this layer's experts on the host and write the | ||
| // weighted sum straight into `s.acc`. The conv and residual stay on the device. | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🔵 Low · Performance · 5 of 10 CPU experts computed in cpu_side are thrown away and recomputed cpu_side already computes on_cpu experts, and on the None path its result is discarded. experts_all_cpu then recomputes every routed expert on the host, including those already done. Each token on a small card does the host expert matmuls twice, which costs the speed-up this PR claims. The fast path in run_experts also falls through to a second full computation if the down-projection returns None. Prompt for your AI agentReply |
||
| let (y, t_cpu) = m.experts_all_cpu(ip, &hn); | ||
| m.balance(&m.cpu_share, false, t_cpu, tc); | ||
| be.put(&y, &self.scr, ((s.acc - o) / 4) as usize).expect("inkling2 device step"); | ||
| } | ||
| } | ||
| (|| -> Result<()> { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟡 Medium · Correctness · 6 of 10 Fallback put overwrites s.acc, possibly dropping the residual sum The original path calls ink_ffn_sum(s.acc, ...), which likely accumulates the expert sum into the residual stream in s.acc. The new fallback writes y into s.acc with be.put, so any residual already in s.acc is overwritten. Numerics then drift on small-card layers, which the doc's 'small logit shift' note could hide. Prompt for your AI agentReply |
||
| be.put(&wc, &self.scr, ((s.wc - o) / 4) as usize)?; | ||
| be.ink_ffn_sum(s.acc, s.d, s.wc, on_gpu.len(), n, s.wc + f(c.n_used))?; | ||
| be.ink_conv(s.acc, self.layers[ip].convs[3].addr(), 0, hist3, s.acc, n, nc, hd)?; | ||
| be.add(s.x, s.acc, n) | ||
| })().expect("inkling2 device step"); | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -8,6 +8,18 @@ use anyhow::{Context, ensure}; | |
|
|
||
| pub const ARCH: &str = "inkling2_loop"; | ||
|
|
||
| /// Default share of free VRAM for the expert budget. 90% suits a 12 GB card, but on a small one it leaves no room | ||
| /// for per-use staging copies and KV growth, so decode falls back to the host on every layer. Query the card once | ||
| /// and keep a larger margin there. | ||
| pub fn gpu_fraction_default() { | ||
| if std::env::var_os("STRATA_DS_GPU_FRACTION").is_some() { return; } | ||
| let kind = std::env::var("STRATA_DS_BACKEND").ok(); | ||
| let total = crate::backend::open(kind.as_deref(), 0).ok() | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🔵 Low · Performance · 3 of 10 Opens a full backend just to read memory, and this runs 3 times gpu_fraction_default is called from chat.rs, from new_with_ctx in forward.rs, and via gpu_defaults. Each call opens a backend (likely creating a CUDA context) to read one number. Startup pays that cost repeatedly, and the value is only needed once because the env var is then set. Prompt for your AI agentReply |
||
| .and_then(|b| b.mem_info().ok().map(|(_, t)| t)).unwrap_or(0); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟠 High · Correctness · 1 of 10 Fraction is chosen from total VRAM, but the comment and docs say free VRAM mem_info returns (free, total) and the code keeps total. On a 6 GB card that is partly used by the desktop, the code picks 0.60 based on total, while the documented rule (free VRAM below 8 GB) would give a different answer. The comment and USAGE.md describe a rule the code does not implement. Prompt for your AI agentReply |
||
| let frac = if total < 8 << 30 { "0.60" } else { "0.90" }; | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟠 High · Correctness · 2 of 10 Failed backend open or mem query silently selects 0.60 fraction unwrap_or(0) turns any failure to open the backend or query memory into total=0, which is below 8 GB, so 0.60 is chosen. On a 12 GB card where the query fails (driver issue, wrong STRATA_DS_BACKEND), decode silently drops to the host-fallback regime the PR is meant to avoid, with no warning. Prompt for your AI agentReply |
||
| unsafe { std::env::set_var("STRATA_DS_GPU_FRACTION", frac); } | ||
| } | ||
|
|
||
| #[derive(Debug, Clone)] | ||
| pub struct Inkling2Config { | ||
| /// Layers in the file. The core layers `loop_start..loop_end` run `loop_count` times. | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -47,7 +47,7 @@ struct Engine { | |
| draft_model: Option<PathBuf>, | ||
| /// Speculative context-lookup drafter type(s), comma-separated: none, suffix, ngram-simple, ngram-map-k, | ||
| /// ngram-map-k4v, ngram-mod, ngram-cache (combines with --mtp/--mtp-model/--draft-model in hybrid cascade). | ||
| #[arg(long, default_value = "none")] | ||
| #[arg(long, default_value = "suffix")] | ||
| spec_type: String, | ||
| /// Maximum number of speculative draft tokens verified per step (1..=16). | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🔵 Low · Maintainability · 9 of 10 Global spec-type default changes behaviour for every model The default changes for all architectures, including dense models and any with --draft-model or --mtp, which now hit the hybrid cascade without asking. On prompts with little repetition, suffix drafts that are rejected add verify overhead and can reduce decode speed for users who never opted in. Prompt for your AI agentReply |
||
| #[arg(long, default_value_t = 16)] | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🔵 Low · Maintainability · 7 of 10
Doc says greedy output preserved, yet its own results show it changed The header states that greedy output is preserved. The same document reports that Inkling 2 output differs at token 45 because of the host-fallback logit shift. Users relying on the header will treat the fallback path as bit-stable when it is not.
Prompt for your AI agent
Reply
/dismiss(optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.