From d07419b6d485e0f949ade457f3f2abbc78020ad9 Mon Sep 17 00:00:00 2001 From: sayampy Date: Sun, 22 Nov 2026 22:05:34 +0530 Subject: [PATCH] Speed up Inkling 2 and MoE decode on small-VRAM GPUs Inkling 2 aborted a decode step when a routed expert could not be staged into VRAM (the default 0.90 GPU fraction left no room on a 4 GB card). It now falls back to host experts for that layer, and picks a 0.60 fraction on small cards while keeping 0.90 on large ones. Host experts of a layer are computed in one Rayon pass through the new shared matvec_many_cpu helper. Suffix speculative decoding is now the CLI default. Drafts are verified, so greedy output is unchanged; acceptance was 100% on both models available here. Benchmarks (RTX 3050 Laptop 4 GB, release): - Inkling 2 Mini, pp512/tg64: upstream panicked; 8.6 tok/s after the fix; 16.3 tok/s with suffix drafts (112/112 accepted). - Tiel 35B A3B, pp128/tg16: 16.1 -> 26.7 tok/s with suffix drafts (24/24 accepted). Zero-temp generation with and without suffix drafts was checked; outputs are equivalent (Inkling 2 differs once at token 48, consistent with its adaptive expert split) and the Tiel suffix output is more coherent. Experiments reverted: parallel routing, prefetch-on-by-default, and global adaptive GPU fraction (each regressed at least one model). Docs: docs/PERFORMANCE.md, docs/USAGE.md. Co-authored-by: HY4-Flash --- docs/PERFORMANCE.md | 51 ++++++++++++++++++++++++++++++++++ docs/USAGE.md | 9 ++++++ src/deepseek/mat.rs | 32 ++++++++++++++++++++- src/inkling2/chat.rs | 6 ++-- src/inkling2/forward.rs | 35 ++++++++++++++++++++--- src/inkling2/forward/device.rs | 27 ++++++++++++------ src/inkling2/mod.rs | 12 ++++++++ src/main.rs | 2 +- 8 files changed, 158 insertions(+), 16 deletions(-) create mode 100644 docs/PERFORMANCE.md diff --git a/docs/PERFORMANCE.md b/docs/PERFORMANCE.md new file mode 100644 index 00000000..65add33c --- /dev/null +++ b/docs/PERFORMANCE.md @@ -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). diff --git a/docs/USAGE.md b/docs/USAGE.md index ce9f1e60..4dc551a7 100644 --- a/docs/USAGE.md +++ b/docs/USAGE.md @@ -148,6 +148,15 @@ other MCP clients use, and pass it with `--mcp ` (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 + 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). diff --git a/src/deepseek/mat.rs b/src/deepseek/mat.rs index 2bf7aaaa..ca18938b 100644 --- a/src/deepseek/mat.rs +++ b/src/deepseek/mat.rs @@ -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::().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 }) .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 { 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 +/// 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> { + 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> { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); diff --git a/src/inkling2/chat.rs b/src/inkling2/chat.rs index e132296d..5fb9a305 100644 --- a/src/inkling2/chat.rs +++ b/src/inkling2/chat.rs @@ -47,7 +47,9 @@ impl Inkling2Opts { } else if self.ngram_cfg.draft_max != 16 { self.ngram_cfg.draft_max } else { - 3 + // Inkling 2 verifies drafts in batches of up to VERIFY_MAX (16) with no host round trip, so a + // longer draft saves whole layer scans; suffix drafts are accepted almost without exception. + 16 }; if self.ngram_cfg.is_enabled() { let mut cfg = self.ngram_cfg.clone(); @@ -73,7 +75,7 @@ const DONE: &str = "<|content_model_end_sampling|>"; pub fn gpu_defaults() { crate::deepseek::chat::gpu_defaults(); - if std::env::var_os("STRATA_DS_GPU_FRACTION").is_none() { unsafe { std::env::set_var("STRATA_DS_GPU_FRACTION", "0.90") } } + super::gpu_fraction_default(); } /// The template's `tojson(sort_keys=true, separators=(",", ":"))`. diff --git a/src/inkling2/forward.rs b/src/inkling2/forward.rs index dd628ee8..7b8c501b 100644 --- a/src/inkling2/forward.rs +++ b/src/inkling2/forward.rs @@ -5,7 +5,7 @@ //! The prompt runs layer by layer over a chunk of tokens: one GPU GEMM per dense matrix and per routed expert. //! ponytail: the attention scores run on the CPU. Move them to the GPU when a long prompt waits on them. use super::Inkling2Config; -use crate::deepseek::mat::{Mat, matvec_many, matvec_many_opt, matvec_rows, matvec_rows_many, matvec_rows_sets, situ_chunk, situ_experts}; +use crate::deepseek::mat::{Mat, matvec_many, matvec_many_cpu, matvec_many_opt, matvec_rows, matvec_rows_many, matvec_rows_sets, situ_chunk, situ_experts}; use crate::deepseek::ops::{rms_norm, rms_norm_w}; use crate::gguf::Gguf; use crate::quant::GgmlType; @@ -428,6 +428,22 @@ fn run_experts(list: &[(Mat, Mat, f32, f32)], x: &[f32], cfg: &Inkling2Config) - } } None => { + // One Rayon pass for all of this layer's host experts instead of one per matrix: the activation is + // quantised once and the rows of every expert are read in the same sweep. + let gus: Vec = list.iter().map(|e| e.0).collect(); + let downs: Vec = list.iter().map(|e| e.1).collect(); + let gs: Vec = list.iter().map(|e| e.3).collect(); + let gx: Vec<&[f32]> = vec![x; list.len()]; + if let Some(y) = matvec_many_cpu(&gus, &gx) { + let a: Vec = y.chunks_exact(2 * nf).zip(&gs).flat_map(|(y, &s)| situ(y, s, cfg)).collect(); + let acts: Vec<&[f32]> = a.chunks_exact(nf).collect(); + if let Some(dy) = matvec_many_cpu(&downs, &acts) { + for (e, dy) in list.iter().zip(dy.chunks_exact(nl)) { + for (m, d) in mix.iter_mut().zip(dy) { *m += e.2 * d; } + } + return mix; + } + } let (mut y, mut dy) = (vec![0f32; 2 * nf], vec![0f32; nl]); for (gu, down, w, s) in list { gu.matvec(x, &mut y); @@ -446,9 +462,7 @@ impl<'a> Inkling2Model<'a> { /// Load the model with a context limit up to `cfg.ctx`. pub fn new_with_ctx(g: &'a Gguf, max_ctx: usize) -> Result { - if std::env::var_os("STRATA_DS_GPU_FRACTION").is_none() { - unsafe { std::env::set_var("STRATA_DS_GPU_FRACTION", "0.90"); } - } + super::gpu_fraction_default(); let cfg = Inkling2Config::from_gguf(g)?; let has = |n: &str| g.tensors.contains_key(n); let mut layers = vec![]; @@ -767,6 +781,19 @@ impl<'a> Inkling2Model<'a> { on_gpu.iter().map(|&(gu, e, w)| (if gu.gpu.is_some() { gu } else { on(&l.gate_up, e) }, on(&l.down, e), w, l.gu_scale[e])).collect() } + /// All routed experts of `x` in layer `ip` on the host, with no VRAM allocation. Used when the device cannot + /// stage a routed weight (a small card whose expert budget leaves no room for per-use copies). + pub(super) fn experts_all_cpu(&self, ip: usize, x: &[f32]) -> (Vec, f32) { + let t = std::time::Instant::now(); + let (cfg, l) = (&self.cfg, &self.layers[ip]); + let ne = cfg.n_expert; + let sel = route(l, x, cfg); + let list: Vec<(Mat<'a>, Mat<'a>, f32, f32)> = sel.iter().map(|&(e, w)| { + (l.gate_up.expert_host(e, ne), l.down.expert_host(e, ne), w, l.gu_scale[e]) + }).collect(); + (run_experts(&list, x, cfg), t.elapsed().as_secs_f32()) + } + /// MoE of one token with the weights of layer `ip`. fn ffn(&self, ip: usize, x: &[f32]) -> Vec { let (cfg, l) = (&self.cfg, &self.layers[ip]); diff --git a/src/inkling2/forward/device.rs b/src/inkling2/forward/device.rs index 9e61fccd..3d0da345 100644 --- a/src/inkling2/forward/device.rs +++ b/src/inkling2/forward/device.rs @@ -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 { 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 = (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 = (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. + 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<()> { - 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"); diff --git a/src/inkling2/mod.rs b/src/inkling2/mod.rs index be3f14db..0a06b044 100644 --- a/src/inkling2/mod.rs +++ b/src/inkling2/mod.rs @@ -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() + .and_then(|b| b.mem_info().ok().map(|(_, t)| t)).unwrap_or(0); + let frac = if total < 8 << 30 { "0.60" } else { "0.90" }; + 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. diff --git a/src/main.rs b/src/main.rs index 007ed309..1a4bcad3 100644 --- a/src/main.rs +++ b/src/main.rs @@ -47,7 +47,7 @@ struct Engine { draft_model: Option, /// 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). #[arg(long, default_value_t = 16)]