From 6452a70172414309a7343bef233187b7b4f962b8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Sacilotti?= Date: Mon, 23 Nov 2026 11:34:14 -0300 Subject: [PATCH 1/9] inkling2: expert slabs on a second GPU, remote FFN, PLAIN_FIRST alloc_slab_on places a layer's whole expert slab on GPU 0 or 1; a layer whose experts live on GPU 1 runs its FFN there (Remote scratch, a light prefill scratch) with the activations over the host, and its attention and tail stay on GPU 0. Each stacked expert tensor keeps all its experts on one GPU (affinity) so a layer's matvecs hit the batched path. STRATA_DS_PLAIN_FIRST keeps the plain weights on GPU 0, where the device decode state lives, and STRATA_DS_PF_TOKENS sets the prompt chunk. (cherry picked from commit b15a10d5dd8f058bfb5ab64b09c5ec67b88152e5) --- src/deepseek/mat.rs | 67 ++++- src/inkling2/chat.rs | 2 + src/inkling2/forward.rs | 10 +- src/inkling2/forward/device.rs | 488 +++++++++++++++++++++++---------- 4 files changed, 412 insertions(+), 155 deletions(-) diff --git a/src/deepseek/mat.rs b/src/deepseek/mat.rs index 05ac70cb..db164271 100644 --- a/src/deepseek/mat.rs +++ b/src/deepseek/mat.rs @@ -21,14 +21,14 @@ pub(crate) mod dev { const SHIFT: u32 = 24; pub fn gpu_of(id: u32) -> usize { (id >> SHIFT) as usize } pub(crate) struct Part { pub(crate) be: Box, ts: Vec, x: Buf, y: Buf, stage: Buf, bytes: usize, budget: usize, room: usize } - pub struct SlabBuf { buf: Buf, bytes: usize, freed: std::sync::Arc } + pub struct SlabBuf { buf: Buf, bytes: usize, acct: usize, freed: std::sync::Arc } impl SlabBuf { pub fn addr(&self) -> u64 { self.buf.addr() } pub fn len(&self) -> usize { self.bytes } } impl Drop for SlabBuf { fn drop(&mut self) { - self.freed.fetch_add(self.bytes, std::sync::atomic::Ordering::Relaxed); + self.freed.fetch_add(self.acct, std::sync::atomic::Ordering::Relaxed); } } #[derive(Default)] @@ -42,6 +42,11 @@ pub(crate) mod dev { now: u64, cur: usize, lookups: u64, + /// Local patch (multi-GPU): the stacked expert tensor (base address, bytes) of the expert being looked up. + group: Option<(usize, usize)>, + /// Local patch: stacked expert tensor base address -> GPU that holds all of its experts; bytes promised per GPU. + aff: std::collections::HashMap, + aff_bytes: Vec, } static DEV: LazyLock> = LazyLock::new(Default::default); /// Whether `DEV` is open: None before the first `get` and after `free`. @@ -131,26 +136,38 @@ pub(crate) mod dev { /// Allocates and uploads a contiguous buffer inside GPU 0 when both `p.budget` and live `mem_info()` keep the /// given byte reserves free. Static mmap slices with `cache_key` deduplicate across multiple model instances. pub fn alloc_slab(&mut self, data: &[u8], cache_key: Option<(usize, usize)>, budget_reserve: usize, free_reserve: usize) -> Option> { + self.alloc_slab_on(0, data, cache_key, budget_reserve, free_reserve) + } + /// `alloc_slab` on GPU `d`. Local patch (Inkling 2 on two GPUs): a slab on a GPU other than 0 is checked against + /// the live free VRAM only, and stays out of the expert budget bookkeeping (which `freed` tracks for GPU 0). + pub fn alloc_slab_on(&mut self, d: usize, data: &[u8], cache_key: Option<(usize, usize)>, budget_reserve: usize, free_reserve: usize) -> Option> { self.reclaim(); + let cache_key = cache_key.map(|k| (k.0, k.1 | d << 60)); if let Some(k) = cache_key && let Some(hit) = self.slabs.get(&k).and_then(std::sync::Weak::upgrade) { return Some(hit); } - let p = self.parts.first_mut()?; - if p.bytes + data.len() + budget_reserve > p.budget { return None; } + let p = self.parts.get_mut(d)?; + if d == 0 && p.bytes + data.len() + budget_reserve > p.budget { return None; } if let Ok((free, _)) = p.be.mem_info() && free < data.len() + free_reserve { return None; } let b = p.be.alloc(data.len()).ok()?; if p.be.htod(data, &b, 0).is_err() { return None; } - p.bytes += data.len(); - let arc = std::sync::Arc::new(SlabBuf { buf: b, bytes: data.len(), freed: self.freed.clone() }); + if d == 0 { p.bytes += data.len(); } + let arc = std::sync::Arc::new(SlabBuf { buf: b, bytes: data.len(), acct: if d == 0 { data.len() } else { 0 }, freed: self.freed.clone() }); if let Some(k) = cache_key { self.slabs.retain(|_, v| v.strong_count() > 0); self.slabs.insert(k, std::sync::Arc::downgrade(&arc)); } Some(arc) } + /// Free VRAM of GPU `d` now, in bytes. + pub fn free_on(&self, d: usize) -> usize { self.parts.get(d).and_then(|p| p.be.mem_info().ok()).map_or(0, |m| m.0) } /// The GPU that takes `len` more bytes of plain weights: the current one while they fit, then the next; the last takes all. pub fn pick(&mut self, len: usize) -> usize { self.reclaim(); + // Local patch (Inkling 2 on several GPUs): the decode state lives on GPU 0 and reads the plain weights + // there, so they stay on GPU 0 while the weight budget has room (the old `room` was ~0.3 GB at 0.9). + if self.parts.len() > 1 && self.cur == 0 && std::env::var_os("STRATA_DS_PLAIN_FIRST").is_some() + && self.parts[0].bytes + len <= self.parts[0].budget { return 0; } while self.cur + 1 < self.parts.len() && self.parts[self.cur].bytes + len > self.parts[self.cur].room { self.cur += 1; } self.cur } @@ -202,6 +219,25 @@ pub(crate) mod dev { /// `evict` false: a miss with no free room returns None, so the caller can run that expert on the CPU. /// Whether the expert that starts at `data` has a VRAM slot (no lookup is counted). pub fn resident(&self, data: &[u8]) -> bool { self.ex.contains_key(&(data.as_ptr() as usize)) } + /// The GPU that holds the experts of the stacked tensor at `base` (`len` bytes): picked on first sight as the + /// GPU with the smallest share of its expert budget already promised. None with one GPU or + /// STRATA_DS_NO_AFFINITY set (the old per-expert choice). + fn affinity(&mut self, base: usize, len: usize) -> Option { + let n = self.parts.len(); + if n < 2 || std::env::var_os("STRATA_DS_NO_AFFINITY").is_some() { return None; } + if let Some(&d) = self.aff.get(&base) { return Some(d); } + if self.aff_bytes.len() != n { self.aff_bytes = vec![0; n]; } + let frac = |d: usize| self.aff_bytes[d] as f64 / self.parts[d].budget.max(1) as f64; + let d = (0..n).min_by(|&a, &b| frac(a).total_cmp(&frac(b)))?; + self.aff_bytes[d] += len; + self.aff.insert(base, d); + Some(d) + } + /// `expert` for an expert that belongs to the stacked tensor (`base`, `len`): see `affinity`. + pub fn expert_grouped(&mut self, group: (usize, usize), data: &[u8], ty: GgmlType, rows: usize, cols: usize, scale: f32, evict: bool) -> Option { + self.group = Some(group); + self.expert(data, ty, rows, cols, scale, evict) + } pub fn expert(&mut self, data: &[u8], ty: GgmlType, rows: usize, cols: usize, scale: f32, evict: bool) -> Option { self.reclaim(); let k = data.as_ptr() as usize; @@ -216,8 +252,14 @@ pub(crate) mod dev { return Some(self.exs[p].0); } EX_LOOKUPS[1].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + // Local patch: all experts of one stacked tensor (a layer's gate_up or down) go to the same GPU, so a + // layer's matvecs hit `batch_mats`' single-GPU path instead of two sequential batches with two readbacks. + // The GPU with the most free budget used to win per expert, which spread every layer over both cards. + let pref = self.group.take().and_then(|(base, len)| self.affinity(base, len)); let room = |p: &Part| (p.bytes + data.len() <= p.budget).then(|| p.budget - p.bytes); - if let Some(d) = (0..self.parts.len()).filter_map(|d| room(&self.parts[d]).map(|r| (r, d))).max().map(|(_, d)| d) { + let pick = pref.filter(|&d| room(&self.parts[d]).is_some()) + .or_else(|| (0..self.parts.len()).filter_map(|d| room(&self.parts[d]).map(|r| (r, d))).max().map(|(_, d)| d)); + if let Some(d) = pick { let i = self.upload_on(d, data, ty, rows, cols, scale)?; self.ex.insert(k, self.exs.len()); self.exs.push((i, k, now, 1.0)); @@ -325,6 +367,8 @@ pub(crate) mod dev { drop(owned); Some(y) } + /// Whether `m` lives in VRAM of the first GPU (a staged matrix is copied up to it per use). + pub fn on_first(&self, m: &Mat) -> bool { self.part_of(m) == Some(0) } fn part_of(&self, m: &Mat) -> Option { let i = m.gpu?; Some(if i == STAGED { 0 } else { gpu_of(i) }) @@ -650,8 +694,15 @@ impl<'a> Mat<'a> { /// `expert` that never overwrites a VRAM slot when `evict` is false: an expert that is not resident and has no /// free room comes back host-only, for the CPU. pub fn expert_opt(&self, e: usize, n_expert: usize, evict: bool) -> Mat<'a> { + self.expert_opt_in(e, n_expert, evict, self, 0) + } + + /// `expert_opt` where the GPU is chosen per `key` (a layer's gate_up tensor) instead of per tensor, so the gate_up + /// and down experts of a layer share a GPU: `extra` is the bytes of the other tensors of the group. + pub fn expert_opt_in(&self, e: usize, n_expert: usize, evict: bool, key: &Mat<'a>, extra: usize) -> Mat<'a> { let mut m = self.expert_host(e, n_expert); - m.gpu = dev::get().and_then(|d| d.lock().unwrap().expert(m.data, m.ty, m.rows, m.cols, m.scale, evict)); + let group = (key.data.as_ptr() as usize, key.data.len() + extra); + m.gpu = dev::get().and_then(|d| d.lock().unwrap().expert_grouped(group, m.data, m.ty, m.rows, m.cols, m.scale, evict)); m } diff --git a/src/inkling2/chat.rs b/src/inkling2/chat.rs index 1ee3e799..4e55f69f 100644 --- a/src/inkling2/chat.rs +++ b/src/inkling2/chat.rs @@ -74,6 +74,8 @@ 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.6,0.9") } } + // Local patch: with several GPUs the plain weights stay on GPU 0, where the device decode state lives. + if std::env::var_os("STRATA_DS_PLAIN_FIRST").is_none() { unsafe { std::env::set_var("STRATA_DS_PLAIN_FIRST", "1") } } } /// The template's `tojson(sort_keys=true, separators=(",", ":"))`. diff --git a/src/inkling2/forward.rs b/src/inkling2/forward.rs index f6d42012..1243c86a 100644 --- a/src/inkling2/forward.rs +++ b/src/inkling2/forward.rs @@ -754,7 +754,7 @@ impl<'a> Inkling2Model<'a> { // share; 0 (also `--fixed-experts`) runs every expert on the GPU: the same numerics on every run. self.lap(4, t); let (share, fixed) = self.share(&self.cpu_share); - let gus: Vec = sel.iter().map(|s| l.gate_up.expert_opt(s.0, ne, share == 0.0)).collect(); + let gus: Vec = sel.iter().map(|s| l.gate_up.expert_opt_in(s.0, ne, share == 0.0, &l.gate_up, l.down.data.len())).collect(); let n_miss = gus.iter().filter(|m| m.gpu.is_none()).count(); let mut left = (share * n_miss as f32).round() as usize; let (mut on_gpu, mut on_cpu) = (vec![], vec![]); @@ -771,7 +771,7 @@ impl<'a> Inkling2Model<'a> { /// The GPU's experts of `plan` with both matrices in VRAM: in a cache slot, or copied up for this use. fn resident(l: &Layer<'a>, ne: usize, on_gpu: &[(Mat<'a>, usize, f32)]) -> Vec<(Mat<'a>, Mat<'a>, f32, f32)> { - let on = |m: &Mat<'a>, e: usize| { let x = m.expert_opt(e, ne, true); if x.gpu.is_some() { x } else { x.staged() } }; + let on = |m: &Mat<'a>, e: usize| { let x = m.expert_opt_in(e, ne, true, &l.gate_up, l.down.data.len()); if x.gpu.is_some() { x } else { x.staged() } }; 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() } @@ -822,8 +822,8 @@ impl<'a> Inkling2Model<'a> { // split of the prefill chunks alone. let cell = if xs.len() <= device::VERIFY_MAX { &self.cpu_share } else { &self.chunk_share }; let (share, fixed) = self.share(cell); - let on = |m: &Mat<'a>, e: usize| { let x = m.expert_opt(e, ne, share == 0.0); if x.gpu.is_some() { x } else { x.staged() } }; - let gus: Vec<(usize, Mat)> = by_e.keys().map(|&e| (e, l.gate_up.expert_opt(e, ne, share == 0.0))).collect(); + let on = |m: &Mat<'a>, e: usize| { let x = m.expert_opt_in(e, ne, share == 0.0, &l.gate_up, l.down.data.len()); if x.gpu.is_some() { x } else { x.staged() } }; + let gus: Vec<(usize, Mat)> = by_e.keys().map(|&e| (e, l.gate_up.expert_opt_in(e, ne, share == 0.0, &l.gate_up, l.down.data.len()))).collect(); let n_miss = gus.iter().filter(|g| g.1.gpu.is_none()).count(); let mut left = (share * n_miss as f32).round() as usize; let (mut on_gpu, mut on_cpu) = (vec![], vec![]); @@ -1250,7 +1250,7 @@ impl<'a> Inkling2Model<'a> { let target_end = self.toks.len() + seq.len() - 1; match d.prepare(self, target_end) { Ok(()) => { - let chunk = env_chunk.unwrap_or(256).clamp(1, 256); + let chunk = env_chunk.unwrap_or(device::pf_tokens()).clamp(1, device::pf_tokens()); let mut logits = vec![]; let mut done = 0usize; let mut failed = None; diff --git a/src/inkling2/forward/device.rs b/src/inkling2/forward/device.rs index d3787ab4..6f5d510e 100644 --- a/src/inkling2/forward/device.rs +++ b/src/inkling2/forward/device.rs @@ -14,6 +14,8 @@ use std::sync::Arc; /// Contiguous all-expert weights + F32 router uploaded once for a layer, enabling zero-round-trip GPU MoE. struct FullExps { + /// The GPU of the slabs: 0, or 1 when GPU 0 had no room (the FFN of that layer runs there, see `Remote`). + part: usize, _gi: Arc, gate_inp: GpuTensor, bias: Arc, @@ -38,6 +40,15 @@ struct DLoop { msg_query: Buf, down: Buf, gain: Buf, forget: Buf } /// sliding-window slot is a ring of `n_swa` rows (position p in row p % n_swa); the others grow. struct DSlot { k: Buf, v: Buf, hist: Buf, cap: usize } +/// What GPU 1 needs to run the FFN of the layers whose experts live there: a decode scratch (`s`) and, from the first +/// prompt chunk on, a prefill scratch. The activations come over the host once per layer run (about 10 KB per token). +struct Remote { part: usize, scr: Buf, s: Scratch, pf: Option } + +/// Tokens of one prompt chunk on the device: `STRATA_DS_PF_TOKENS` (default 512, at most 2048). +pub(super) fn pf_tokens() -> usize { + std::env::var("STRATA_DS_PF_TOKENS").ok().and_then(|v| v.parse::().ok()).unwrap_or(512).clamp(1, 2048) +} + /// Device addresses of the regions of the decode scratch buffer (`sc` lives in `Device::sc_buf` so `--ctx` scales dynamically). #[derive(Clone, Copy)] struct Scratch { @@ -116,23 +127,38 @@ struct PrefillScratch { } impl PrefillScratch { - fn alloc(be: &dyn Backend, c: &Inkling2Config, rank: usize, vocab_rows: usize, max_nt: usize) -> Result { + /// Bytes `alloc` takes (plus a little for the allocator). + fn bytes(be: &dyn Backend, c: &Inkling2Config, rank: usize, vocab_rows: usize, max_nt: usize, light: bool) -> usize { + let (kw, n_slot) = (c.n_head_kv * c.head_dim, c.n_slot()); + let rb = 2 * be.kv_words(kw); + let lay = PrefillLayout::at(0, c, rank, max_nt).end as usize; + let swa = (n_slot * VERIFY_MAX * rb).max(1024); + let extra = if light { 0 } else { + 2 * max_nt * rb + 4 * VERIFY_MAX * vocab_rows + 16 * max_nt * c.n_embd + 4 * n_slot * hists(c).1 + + 4 * n_slot * VERIFY_MAX * (2 * kw + 2 * c.n_embd) + 2 * swa + }; + lay + 4 * max_nt * c.n_embd + (40 * max_nt * c.n_used).max(1024) + extra + (16 << 20) + } + + /// `light`: only what the routed experts of a layer need (GPU 1 runs nothing else): the attention logs are tiny. + fn alloc(be: &dyn Backend, c: &Inkling2Config, rank: usize, vocab_rows: usize, max_nt: usize, light: bool) -> Result { let lay0 = PrefillLayout::at(0, c, rank, max_nt); let buf = be.alloc(lay0.end as usize)?; let p = PrefillLayout::at(buf.addr(), c, rank, max_nt); let acc_buf = be.alloc(4 * max_nt * c.n_embd)?; let kw = c.n_head_kv * c.head_dim; let rb = 2 * be.kv_words(kw); - let kv_bytes = max_nt * rb; + let kv_bytes = if light { 256 } else { max_nt * rb }; let (kc_tmp, vc_tmp) = (be.alloc(kv_bytes)?, be.alloc(kv_bytes)?); let max_np = max_nt * c.n_used; let meta = be.alloc((40 * max_np).max(1024))?; - let logits_buf = be.alloc(4 * VERIFY_MAX * vocab_rows)?; - let dspark_buf = be.alloc(4 * 4 * max_nt * c.n_embd)?; + let lt = |b: usize| if light { 256 } else { b }; + let logits_buf = be.alloc(lt(4 * VERIFY_MAX * vocab_rows))?; + let dspark_buf = be.alloc(lt(4 * 4 * max_nt * c.n_embd))?; let n_slot = c.n_slot(); - let hist_bak = be.alloc(4 * n_slot * hists(c).1)?; - let conv_log = be.alloc(4 * n_slot * VERIFY_MAX * (2 * kw + 2 * c.n_embd))?; - let swa_log_bytes = (n_slot * VERIFY_MAX * rb).max(1024); + let hist_bak = be.alloc(lt(4 * n_slot * hists(c).1))?; + let conv_log = be.alloc(lt(4 * n_slot * VERIFY_MAX * (2 * kw + 2 * c.n_embd)))?; + let swa_log_bytes = lt((n_slot * VERIFY_MAX * rb).max(1024)); let (swa_kc_log, swa_vc_log) = (be.alloc(swa_log_bytes)?, be.alloc(swa_log_bytes)?); Ok(Self { max_nt, buf, acc_buf, kc_tmp, vc_tmp, meta, logits_buf, dspark_buf, @@ -153,6 +179,12 @@ pub(super) struct Device { s: Scratch, rank: usize, all_full: bool, + /// GPU 1's share of the FFN layers (None when every layer's experts are on GPU 0). + rem: Option, + /// With `rem`: the loop layers are all on GPU 0, so the loop runs as one graph, and the layers around it launch one by one. + seg_graph: bool, + /// Blocks in the depth mix after the loop (what `layer_attn` counted when the loop graph was recorded). + loop_nb: usize, /// Key of the recorded `step_fast` graph, by `argmax` (0: none). graph_keys: [u64; 2], /// Positions whose rows both sides hold, and whether the device has run tokens after them. @@ -248,8 +280,9 @@ impl Device { let full = (2 * (pos + 1)).clamp(4096.min(m.max_ctx), m.max_ctx); { let mut d = dev::get()?.lock().unwrap(); - if d.parts.len() != 1 { return None; } - let dense = |x: &Mat| !x.host_only(); + // Local patch: several GPUs are fine as long as the plain weights are on GPU 0 (see STRATA_DS_PLAIN_FIRST); the + // experts that live on another GPU run as a third share in `layer`. + let dense = |x: &Mat| !x.host_only() && d.on_first(x); if !dense(&m.output) || !m.layers.iter().all(|l| { [l.wq, l.wk, l.wv, l.wo, l.gate, l.rel, l.sink].iter().chain(l.conv_proj.iter().flatten()).all(dense) }) { return None; } @@ -289,38 +322,63 @@ impl Device { let s = Scratch::at(scr.addr(), c, rank, m.output.rows); // Preload full-layer expert slabs so selected layers skip CPU routing, uploads, and host syncs. - // Core loop layers run 3x per token (75% of FFN compute), so prioritize them first. + // Core loop layers run 3x per token (75% of FFN compute), so they go first, and to GPU 0, where the attention is. + // Local patch: with two GPUs the layers that run once (outside the loop) prefer GPU 1, and a layer that does not + // fit on its GPU goes to the other one: every layer's experts end up in VRAM, and the FFN of a layer on GPU 1 + // runs there (`Remote`). GPU 0 keeps free what the state still needs: prompt chunk scratch and KV growth. let cpu_share = std::env::var("STRATA_DS_CPU_SHARE").ok().and_then(|v| v.parse::().ok()).unwrap_or(0.0); - let (mut n_full, mut slab_bytes) = (0usize, 0usize); + let (mut n_full, mut slab_bytes, mut per_part) = (0usize, 0usize, [0usize; 2]); + let mut rem: Option = None; if cpu_share <= 0.0 && c.n_expert <= 512 && c.n_used <= 32 { let (b_res, f_res) = (64 << 20, 384 << 20); - let order = (c.loop_start..c.loop_end).chain(0..c.loop_start).chain(c.loop_end..c.n_layer); + let (n_parts, pf_cap, vocab) = (dev::get().unwrap().lock().unwrap().parts.len().min(2), pf_tokens(), m.output.rows); + let (res0, res1) = { + let d = dev::get().unwrap().lock().unwrap(); + let be0 = &*d.parts[0].be; + // The KV rows GPU 0 must still be able to take: all of `--ctx` unless STRATA_DS_KV_TOKENS says less (a + // lower value frees room for more expert slabs on GPU 0, at the price of a host fallback past it). + let kv_rows = std::env::var("STRATA_DS_KV_TOKENS").ok().and_then(|v| v.parse::().ok()).unwrap_or(m.max_ctx) + .min(m.max_ctx).max(full); + let n_att = (0..c.n_slot()).filter(|&il| !c.swa[layer_of(c, il)]).count(); + let kv = 4 * n_att * kv_rows * be0.kv_words(kw) + sc_bytes(c, kv_rows); + let pf0 = PrefillScratch::bytes(be0, c, rank, vocab, pf_cap, false); + let pf1 = if n_parts > 1 { PrefillScratch::bytes(&*d.parts[1].be, c, rank, vocab, pf_cap, true) } else { 0 }; + (f_res + pf0 + kv, (192 << 20) + pf1 + Scratch::at(0, c, rank, 0).end as usize) + }; let key = |s: &[u8]| Some((s.as_ptr() as usize, s.len())); + let on_loop = |ip: usize| (c.loop_start..c.loop_end).contains(&ip); + let order = (c.loop_start..c.loop_end).chain(0..c.loop_start).chain(c.loop_end..c.n_layer); for ip in order { let ml = &m.layers[ip]; let gi_bytes: Vec = ml.gate_inp.iter().flat_map(|x| x.to_le_bytes()).collect(); let bias_bytes: Vec = ml.bias.iter().flat_map(|x| x.to_le_bytes()).collect(); let gs_bytes: Vec = ml.gu_scale.iter().flat_map(|x| x.to_le_bytes()).collect(); let ds_bytes: Vec = ml.down_scale.iter().flat_map(|x| x.to_le_bytes()).collect(); - let Some((gu, dn, gi_slab, bias, gu_scale, dn_scale)) = (|| -> Option<_> { + let place = |part: usize| -> Option<(usize, Arc, Arc, Arc, Arc, Option>, Option>)> { let mut d = dev::get().unwrap().lock().unwrap(); - let gu = d.alloc_slab(ml.gate_up.data, key(ml.gate_up.data), b_res, f_res)?; - let dn = d.alloc_slab(ml.down.data, key(ml.down.data), b_res, f_res)?; - let gi = d.alloc_slab(&gi_bytes, None, b_res, f_res)?; - let bi = d.alloc_slab(&bias_bytes, None, b_res, f_res)?; - let gs = if gs_bytes.is_empty() { None } else { Some(d.alloc_slab(&gs_bytes, None, b_res, f_res)?) }; - let ds = if ds_bytes.is_empty() { None } else { Some(d.alloc_slab(&ds_bytes, None, b_res, f_res)?) }; - Some((gu, dn, gi, bi, gs, ds)) - })() else { + let fr = if part == 0 { res0 } else { res1 }; + let gu = d.alloc_slab_on(part, ml.gate_up.data, key(ml.gate_up.data), b_res, fr)?; + let dn = d.alloc_slab_on(part, ml.down.data, key(ml.down.data), b_res, fr)?; + let gi = d.alloc_slab_on(part, &gi_bytes, None, b_res, fr)?; + let bi = d.alloc_slab_on(part, &bias_bytes, None, b_res, fr)?; + let gs = if gs_bytes.is_empty() { None } else { Some(d.alloc_slab_on(part, &gs_bytes, None, b_res, fr)?) }; + let ds = if ds_bytes.is_empty() { None } else { Some(d.alloc_slab_on(part, &ds_bytes, None, b_res, fr)?) }; + Some((part, gu, dn, gi, bi, gs, ds)) + }; + let prefs: &[usize] = match (n_parts > 1, on_loop(ip)) { (false, _) => &[0], (true, true) => &[0, 1], (true, false) => &[1, 0] }; + let Some((part, gu, dn, gi_slab, bias, gu_scale, dn_scale)) = prefs.iter().find_map(|&p| place(p)) else { break; }; - slab_bytes += gu.len() + dn.len() + gi_slab.len() + bias.len() + let bytes = gu.len() + dn.len() + gi_slab.len() + bias.len() + gu_scale.as_ref().map_or(0, |b| b.len()) + dn_scale.as_ref().map_or(0, |b| b.len()); + slab_bytes += bytes; + per_part[part] += bytes; n_full += 1; let (gu_rows, gu_cols) = (ml.gate_up.rows / c.n_expert, ml.gate_up.cols); let (dn_rows, dn_cols) = (ml.down.rows / c.n_expert, ml.down.cols); layers[ip].full_exps = Some(FullExps { + part, gate_inp: GpuTensor::new(GgmlType::F32, c.n_expert, c.n_embd, Buf::new(gi_slab.addr(), gi_slab.len(), ())), _gi: gi_slab, bias, @@ -332,12 +390,26 @@ impl Device { dn_scale, }); } + if layers.iter().any(|l| l.full_exps.as_ref().is_some_and(|fe| fe.part == 1)) { + let d = dev::get().unwrap().lock().unwrap(); + let be1 = &*d.parts[1].be; + let r_scr = be1.alloc(Scratch::at(0, c, rank, 0).end as usize)?; + let r_s = Scratch::at(r_scr.addr(), c, rank, 0); + let pf = PrefillScratch::alloc(be1, c, rank, vocab, pf_cap, true).ok(); + rem = Some(Remote { part: 1, scr: r_scr, s: r_s, pf }); + } } if std::env::var_os("STRATA_DS_PROF").is_some() { - eprintln!("inkling2: preloaded {n_full}/{} expert layers ({:.2} GB) as contiguous slabs", c.n_layer, slab_bytes as f64 / 1e9); + eprintln!("inkling2: preloaded {n_full}/{} expert layers ({:.2} GB: {:.2} on GPU 0, {:.2} on GPU 1) as contiguous slabs", + c.n_layer, slab_bytes as f64 / 1e9, per_part[0] as f64 / 1e9, per_part[1] as f64 / 1e9); } - let all_full = layers.iter().all(|l| l.full_exps.is_some()); - Ok(Device { layers, loops, slots, out_query, out_norm, scr, sc_buf, pf: None, s, rank, all_full, graph_keys: [0; 2], synced: 0, ahead: false }) + let all_full = rem.is_none() && layers.iter().all(|l| l.full_exps.is_some()); + let core = c.loop_end - c.loop_start; + let seg_graph = rem.is_some() && std::env::var_os("STRATA_DS_NO_SEG_GRAPH").is_none() + && layers.iter().all(|l| l.full_exps.is_some()) + && (c.loop_start..c.loop_end).all(|ip| layers[ip].full_exps.as_ref().is_some_and(|fe| fe.part == 0)) + && (c.loop_count * core) % 2 == 0; + Ok(Device { layers, loops, slots, out_query, out_norm, scr, sc_buf, pf: None, s, rank, all_full, rem, seg_graph, loop_nb: 0, graph_keys: [0; 2], synced: 0, ahead: false }) })(); made.inspect_err(|e| eprintln!("inkling2: no room in VRAM for the decode state ({e:#}); the tokens run as prompt chunks do")).ok() } @@ -501,45 +573,97 @@ impl Device { // 17 MiB of device memory, and the backend stops recording at 32 of them). let last = std::mem::replace(&mut self.graph_keys[argmax as usize], key); if last != 0 && last != key { be.graph_drop(last)?; } - be.graph(key, &mut || { + if !self.seg_graph { + be.graph(key, &mut || { + let mut nb = 0usize; + for il in 0..c.loop_start { + self.layer_attn(be, &d, m, il, il, false, pos, true, &mut nb)?; + self.layer_ffn_gpu(be, m, il, il)?; + } + be.dtod(&self.scr, (self.s.cur - o) as usize, &self.scr, (self.s.prelude - o) as usize, 4 * n)?; + let n_pre = nb; + for pass in 0..c.loop_count { + let n_bank = nb.saturating_sub(n_pre + 1); + if pass > 0 { + let s = self.s; + if n_bank > 0 { + be.dtod(&self.scr, (s.blocks - o) as usize + 4 * (n_pre + 1) * n, &self.scr, (s.bank - o) as usize, 4 * n_bank * n)?; + } + be.dtod(&self.scr, (s.cur - o) as usize, &self.scr, (s.outb - o) as usize, 4 * n)?; + be.dtod(&self.scr, (s.prelude - o) as usize, &self.scr, (s.cur - o) as usize, 4 * n)?; + nb = n_pre; + } + for ip in c.loop_start..c.loop_end { + let il = if pass == 0 { ip } else { c.n_layer + (pass - 1) * core + ip - c.loop_start }; + if pass > 0 { + let s = self.s; + be.ink_mix(s.bank, n_bank, s.outb, self.loops[ip - c.loop_start].msg_query.addr(), 4, s.msg, n)?; + } + self.layer_attn(be, &d, m, il, ip, pass > 0, pos, true, &mut nb)?; + self.layer_ffn_gpu(be, m, il, ip)?; + } + } + for il in c.loop_end..c.n_layer { + self.layer_attn(be, &d, m, il, il, false, pos, true, &mut nb)?; + self.layer_ffn_gpu(be, m, il, il)?; + } + self.finish_logits(be, &d, m, nb)?; + if argmax { + be.argmax_rows(self.s.logits, c.n_vocab, 1, self.s.amax)?; + } + Ok(()) + })?; + } else { + // Local patch: layers 0..loop_start and loop_end.. launch one by one (their FFN may be on GPU 1, which needs + // the host between the attention and the experts); the loop between them is one graph. + let prof = std::env::var_os("STRATA_DS_PROF").is_some(); + let mut tt = std::time::Instant::now(); let mut nb = 0usize; for il in 0..c.loop_start { self.layer_attn(be, &d, m, il, il, false, pos, true, &mut nb)?; - self.layer_ffn_gpu(be, m, il, il)?; + if !self.layer_ffn_remote(&d, m, il, il)? { self.layer_ffn_gpu(be, m, il, il)?; } } - be.dtod(&self.scr, (self.s.cur - o) as usize, &self.scr, (self.s.prelude - o) as usize, 4 * n)?; + if prof { be.sync()?; m.lap(1, tt); tt = std::time::Instant::now(); } let n_pre = nb; - for pass in 0..c.loop_count { - let n_bank = nb.saturating_sub(n_pre + 1); - if pass > 0 { - let s = self.s; - if n_bank > 0 { - be.dtod(&self.scr, (s.blocks - o) as usize + 4 * (n_pre + 1) * n, &self.scr, (s.bank - o) as usize, 4 * n_bank * n)?; - } - be.dtod(&self.scr, (s.cur - o) as usize, &self.scr, (s.outb - o) as usize, 4 * n)?; - be.dtod(&self.scr, (s.prelude - o) as usize, &self.scr, (s.cur - o) as usize, 4 * n)?; - nb = n_pre; - } - for ip in c.loop_start..c.loop_end { - let il = if pass == 0 { ip } else { c.n_layer + (pass - 1) * core + ip - c.loop_start }; + be.graph(key, &mut || { + let mut nb = n_pre; + be.dtod(&self.scr, (self.s.cur - o) as usize, &self.scr, (self.s.prelude - o) as usize, 4 * n)?; + for pass in 0..c.loop_count { + let n_bank = nb.saturating_sub(n_pre + 1); if pass > 0 { let s = self.s; - be.ink_mix(s.bank, n_bank, s.outb, self.loops[ip - c.loop_start].msg_query.addr(), 4, s.msg, n)?; + if n_bank > 0 { + be.dtod(&self.scr, (s.blocks - o) as usize + 4 * (n_pre + 1) * n, &self.scr, (s.bank - o) as usize, 4 * n_bank * n)?; + } + be.dtod(&self.scr, (s.cur - o) as usize, &self.scr, (s.outb - o) as usize, 4 * n)?; + be.dtod(&self.scr, (s.prelude - o) as usize, &self.scr, (s.cur - o) as usize, 4 * n)?; + nb = n_pre; + } + for ip in c.loop_start..c.loop_end { + let il = if pass == 0 { ip } else { c.n_layer + (pass - 1) * core + ip - c.loop_start }; + if pass > 0 { + let s = self.s; + be.ink_mix(s.bank, n_bank, s.outb, self.loops[ip - c.loop_start].msg_query.addr(), 4, s.msg, n)?; + } + self.layer_attn(be, &d, m, il, ip, pass > 0, pos, true, &mut nb)?; + self.layer_ffn_gpu(be, m, il, ip)?; } - self.layer_attn(be, &d, m, il, ip, pass > 0, pos, true, &mut nb)?; - self.layer_ffn_gpu(be, m, il, ip)?; } - } + self.loop_nb = nb; + Ok(()) + })?; + if prof { be.sync()?; m.lap(2, tt); tt = std::time::Instant::now(); } + let mut nb = self.loop_nb; for il in c.loop_end..c.n_layer { self.layer_attn(be, &d, m, il, il, false, pos, true, &mut nb)?; - self.layer_ffn_gpu(be, m, il, il)?; + if !self.layer_ffn_remote(&d, m, il, il)? { self.layer_ffn_gpu(be, m, il, il)?; } } + if prof { be.sync()?; m.lap(3, tt); } self.finish_logits(be, &d, m, nb)?; if argmax { be.argmax_rows(self.s.logits, c.n_vocab, 1, self.s.amax)?; } - Ok(()) - })?; + } if argmax { let id = be.get::(&self.scr, ((self.s.amax - o) / 4) as usize, 1)?[0] as u32; Ok((Vec::new(), id)) @@ -609,7 +733,7 @@ impl Device { let pos = m.toks.len(); assert!(pos < m.max_ctx, "context is limited to {} tokens", m.max_ctx); assert!((tok as usize) < m.tok_embd.rows, "token {tok} is outside the vocabulary"); - if self.all_full { + if self.all_full || self.seg_graph { let t = std::time::Instant::now(); let (logits, _) = self.step_fast(m, tok, false); m.lap(7, t); @@ -633,7 +757,7 @@ impl Device { let pos = m.toks.len(); assert!(pos < m.max_ctx, "context is limited to {} tokens", m.max_ctx); assert!((tok as usize) < m.tok_embd.rows, "token {tok} is outside the vocabulary"); - if self.all_full { + if self.all_full || self.seg_graph { let t = std::time::Instant::now(); let (_, id) = self.step_fast(m, tok, true); m.lap(7, t); @@ -659,12 +783,12 @@ impl Device { be.sync()?; self.pf = None; } - let target = need_nt.max(256).min(256); + let target = need_nt.max(pf_tokens()); let mut tries = vec![target]; if need_nt < target { tries.push(need_nt.max(128)); tries.push(need_nt.max(64)); tries.push(need_nt); } let mut last_err = None; for cap in tries { - match PrefillScratch::alloc(be, c, self.rank, vocab_rows, cap) { + match PrefillScratch::alloc(be, c, self.rank, vocab_rows, cap, false) { Ok(pf) => { self.pf = Some(pf); return Ok(()); } Err(e) => last_err = Some(e), } @@ -672,6 +796,17 @@ impl Device { Err(last_err.unwrap()) } + /// GPU 1's prefill scratch for `need_nt` rows, when some layer's experts live there. + fn ensure_pf_remote(&mut self, d: &dev::Dev, c: &Inkling2Config, vocab_rows: usize, need_nt: usize) -> Result<()> { + let rank = self.rank; + let Some(r) = &mut self.rem else { return Ok(()) }; + if r.pf.as_ref().is_some_and(|pf| pf.max_nt >= need_nt) { return Ok(()); } + let be1 = &*d.parts[r.part].be; + if r.pf.is_some() { be1.sync()?; r.pf = None; } + r.pf = Some(PrefillScratch::alloc(be1, c, rank, vocab_rows, need_nt.max(pf_tokens()), true)?); + Ok(()) + } + /// Project a single corrected hidden vector `h_corr` (`[n_embd]`) through the target's LM head on GPU /// and return the argmax token ID (`0..c.n_vocab`). No softcap: `softcap * tanh(x / softcap)` keeps the /// order of the logits (two that differ by a few ulp may become equal), and the token is a draft that @@ -726,6 +861,7 @@ impl Device { let d = dev::get().unwrap().lock().unwrap(); let be = &*d.parts[0].be; self.ensure_pf(be, c, m.output.rows, nt)?; + self.ensure_pf_remote(&d, c, m.output.rows, nt)?; if !self.ahead { self.to_device(m, be, pos0)?; } let pf = self.pf.as_ref().unwrap(); be.put(&cur_host, &pf.buf, 0)?; @@ -839,6 +975,7 @@ impl Device { let d = dev::get().unwrap().lock().unwrap(); let be = &*d.parts[0].be; self.ensure_pf(be, c, m.output.rows, nt)?; + self.ensure_pf_remote(&d, c, m.output.rows, nt)?; if !self.ahead { self.to_device(m, be, pos0)?; } let pf = self.pf.as_ref().unwrap(); for (il, ds) in self.slots.iter().enumerate() { @@ -1127,7 +1264,7 @@ impl Device { h = p.h2; } if let Some(fe) = &l.full_exps { - let use_gemm = !small && fe.gu_cols % 64 == 0 && fe.dn_cols % 64 == 0; + let use_gemm = (!small || fe.part != 0) && fe.gu_cols % 64 == 0 && fe.dn_cols % 64 == 0; if use_gemm || fe.gu_ty.float_x() { be.rms_norm(h, n, l.ffn_norm.addr(), p.hn, n, n, nt, c.eps)?; } else { @@ -1135,86 +1272,24 @@ impl Device { } m.lap(0, t_prep); let t_gpu = std::time::Instant::now(); - Self::proj_n(be, &fe.gate_inp, small, nt, p.hn, 0, p.rlogits, 0)?; - let gu_sc = fe.gu_scale.as_ref().map_or(0, |b| b.addr()); - let dn_sc = fe.dn_scale.as_ref().map_or(0, |b| b.addr()); - let gsc_out = if gu_sc != 0 { p.gsc } else { 0 }; - be.ink_route(p.rlogits, fe.bias.addr(), p.ids, p.wts, gu_sc, dn_sc, gsc_out, c.n_expert, k, c.exp_scale, nt)?; - if !use_gemm { - // Process up to 16 tokens per moe_gemv batch so zero host sync is needed (exact decode speed for nt <= 16). - for tok0 in (0..nt).step_by(16) { - let bt = (nt - tok0).min(16); - let np = bt * k; - let xh_tok_floats = (n + n.div_ceil(32) * 4).div_ceil(16) * 4; - let ids_a = p.ids + (4 * tok0 * k) as u64; - let wts_a = p.wts + f(tok0 * k); - let gsc_a = if gu_sc != 0 { p.gsc + f(tok0 * k) } else { 0 }; - let hn_a = p.hn + f(tok0 * n); - let xh_a = p.xh + f(tok0 * xh_tok_floats); - let y_a = p.y; - let d_a = p.d; - let acc_a = pf.acc_buf.addr() + f(tok0 * n); - be.moe_gemv(fe.gu_ty, fe.gu_rows, fe.gu_cols, fe.gu.addr(), fe.gu_stride, ids_a, np, hn_a, n, k, y_a, None, xh_a)?; - if fe.dn_ty.float_x() || nf % 32 != 0 { - be.situ(y_a, nf, np, gsc_a, c.situ_beta, c.situ_linear_beta)?; - be.moe_gemv(fe.dn_ty, fe.dn_rows, fe.dn_cols, fe.dn.addr(), fe.dn_stride, ids_a, np, y_a, 2 * nf, 1, d_a, None, 0)?; - } else { - be.situ_q(y_a, nf, np, gsc_a, c.situ_beta, c.situ_linear_beta, p.xq)?; - be.moe_gemv(fe.dn_ty, fe.dn_rows, fe.dn_cols, fe.dn.addr(), fe.dn_stride, ids_a, np, y_a, 2 * nf, 1, d_a, None, p.xq)?; - } - be.ink_ffn_sum_n(acc_a, d_a, wts_a, k, n, bt, 0)?; - } + if fe.part == 0 { + Self::pf_ffn_core(be, m, ip, fe, pf, nt, small, use_gemm)?; } else { - use crate::backend::GEMM_BM; - let ids: Vec = be.get(&pf.buf, ((p.ids - buf_o) / 4) as usize, nt * k)?; - let mut by_e: Vec> = vec![vec![]; c.n_expert]; - for (t, row) in ids.chunks_exact(k).enumerate() { - for (j, &e) in row.iter().enumerate() { by_e[e as usize].push((t, j)); } - } - let np = nt * k; - let mut tiles_gu: Vec = Vec::with_capacity(2 * (c.n_expert + np / GEMM_BM)); - let mut tiles_dn: Vec = Vec::with_capacity(2 * (c.n_expert + np / GEMM_BM)); - let mut xrow: Vec = Vec::with_capacity(np); - let mut inv: Vec = vec![0i32; nt * k]; - let mut gsc_rows: Vec = if ml.gu_scale.is_empty() { Vec::new() } else { Vec::with_capacity(np) }; - let mut m0 = 0usize; - for e in 0..c.n_expert { - if by_e[e].is_empty() { continue; } - let wg = fe.gu.addr() + (e * fe.gu_stride) as u64; - let wd = fe.dn.addr() + (e * fe.dn_stride) as u64; - for at in (0..by_e[e].len()).step_by(GEMM_BM) { - let cnt = GEMM_BM.min(by_e[e].len() - at) as u64; - tiles_gu.extend([wg, (m0 + at) as u64 | (cnt << 32)]); - tiles_dn.extend([wd, (m0 + at) as u64 | (cnt << 32)]); - } - for &(t, j) in &by_e[e] { - inv[t * k + j] = xrow.len() as i32; - xrow.push(t as i32); - if !ml.gu_scale.is_empty() { gsc_rows.push(ml.gu_scale[e]); } - } - m0 += by_e[e].len(); + // Experts on GPU 1: the normed rows cross over, the experts run there, the sum comes back. + let r = self.rem.as_ref().ok_or_else(|| anyhow::anyhow!("experts on GPU 1 without a scratch there"))?; + let pf1 = r.pf.as_ref().ok_or_else(|| anyhow::anyhow!("no prefill scratch on GPU 1"))?; + let be1 = &*d.parts[r.part].be; + let (o0, o1) = (buf_o, pf1.buf.addr()); + let hn: Vec = be.get(&pf.buf, ((p.hn - o0) / 4) as usize, nt * n)?; + be1.put(&hn, &pf1.buf, ((pf1.p.hn - o1) / 4) as usize)?; + if !use_gemm && !fe.gu_ty.float_x() { + let xw = (n + n.div_ceil(32) * 4).div_ceil(16) * 4; + let xh: Vec = be.get(&pf.buf, ((p.xh - o0) / 4) as usize, nt * xw)?; + be1.put(&xh, &pf1.buf, ((pf1.p.xh - o1) / 4) as usize)?; } - let n_tiles = tiles_gu.len() / 2; - let dn_off = 8 * tiles_gu.len(); - let xr_off = dn_off + 8 * tiles_dn.len(); - let inv_off = xr_off + 4 * np; - ensure!(inv_off + 4 * nt * k <= pf.meta.len(), "prefill meta overflow"); - be.put(&tiles_gu, &pf.meta, 0)?; - be.put(&tiles_dn, &pf.meta, dn_off / 8)?; - be.put(&xrow, &pf.meta, xr_off / 4)?; - be.put(&inv, &pf.meta, inv_off / 4)?; - let gsc_a = if !gsc_rows.is_empty() { - be.put(&gsc_rows, &pf.buf, ((p.gsc - buf_o) / 4) as usize)?; - p.gsc - } else { - 0 - }; - let ma = pf.meta.addr(); - be.gemm(fe.gu_ty, fe.gu_rows, fe.gu_cols, ma, n_tiles, p.hn, n, nt, ma + xr_off as u64, p.y, 2 * nf, 0)?; - be.situ(p.y, nf, np, gsc_a, c.situ_beta, c.situ_linear_beta)?; - be.gemm(fe.dn_ty, fe.dn_rows, fe.dn_cols, ma + dn_off as u64, n_tiles, p.y, 2 * nf, np, 0, p.d, n, 0)?; - be.memset(&pf.acc_buf)?; - be.moe_combine_seq(pf.acc_buf.addr(), p.d, p.wts, ma + inv_off as u64, k, 0, 0, n, nt)?; + Self::pf_ffn_core(be1, m, ip, fe, pf1, nt, small, use_gemm)?; + let acc: Vec = be1.get(&pf1.acc_buf, 0, nt * n)?; + be.put(&acc, &pf.acc_buf, 0)?; } if verify_mode { be.dtod(&pf.acc_buf, 0, &pf.conv_log, log_base + 4 * VERIFY_MAX * (2 * kw + n), 4 * nt * n)?; @@ -1250,6 +1325,97 @@ impl Device { Ok(()) } + /// The routed experts of a prompt chunk on the GPU `be` runs on: from the normed rows in `pf.p.hn` (and, below the + /// GEMM size, their quantized copy in `pf.p.xh`) to the weighted sum in `pf.acc_buf`. + #[allow(clippy::too_many_arguments)] + fn pf_ffn_core(be: &dyn Backend, m: &Inkling2Model, ip: usize, fe: &FullExps, pf: &PrefillScratch, nt: usize, small: bool, use_gemm: bool) -> Result<()> { + let (c, ml) = (&m.cfg, &m.layers[ip]); + let (n, nf, k) = (c.n_embd, c.n_ff_exp, c.n_used); + let (p, buf_o) = (pf.p, pf.buf.addr()); + Self::proj_n(be, &fe.gate_inp, small, nt, p.hn, 0, p.rlogits, 0)?; + let gu_sc = fe.gu_scale.as_ref().map_or(0, |b| b.addr()); + let dn_sc = fe.dn_scale.as_ref().map_or(0, |b| b.addr()); + let gsc_out = if gu_sc != 0 { p.gsc } else { 0 }; + be.ink_route(p.rlogits, fe.bias.addr(), p.ids, p.wts, gu_sc, dn_sc, gsc_out, c.n_expert, k, c.exp_scale, nt)?; + if !use_gemm { + // Process up to 16 tokens per moe_gemv batch so zero host sync is needed (exact decode speed for nt <= 16). + for tok0 in (0..nt).step_by(16) { + let bt = (nt - tok0).min(16); + let np = bt * k; + let xh_tok_floats = (n + n.div_ceil(32) * 4).div_ceil(16) * 4; + let ids_a = p.ids + (4 * tok0 * k) as u64; + let wts_a = p.wts + f(tok0 * k); + let gsc_a = if gu_sc != 0 { p.gsc + f(tok0 * k) } else { 0 }; + let hn_a = p.hn + f(tok0 * n); + let xh_a = p.xh + f(tok0 * xh_tok_floats); + let y_a = p.y; + let d_a = p.d; + let acc_a = pf.acc_buf.addr() + f(tok0 * n); + be.moe_gemv(fe.gu_ty, fe.gu_rows, fe.gu_cols, fe.gu.addr(), fe.gu_stride, ids_a, np, hn_a, n, k, y_a, None, xh_a)?; + if fe.dn_ty.float_x() || nf % 32 != 0 { + be.situ(y_a, nf, np, gsc_a, c.situ_beta, c.situ_linear_beta)?; + be.moe_gemv(fe.dn_ty, fe.dn_rows, fe.dn_cols, fe.dn.addr(), fe.dn_stride, ids_a, np, y_a, 2 * nf, 1, d_a, None, 0)?; + } else { + be.situ_q(y_a, nf, np, gsc_a, c.situ_beta, c.situ_linear_beta, p.xq)?; + be.moe_gemv(fe.dn_ty, fe.dn_rows, fe.dn_cols, fe.dn.addr(), fe.dn_stride, ids_a, np, y_a, 2 * nf, 1, d_a, None, p.xq)?; + } + be.ink_ffn_sum_n(acc_a, d_a, wts_a, k, n, bt, 0)?; + } + } else { + use crate::backend::GEMM_BM; + let ids: Vec = be.get(&pf.buf, ((p.ids - buf_o) / 4) as usize, nt * k)?; + let mut by_e: Vec> = vec![vec![]; c.n_expert]; + for (t, row) in ids.chunks_exact(k).enumerate() { + for (j, &e) in row.iter().enumerate() { by_e[e as usize].push((t, j)); } + } + let np = nt * k; + let mut tiles_gu: Vec = Vec::with_capacity(2 * (c.n_expert + np / GEMM_BM)); + let mut tiles_dn: Vec = Vec::with_capacity(2 * (c.n_expert + np / GEMM_BM)); + let mut xrow: Vec = Vec::with_capacity(np); + let mut inv: Vec = vec![0i32; nt * k]; + let mut gsc_rows: Vec = if ml.gu_scale.is_empty() { Vec::new() } else { Vec::with_capacity(np) }; + let mut m0 = 0usize; + for e in 0..c.n_expert { + if by_e[e].is_empty() { continue; } + let wg = fe.gu.addr() + (e * fe.gu_stride) as u64; + let wd = fe.dn.addr() + (e * fe.dn_stride) as u64; + for at in (0..by_e[e].len()).step_by(GEMM_BM) { + let cnt = GEMM_BM.min(by_e[e].len() - at) as u64; + tiles_gu.extend([wg, (m0 + at) as u64 | (cnt << 32)]); + tiles_dn.extend([wd, (m0 + at) as u64 | (cnt << 32)]); + } + for &(t, j) in &by_e[e] { + inv[t * k + j] = xrow.len() as i32; + xrow.push(t as i32); + if !ml.gu_scale.is_empty() { gsc_rows.push(ml.gu_scale[e]); } + } + m0 += by_e[e].len(); + } + let n_tiles = tiles_gu.len() / 2; + let dn_off = 8 * tiles_gu.len(); + let xr_off = dn_off + 8 * tiles_dn.len(); + let inv_off = xr_off + 4 * np; + ensure!(inv_off + 4 * nt * k <= pf.meta.len(), "prefill meta overflow"); + be.put(&tiles_gu, &pf.meta, 0)?; + be.put(&tiles_dn, &pf.meta, dn_off / 8)?; + be.put(&xrow, &pf.meta, xr_off / 4)?; + be.put(&inv, &pf.meta, inv_off / 4)?; + let gsc_a = if !gsc_rows.is_empty() { + be.put(&gsc_rows, &pf.buf, ((p.gsc - buf_o) / 4) as usize)?; + p.gsc + } else { + 0 + }; + let ma = pf.meta.addr(); + be.gemm(fe.gu_ty, fe.gu_rows, fe.gu_cols, ma, n_tiles, p.hn, n, nt, ma + xr_off as u64, p.y, 2 * nf, 0)?; + be.situ(p.y, nf, np, gsc_a, c.situ_beta, c.situ_linear_beta)?; + be.gemm(fe.dn_ty, fe.dn_rows, fe.dn_cols, ma + dn_off as u64, n_tiles, p.y, 2 * nf, np, 0, p.d, n, 0)?; + be.memset(&pf.acc_buf)?; + be.moe_combine_seq(pf.acc_buf.addr(), p.d, p.wts, ma + inv_off as u64, k, 0, 0, n, nt)?; + } + Ok(()) + } + fn layer_attn(&self, be: &dyn Backend, d: &dev::Dev, m: &Inkling2Model, il: usize, ip: usize, msgs: bool, pos: usize, graph: bool, nb: &mut usize) -> Result<()> { let (c, ml, l, ds, s, rank) = (&m.cfg, &m.layers[ip], &self.layers[ip], &self.slots[il], self.s, self.rank); let (n, hd, nh, nkv, nr, nc) = (c.n_embd, c.head_dim, c.n_head, c.n_head_kv, c.n_rel, c.n_conv); @@ -1343,11 +1509,10 @@ impl Device { be.rms_norm_q(h, n, l.ffn_norm.addr(), s.hn, n, n, 1, c.eps, s.xh, 0) } - fn layer_ffn_gpu(&mut self, be: &dyn Backend, m: &Inkling2Model, il: usize, ip: usize) -> Result { - let Some(fe) = &self.layers[ip].full_exps else { return Ok(false) }; - let (c, ds, s) = (&m.cfg, &self.slots[il], self.s); - let (n, hd, nc, nf, k) = (c.n_embd, c.head_dim, c.n_conv, c.n_ff_exp, c.n_used); - let hist3 = ds.hist.addr() + f(hists(c).0[3]); + /// The routed experts of one token on the GPU `be` runs on, from the normed input in `s.hn` (and its quantized + /// copy `s.xh`) to the weighted sum in `s.acc`. All of it stays on that device. + fn ffn_core(be: &dyn Backend, c: &Inkling2Config, s: Scratch, fe: &FullExps) -> Result<()> { + let (n, nf, k) = (c.n_embd, c.n_ff_exp, c.n_used); be.gemv(&fe.gate_inp, s.hn, s.rlogits)?; let gu_sc = fe.gu_scale.as_ref().map_or(0, |b| b.addr()); let dn_sc = fe.dn_scale.as_ref().map_or(0, |b| b.addr()); @@ -1361,10 +1526,44 @@ impl Device { be.situ_q(s.y, nf, k, gsc_a, c.situ_beta, c.situ_linear_beta, s.xq)?; be.moe_gemv(fe.dn_ty, fe.dn_rows, fe.dn_cols, fe.dn.addr(), fe.dn_stride, s.ids, k, s.y, 2 * nf, 1, s.d, None, s.xq)?; } - be.ink_ffn_sum(s.acc, s.d, s.wc, k, n, 0)?; + be.ink_ffn_sum(s.acc, s.d, s.wc, k, n, 0) + } + + /// What follows the experts of a layer run: the short convolution, the residual add, and the swap of the streams. + fn ffn_tail(&mut self, be: &dyn Backend, m: &Inkling2Model, il: usize, ip: usize) -> Result<()> { + let (c, ds, s) = (&m.cfg, &self.slots[il], self.s); + let (n, hd, nc) = (c.n_embd, c.head_dim, c.n_conv); + let hist3 = ds.hist.addr() + f(hists(c).0[3]); 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)?; (self.s.cur, self.s.x) = (s.x, s.cur); + Ok(()) + } + + fn layer_ffn_gpu(&mut self, be: &dyn Backend, m: &Inkling2Model, il: usize, ip: usize) -> Result { + let Some(fe) = &self.layers[ip].full_exps else { return Ok(false) }; + Self::ffn_core(be, &m.cfg, self.s, fe)?; + self.ffn_tail(be, m, il, ip)?; + Ok(true) + } + + /// `layer_ffn_gpu` for a layer whose experts are on GPU 1: the normed input crosses to it through the host, the + /// experts run there, and the sum comes back (two small copies and two syncs per layer run). False: not that kind of layer. + fn layer_ffn_remote(&mut self, d: &dev::Dev, m: &Inkling2Model, il: usize, ip: usize) -> Result { + let (Some(fe), Some(r)) = (&self.layers[ip].full_exps, &self.rem) else { return Ok(false) }; + if fe.part == 0 { return Ok(false) } + let (c, s, rs) = (&m.cfg, self.s, r.s); + let (be0, be1) = (&*d.parts[0].be, &*d.parts[r.part].be); + let (n, o0, o1) = (c.n_embd, self.scr.addr(), r.scr.addr()); + let xh_words = (n + n.div_ceil(32) * 4).div_ceil(16) * 4; + let hn: Vec = be0.get(&self.scr, ((s.hn - o0) / 4) as usize, n)?; + let xh: Vec = be0.get(&self.scr, ((s.xh - o0) / 4) as usize, xh_words)?; + be1.put(&hn, &r.scr, ((rs.hn - o1) / 4) as usize)?; + be1.put(&xh, &r.scr, ((rs.xh - o1) / 4) as usize)?; + Self::ffn_core(be1, c, rs, fe)?; + let acc: Vec = be1.get(&r.scr, ((rs.acc - o1) / 4) as usize, n)?; + be0.put(&acc, &self.scr, ((s.acc - o0) / 4) as usize)?; + self.ffn_tail(be0, m, il, ip)?; Ok(true) } @@ -1381,7 +1580,7 @@ impl Device { let d = lock(); let be = &*d.parts[0].be; self.layer_attn(be, &d, m, il, ip, msgs, pos, false, nb).expect("inkling2 device step"); - if self.layer_ffn_gpu(be, m, il, ip).expect("inkling2 device step") { + if self.layer_ffn_remote(&d, m, il, ip).expect("inkling2 device step remote") || self.layer_ffn_gpu(be, m, il, ip).expect("inkling2 device step") { m.lap(0, t); return; } @@ -1390,9 +1589,12 @@ 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); + // Local patch: an expert with a matrix on another GPU cannot run in this GPU's queue; `remote` runs through + // `run_experts` (each matrix where it lives), next to the CPU share. + let on_first = |x: &Mat| x.gpu.is_none_or(|i| i == dev::STAGED || dev::gpu_of(i) == 0); + let (list, remote): (Vec<_>, Vec<_>) = Inkling2Model::resident(ml, c.n_expert, &on_gpu).into_iter().partition(|e| on_first(&e.0) && on_first(&e.1)); let gpu_side = || -> Option { let t = std::time::Instant::now(); - let list = Inkling2Model::resident(ml, c.n_expert, &on_gpu); let d = lock(); let (p, mut owned) = (&d.parts[0], vec![]); (|| -> Option<()> { @@ -1435,15 +1637,17 @@ impl Device { let t = std::time::Instant::now(); (run_experts(&on_cpu, &hn, c), t.elapsed().as_secs_f32()) }; - let (gpu, (cpu, tc)) = rayon::join(gpu_side, cpu_side); + let remote_side = || (!remote.is_empty()).then(|| run_experts(&remote, &hn, c)); + let (gpu, ((cpu, tc), rem)) = rayon::join(gpu_side, || rayon::join(cpu_side, remote_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(); + let host: Vec = match rem { Some(r) => cpu.iter().zip(&r).map(|(a, b)| a + b).collect(), None => cpu }; + let wc: Vec = (0..c.n_used).map(|i| list.get(i).map_or(0.0, |e| e.2)).chain(host).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"); + be.ink_ffn_sum(s.acc, s.d, s.wc, list.len(), n, s.wc + f(c.n_used)).expect("inkling2 device step"); } None => { // No room to stage a routed weight (a card with little free VRAM): the experts of the GPU run on From 00593f2e7d908a0b054ec4fd671242e87e5467e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Sacilotti?= Date: Tue, 24 Nov 2026 04:12:50 -0300 Subject: [PATCH 2/9] bench: an Inkling 2 benchmark uses the defaults chat and serve use bench_inkling2 called only deepseek::chat::gpu_defaults(), which turns the GPU on but not the Inkling 2 defaults: STRATA_DS_GPU_FRACTION=0.6,0.9 (the share of free VRAM the expert cache may take; 0.8 without it) was missing, so bench kept fewer expert layers in VRAM than chat, generate and serve do for the same model and flags, and reported a smaller cache than the one those commands run with. (The other Inkling 2 default, STRATA_DS_PLAIN_FIRST, is a no-op until the multi-GPU work lands.) One card, bench --pp 512,2048 --tg 16 --ctx 8192 --device 0, the only difference being that fraction, median of 2: | | prefill 512 | prefill 2048 | decode 512 / 2048 | |---|---|---|---| | before (0.8) | 106.9 | 163.7 | 18.3 / 18.3 | | after (0.9) | 109.4 (+2.3%) | 177.6 (+8.5%) | 20.2 (+10.4%) / 18.9 (+3.6%) | (cherry picked from commit 9b449a11839ba53e0f768f81228b13b75bfbbb2a) --- src/main.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main.rs b/src/main.rs index 39820459..64935fa1 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1967,7 +1967,9 @@ bench_tokenwise!(bench_hy4, rusting_strata::hy4::forward::Hy4Model); /// `strata bench` for Inkling 2 (uses GPU argmax decode, plus `--draft-model` DSpark / `--spec-type` context lookup). fn bench_inkling2(g: &Gguf, model: &Path, pp: &[usize], tg: usize, reps: usize, json_out: Option, engine: &mut Engine) -> anyhow::Result<()> { - rusting_strata::deepseek::chat::gpu_defaults(); + // The same defaults `chat`, `generate` and `serve` set: without them the plain weights spread over both cards, + // `Device::new` refuses the second one and the whole benchmark runs the host path (about a fifth of the speed). + rusting_strata::inkling2::chat::gpu_defaults(); let tok = Tokenizer::from_gguf(g)?; let max_ctx = engine.ctx.max(pp.iter().copied().max().unwrap_or(0) + tg + 64); let opts = rusting_strata::inkling2::chat::Inkling2Opts { From d68cd83bd8675b4afac1972102e4afd963bb736b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Sacilotti?= Date: Mon, 23 Nov 2026 12:40:19 -0300 Subject: [PATCH 3/9] tools: bench_2x3060.sh, the two-card Inkling 2 matrix One fresh process per (ctx, prompt length) row: the KV and the prefill scratch are sized by the context, and the load line goes with every row because how many expert layers fit depends on the free VRAM at load. (cherry picked from commit e7b8896fc630ee982d1016015a4b8712e3379c92) --- tools/bench_2x3060.sh | 53 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100755 tools/bench_2x3060.sh diff --git a/tools/bench_2x3060.sh b/tools/bench_2x3060.sh new file mode 100755 index 00000000..e794af1f --- /dev/null +++ b/tools/bench_2x3060.sh @@ -0,0 +1,53 @@ +#!/usr/bin/env bash +# Inkling 2 on two RTX 3060s: prompt lengths at a 32k and a 200k context, greedy decode, one repetition each. +# tools/bench_2x3060.sh [--model PATH] [--out STEM] [--pp LIST] [--ctx LIST] [--tg N] +# Prints one table row per (ctx, pp); with --out writes STEM--.json (`strata.bench.v1`) per row. +# +# The load line is printed under each row: how many expert layers are in VRAM and where decides most of the speed, +# and it depends on the free VRAM at that moment (a desktop on GPU 0 costs layers). A run whose line differs from +# the one in docs/BENCHMARKS.md is not comparable to it. +set -euo pipefail +cd "$(dirname "$0")/.." +model=${STRATA_INKLING2_MODEL:-/home/andre/strata/models/Inkling-2-Mini-GGUF/Inkling-2-Mini-UD-IQ4_XS.gguf} +out="" +pp_list="512,2048,4096" +ctx_list="32768 200000" +tg=32 +while [ $# -gt 0 ]; do + case "$1" in + --model) model=$2; shift 2 ;; + --out) out=$2; shift 2 ;; + --pp) pp_list=$2; shift 2 ;; + --ctx) ctx_list=$2; shift 2 ;; + --tg) tg=$2; shift 2 ;; + *) echo "unknown option: $1" >&2; exit 1 ;; + esac +done +bin=${BIN:-target/release/rustingstrata} +# The runtime CUDA libraries the driver ships (cu13 here) come first: an older /usr/local/cuda libnvrtc compiles +# the kernels and the forward falls back to the host. +export LD_LIBRARY_PATH=$HOME/nvrtc13/lib/python3.11/site-packages/nvidia/cu13/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH} +[ -f "$bin" ] || { echo "no $bin (cargo build --release)" >&2; exit 1; } +printf '%-8s %-10s %10s %10s\n' ctx pp prefill decode +for ctx in $ctx_list; do + for pp in ${pp_list//,/ }; do + log=$(mktemp) + # A fresh process per row: the prefill scratch and the KV are sized by the context, and a second prompt in the + # same process reuses them (a different measurement). + if [ -n "$out" ]; then + env -u STRATA_DS_PLAIN_FIRST STRATA_DS_KV_TOKENS="$ctx" STRATA_DS_PF_TOKENS=512 \ + "$bin" bench --model "$model" --pp "$pp" --tg "$tg" --reps 1 --ctx "$ctx" --device 0,1 --gpu \ + --json-out "$out-$ctx-$pp.json" >"$log" 2>&1 + else + env -u STRATA_DS_PLAIN_FIRST STRATA_DS_KV_TOKENS="$ctx" STRATA_DS_PF_TOKENS=512 \ + "$bin" bench --model "$model" --pp "$pp" --tg "$tg" --reps 1 --ctx "$ctx" --device 0,1 --gpu \ + >"$log" 2>&1 + fi + row=$(grep -E '^pp ' "$log" | tail -1) + [ -n "$row" ] || { echo "ctx $ctx pp $pp: no result"; sed -n '1,20p' "$log"; rm -f "$log"; continue; } + # `pp 512: prefill V (...) tok/s | tg 32: decode D (...) tok/s`. + printf '%-8s %-10s %10s %10s\n' "$ctx" "$pp" "$(awk '{print $4}' <<<"$row")" "$(awk '{print $11}' <<<"$row")" + grep -E '^inkling2: preloaded' "$log" | sed 's/^inkling2: / /' || true + rm -f "$log" + done +done From 9182d84830b3b7e6f6fdfa947bcfc65f5a4052ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Sacilotti?= Date: Mon, 23 Nov 2026 20:33:44 -0300 Subject: [PATCH 4/9] tools: compare two builds' log-probabilities, and score the Inkling 2 forward perplexity --kld-base writes llama-perplexity's file (the log-softmax quantized to 16 bits over 16 nats); comparing two builds of the engine with it turns 'the kernels did not change' into a byte comparison over every scored position and the whole vocabulary, and 'the sums moved a little' into a KLD, a top-1 agreement and the number of cells that moved one quantum. tools/kld_compare.py reads two files and prints those, with the PPL of each. perplexity loaded only the generic Model, which refuses the Inkling 2 architecture: it now runs that forward for those files (the model scores the first half of each chunk and steps the rest, exactly as the hint says), so the target of these PRs gets the same gate as the others. (cherry picked from commit 15940f0a8fa2709608f313b5475466829ab86f1d) --- src/main.rs | 34 +++++++++++---- tools/kld_compare.py | 98 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 124 insertions(+), 8 deletions(-) create mode 100644 tools/kld_compare.py diff --git a/src/main.rs b/src/main.rs index 64935fa1..75eafba6 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1232,16 +1232,25 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { } Cmd::Perplexity { model, file, ctx_len: n, chunks, kld_base, mut engine } => { let g = Gguf::open(&model)?; - let aux_g = open_mtp_gguf(engine.aux_model_path())?; - let m = Model::load_with_aux(&g, aux_g.as_ref(), &engine.lora_specs())?; let tok = Tokenizer::from_gguf(&g)?; // ponytail: no BOS at chunk starts (llama-perplexity adds one where the vocabulary asks for it; Qwen does not) let ids = tok.encode(&std::fs::read_to_string(&file)?)?; let n_chunk = (ids.len() / n).min(chunks.unwrap_or(usize::MAX)); anyhow::ensure!(n >= 4 && n_chunk > 0, "{} tokens: need at least one chunk of --ctx-len {n} (>= 4)", ids.len()); engine.ctx = engine.ctx.max(n); - let mut r = engine.runner(&m, &model)?; - let nv = m.cfg.n_vocab; + // Inkling 2 runs its own forward (`Model` does not load that architecture); it scores the same way, so + // `--kld-base` compares it with another build the same as it compares llama.cpp with the others. + let mut ink = if g.get("general.architecture").ok().and_then(|v| v.as_str()).is_some_and(rusting_strata::inkling2::is_arch) { + rusting_strata::inkling2::chat::gpu_defaults(); + engine.ds_env(); + Some(rusting_strata::inkling2::forward::Inkling2Model::new_with_ctx(&g, n)?) + } else { + None + }; + let aux_g = if ink.is_none() { open_mtp_gguf(engine.aux_model_path())? } else { None }; + let m = if ink.is_none() { Some(Model::load_with_aux(&g, aux_g.as_ref(), &engine.lora_specs())?) } else { None }; + let mut r = match &m { Some(m) => Some(engine.runner(m, &model)?), None => None }; + let nv = match (&ink, &m) { (Some(im), _) => im.cfg.n_vocab, (_, Some(m)) => m.cfg.n_vocab, _ => unreachable!() }; let mut out = kld_base.map(|p| std::fs::File::create(p).map(std::io::BufWriter::new)).transpose()?; if let Some(o) = &mut out { o.write_all(b"_logits_")?; @@ -1251,10 +1260,19 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { let (mut nll, mut count, mut row) = (0f64, 0usize, Vec::new()); let first = n / 2; for c in ids.chunks_exact(n).take(n_chunk) { - r.reset()?; - let mut logits = r.prefill(&c[..=first])?; + let mut logits = match (&mut ink, &mut r) { + (Some(im), _) => { im.reset(); im.prefill(&c[..=first]) } + (_, Some(run)) => { run.reset()?; run.prefill(&c[..=first])? } + _ => unreachable!(), + }; for i in first..n - 1 { - if i > first { logits = r.step(c[i])?; } + if i > first { + logits = match (&mut ink, &mut r) { + (Some(im), _) => im.step(c[i]), + (_, Some(run)) => run.step(c[i])?, + _ => unreachable!(), + }; + } anyhow::ensure!(logits.len() == nv, "{} logits, vocabulary {nv}", logits.len()); nll += log_probs(&logits, c[i + 1], &mut row); if let Some(o) = &mut out { for v in &row { o.write_all(&v.to_le_bytes())?; } } @@ -1264,7 +1282,7 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { } if let Some(o) = &mut out { o.flush()?; } println!("\nPPL = {:.4} over {n_chunk} chunks of {n} tokens ({count} scored)", (nll / count as f64).exp()); - r.finish()?; + if let Some(run) = &mut r { run.finish()?; } } Cmd::Bench { model, pp, tg, reps, json_out, prompt_file, mut engine } => { if let Some(f) = &prompt_file { diff --git a/tools/kld_compare.py b/tools/kld_compare.py new file mode 100644 index 00000000..6f49d45f --- /dev/null +++ b/tools/kld_compare.py @@ -0,0 +1,98 @@ +#!/usr/bin/env python3 +"""Compare two `perplexity --kld-base` files: KLD, top-token agreement, both PPLs, and how many cells moved. + + tools/kld_compare.py a.bin b.bin [--quiet] + +The file (written by `log_probs` in src/main.rs) is llama-perplexity's: `_logits_`, `n`, `n_vocab`, `n_chunks` +(u32 each), the `n_chunks * n` token ids (u32), then one row per scored position: the row's scale and offset (two +f32, as their u16 halves) and `n_vocab` u16 values, `logp(v) = offset + q(v) * scale` after dequantization. Two +builds of the engine that run the same kernels write byte-identical files; a kernel whose sums are reordered moves +the log-probabilities by a few ulp, below the u16 quantum (16 nats / 65535 = 2.4e-4), so most cells stay equal and +a few move by one step. + +Exit status: 0 when the files are byte-identical, 1 when they differ (the report says by how much). +""" + +import argparse +import struct +import sys + +import numpy as np + + +def header(f): + magic = f.read(8) + if magic != b"_logits_": + sys.exit(f"{f.name}: not a --kld-base file (starts with {magic[:8]!r})") + n, nv, nch = struct.unpack(" Date: Mon, 23 Nov 2026 12:40:19 -0300 Subject: [PATCH 5/9] cuda: the loop controllers tile 64 tokens per prompt block ink_ctrl_gate and ink_ctrl_out gave a block one (controller row, token) pair, so a 64-row controller weight was read once per token: at a prompt of 2048 tokens in 512-token chunks they took 466 ms of a 3.1 s prefill (the gate 0.65 GB/s of the card). The tiled pair puts 64 tokens and all 64 rows in a block (16 x 16 threads, 4 x 4 outputs each), reading a weight row once per 64 tokens. gate+out go from 4.86 to 1.03 ms per layer run: prefill 669 to 722 tok/s at 2048 tokens, 629 to 690 at 4096, 573 to 626 at 8192, same greedy text. A decoded token keeps the per-token pair (there is no tile to reuse) behind STRATA_CTRL_TILE=0. (cherry picked from commit 5f7920476059aea5ee86fe64b8cf4a22bfd337eb) --- src/cuda/kernels.cu | 122 ++++++++++++++++++++++++++++++++++++++++++++ src/cuda/mod.rs | 19 +++++-- 2 files changed, 137 insertions(+), 4 deletions(-) diff --git a/src/cuda/kernels.cu b/src/cuda/kernels.cu index 9afa0cca..a099324e 100644 --- a/src/cuda/kernels.cu +++ b/src/cuda/kernels.cu @@ -1821,6 +1821,128 @@ extern "C" __global__ void ink_ctrl_out(const u16* gain, const u16* forget, cons out[mo] = x - tanhf(f) * x + tanhf(g) * msg[mo]; } +// The same two controllers for a prompt chunk, tiled over tokens: a block holds 64 tokens of one controller and all +// `rank` rows (a 64 x 64 output tile), so a weight row is read once per 64 tokens where the per-token kernels above +// read it once per token (32x the traffic of the tile, and a block reduction per output). 16 x 16 threads, 4 x 4 +// outputs each; both read and write the layout of the per-token pair, so nothing outside these four kernels changes. +extern "C" __global__ void __launch_bounds__(256) ink_ctrl_gate_b(const u16* down, const float* cur, int nins, + const float* msg, float* gate, int n, int rank, int nt) { + constexpr int BT = 64; + __shared__ __align__(16) float xs[BT][65]; + __shared__ __align__(16) u16 ws[BT][65]; + __shared__ float sc[BT][2]; + const int j = blockIdx.x, t0 = blockIdx.y * BT, tw = 2 * n, count = gridDim.x; + const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5; + const float* ccur = cur + (size_t)min(j, nins - 1) * nt * n; + const float* cmsg = msg + (size_t)j * nt * n; + // The RMS of both inputs of each token, one warp a token: the per-token kernel folds this into its one dot. + for (int tt = warp; tt < BT; tt += 8) { + const int t = t0 + tt; + float sa = 0.f, sb = 0.f; + if (t < nt) { + const float* c = ccur + (size_t)t * n; + const float* m = cmsg + (size_t)t * n; + for (int i = lane; i < n; i += 32) { sa += c[i] * c[i]; sb += m[i] * m[i]; } + } + sa = warp_sum(sa); sb = warp_sum(sb); + if (lane == 0) { sc[tt][0] = rsqrtf(sa / (float)n + 1e-6f); sc[tt][1] = rsqrtf(sb / (float)n + 1e-6f); } + } + __syncthreads(); + const int ty = tid >> 4, tx = tid & 15; + float acc[4][4]; + for (int i = 0; i < 4; i++) for (int r = 0; r < 4; r++) acc[i][r] = 0.f; + for (int k0 = 0; k0 < tw; k0 += 64) { + for (int i = tid; i < BT * 64; i += 256) { + const int tt = i >> 6, kk = i & 63, t = t0 + tt, k = k0 + kk; + float v = 0.f; + if (t < nt) { + const float* c = ccur + (size_t)t * n; + const float* m = cmsg + (size_t)t * n; + v = k < n ? c[k] * sc[tt][0] : m[k - n] * sc[tt][1]; + } + xs[tt][kk] = v; + } + for (int i = tid; i < 64 * 64; i += 256) { + const int r = i >> 6, kk = i & 63; + ws[r][kk] = r < rank && k0 + kk < tw ? down[((size_t)j * rank + r) * tw + k0 + kk] : (u16)0; + } + __syncthreads(); + for (int k = 0; k < 64; k++) { + float xv[4], wv[4]; +#pragma unroll + for (int i = 0; i < 4; i++) xv[i] = xs[ty * 4 + i][k]; +#pragma unroll + for (int r = 0; r < 4; r++) wv[r] = h2f(ws[tx * 4 + r][k]); +#pragma unroll + for (int i = 0; i < 4; i++) { +#pragma unroll + for (int r = 0; r < 4; r++) acc[i][r] = fmaf(xv[i], wv[r], acc[i][r]); + } + } + __syncthreads(); + } +#pragma unroll + for (int i = 0; i < 4; i++) { + const int t = t0 + ty * 4 + i; + if (t >= nt) break; +#pragma unroll + for (int r = 0; r < 4; r++) { + if (tx * 4 + r < rank) gate[((size_t)t * count + j) * rank + tx * 4 + r] = acc[i][r]; + } + } +} + +extern "C" __global__ void __launch_bounds__(256) ink_ctrl_out_b(const u16* gain, const u16* forget, const float* gate, + const float* cur, int nins, const float* msg, float* out, + int n, int rank, int nt) { + constexpr int BT = 64; + __shared__ __align__(16) float gs[BT][65]; + __shared__ __align__(16) u16 ws[2][BT][65]; + const int j = blockIdx.x, c0 = blockIdx.y * BT, t0 = blockIdx.z * BT, count = gridDim.x; + const int tid = threadIdx.x; + for (int i = tid; i < BT * 64; i += 256) { + const int tt = i >> 6, r = i & 63, t = t0 + tt; + gs[tt][r] = t < nt && r < rank ? gate[((size_t)t * count + j) * rank + r] : 0.f; + } + for (int i = tid; i < BT * 64; i += 256) { + const int r = i >> 6, cc = i & 63, c = c0 + cc; + const bool in = r < rank && c < n; + const size_t at = ((size_t)j * rank + r) * n + c; + ws[0][r][cc] = in ? gain[at] : (u16)0; + ws[1][r][cc] = in ? forget[at] : (u16)0; + } + __syncthreads(); + const int ty = tid >> 4, tx = tid & 15; + float ag[4][4], af[4][4]; + for (int i = 0; i < 4; i++) for (int cc = 0; cc < 4; cc++) { ag[i][cc] = 0.f; af[i][cc] = 0.f; } + for (int r = 0; r < rank; r++) { + float gv[4], wg[4], wf[4]; +#pragma unroll + for (int i = 0; i < 4; i++) gv[i] = gs[ty * 4 + i][r]; +#pragma unroll + for (int cc = 0; cc < 4; cc++) { wg[cc] = h2f(ws[0][r][tx * 4 + cc]); wf[cc] = h2f(ws[1][r][tx * 4 + cc]); } +#pragma unroll + for (int i = 0; i < 4; i++) { +#pragma unroll + for (int cc = 0; cc < 4; cc++) { ag[i][cc] = fmaf(gv[i], wg[cc], ag[i][cc]); af[i][cc] = fmaf(gv[i], wf[cc], af[i][cc]); } + } + } + for (int i = 0; i < 4; i++) { + const int t = t0 + ty * 4 + i; + if (t >= nt) break; + const int c = c0 + tx * 4; + if (c >= n) continue; + float* o = out + ((size_t)j * nt + t) * n + c; + const float* x = cur + ((size_t)min(j, nins - 1) * nt + t) * n + c; + const float* m = msg + ((size_t)j * nt + t) * n + c; + const int cnt = min(4, n - c); + for (int cc = 0; cc < cnt; cc++) { + const float f = fminf(fmaxf(af[i][cc], -10.f), 10.f), g = fminf(fmaxf(ag[i][cc], -10.f), 10.f); + o[cc] = x[cc] - tanhf(f) * x[cc] + tanhf(g) * m[cc]; + } + } +} + // Short causal convolution with a residual (nc at most 8; out may be cur): hist holds the last nc - 1 inputs, the // oldest first, and is advanced by cur. taps ([c / per][lag], lag 0 the current input) may be null. extern "C" __global__ void ink_conv(const float* cur, const float* w, const float* taps, float* hist, float* out, int n, int nc, int per) { diff --git a/src/cuda/mod.rs b/src/cuda/mod.rs index f07f182c..672e8f32 100644 --- a/src/cuda/mod.rs +++ b/src/cuda/mod.rs @@ -17,12 +17,12 @@ const QTYPES: [GgmlType; 29] = { use GgmlType::*; [F32, BF16, F8E4M3, Q8_0, Q2K, Q3K, Q4K, Q5K, Q6K, IQ1S, IQ1M, IQ2XXS, IQ2XS, IQ2S, IQ3XXS, IQ3S, IQ4XS, IQ4NL, Q2_0, TQ1_0, TQ2_0, TQ2T, TQK6, TQK7, Q4_1, Q5_1, Q4_0, Q5_0, NVFP4] }; -const KERNELS: [&str; 54] = [ +const KERNELS: [&str; 56] = [ "rope_freq", "qsa_pool", "qsa_score", "qsa_select", "rms_norm", "quant_xq", "argmax_part", "argmax_rows", "l2_norm", "rope_neox", "rms_norm_rope", "add", "swiglu", "situ", "situ_q", "softcap", "swiglu_q", "ssm_gates", "conv_silu", "deltanet_seq", "norm_gate", "kv_store", "attn_merge", "router_topk", "moe_combine", "moe_route", "conv_seq", "conv_state", "moe_combine_seq", "moe_prefetch", "attn_prefill_64", "attn_prefill_128", "attn_prefill_256", "quant_q8", "hc_silu", "hc_mix", "hc_write", "ple_gate", "ple_conv", "dflash2_conv", "hadamard", - "ink_mix", "ink_ctrl_gate", "ink_ctrl_out", "ink_conv", "ink_conv_batch", "ink_clip", "ink_attn", "ink_attn_merge", + "ink_mix", "ink_ctrl_gate", "ink_ctrl_out", "ink_ctrl_gate_b", "ink_ctrl_out_b", "ink_conv", "ink_conv_batch", "ink_clip", "ink_attn", "ink_attn_merge", "ink_attn_prefill_32", "ink_attn_prefill_64", "ink_attn_prefill_128", "ink_ffn_sum", "ink_route", ]; @@ -1082,6 +1082,17 @@ impl Backend for Gpu { Ok(()) } fn ink_ctrl_n(&self, down: u64, gain: u64, forget: u64, cur: u64, nins: usize, msg: u64, gate: u64, out: u64, n: usize, rank: usize, count: usize, nt: usize) -> anyhow::Result<()> { + // A prompt chunk uses the tiled pair (a weight row is read once per 64 tokens); a decoded token the + // per-token pair, which has no tile to reuse. Both pairs read and write the same gate layout. + // STRATA_CTRL_TILE=0 forces the per-token pair, to compare the two on the same text. + let tiled = nt >= 64 && rank <= 64 && n % 64 == 0 && std::env::var("STRATA_CTRL_TILE").map_or(true, |v| v != "0"); + if tiled { + let g1 = cfg((count as u32, nt.div_ceil(64) as u32), 256, 0); + let g2 = LaunchConfig { grid_dim: (count as u32, n.div_ceil(64) as u32, nt.div_ceil(64) as u32), block_dim: (256, 1, 1), shared_mem_bytes: 0 }; + launch!(self, "ink_ctrl_gate_b", g1, down, cur, nins as i32, msg, gate, n as i32, rank as i32, nt as i32); + launch!(self, "ink_ctrl_out_b", g2, gain, forget, gate, cur, nins as i32, msg, out, n as i32, rank as i32, nt as i32); + return Ok(()); + } let g1 = LaunchConfig { grid_dim: (rank as u32, count as u32, nt as u32), block_dim: (256, 1, 1), shared_mem_bytes: 0 }; let g2 = LaunchConfig { grid_dim: (n.div_ceil(256) as u32, count as u32, nt as u32), block_dim: (256, 1, 1), shared_mem_bytes: 0 }; launch!(self, "ink_ctrl_gate", g1, down, cur, nins as i32, msg, gate, n as i32, rank as i32, nt as i32); @@ -1502,8 +1513,8 @@ mod tests { #[test] fn kernel_names() { let (sm70, sm80) = (super::kernel_names(false), super::kernel_names(true)); - assert_eq!(sm80.len(), 370); - assert_eq!(sm70.len(), 324); + assert_eq!(sm80.len(), 372); + assert_eq!(sm70.len(), 326); assert!(sm70.iter().all(|n| !n.starts_with("gemmi") && !n.starts_with("gemmis")), "sm_70 must not load the int8 prefill GEMM: {:?}", sm70.iter().filter(|n| n.starts_with("gemmi")).collect::>()); From 90514c7462dd4aa87afaf4bf70d8f1eb0233036a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Sacilotti?= Date: Mon, 23 Nov 2026 20:45:59 -0300 Subject: [PATCH 6/9] cuda: decode attention reads K/V at the card's bandwidth The scalar kernel walks one key at a time: every lane loads a 2-byte K element through ldkv1 and the 128-long dot ends in a warp reduction, so one key costs a row of scalar loads and five shuffles. At 24.5k positions that read K/V at about 95 GB/s of the 360 the card has, and it was 8.4 of the 27 ms a token took there (68 ms at 200k). ink_attn_128 has a 128-thread block own 128 positions: their K rows are staged in shared memory with coalesced 16-byte loads, lane i of warp w scores key 32w + i with sixteen 16-byte loads and 128 FMAs (one block max and one block sum per 128 keys, no shuffle per key), and V is read 8 bytes a lane, one key at a time, as it already was coalesced. Measured with the two-card work (a separate branch: this file loads the device only with one card today) decode after a 24.5k-token prompt went 37.0 to 45.5 tok/s; tests/inkling2_forward still matches llama.cpp's greedy tokens on one card (24/24 short, 47/48 long, the same near tie), and STRATA_DS_ATTN_OLD=1 keeps the scalar kernel. (cherry picked from commit a7d37ddc27b4b6c2dd733e154ecb0dd5bcfa425b) --- src/cuda/kernels.cu | 71 +++++++++++++++++++++++++++++++++++++++++++++ src/cuda/mod.rs | 26 ++++++++++++----- 2 files changed, 89 insertions(+), 8 deletions(-) diff --git a/src/cuda/kernels.cu b/src/cuda/kernels.cu index a099324e..343312e9 100644 --- a/src/cuda/kernels.cu +++ b/src/cuda/kernels.cu @@ -7,6 +7,7 @@ typedef unsigned int u32; typedef unsigned long long u64; __device__ __forceinline__ float h2f(u16 h) { float f; asm("cvt.f32.f16 %0, %1;" : "=f"(f) : "h"(h)); return f; } +__device__ __forceinline__ float2 ink_h2f2(unsigned w) { return make_float2(h2f((u16)(w & 0xFFFFu)), h2f((u16)(w >> 16))); } __device__ __forceinline__ u16 f2h(float f) { u16 h; asm("cvt.rn.f16.f32 %0, %1;" : "=h"(h) : "f"(f)); return h; } __device__ __forceinline__ u32 ld16(const u8* p) { return *(const u16*)p; } // 2-aligned only (every quant field is) __device__ __forceinline__ u32 ld32(const u8* p) { return p[0] | (p[1] << 8) | (p[2] << 16) | ((u32)p[3] << 24); } @@ -2680,6 +2681,76 @@ extern "C" __global__ void ink_attn(const float* q, const float* r, const float* } } +#if KV_MODE == 0 +// Decode attention for head_dim 128, one query per head, restructured for bandwidth. A 128-thread block owns 128 key +// positions and stages their K rows in shared memory with coalesced 16-byte loads; lane i of warp w scores key +// 32w + i with sixteen 16-byte loads and 128 FMAs, so there is no shuffle per key (one block max and one block sum +// per 128 keys), and V is read 8 bytes a lane, one key at a time, which is coalesced as it is. The kernel above walks +// one key at a time through ldkv1 (a 2-byte load per lane per element) and reads K/V at about 95 GB/s of the card's +// 360: 8.4 ms a token at 24.5k positions, and most of the 21 ms it takes at 200k. +extern "C" __global__ void __launch_bounds__(128) ink_attn_128(const float* q, const float* r, const float* sink, + const u16* k, const u16* v, const float* bias, float* sc, int rows, int at, int ring, int nkv, int hd, + int nr, int ext, const int* pos_ptr) { + constexpr int HD = 128, PQ = HD + 8; + __shared__ __align__(16) float qs[HD], rs[32], lg[128], ac[4][HD]; + __shared__ __align__(16) u16 ks[128 * PQ]; + int h = blockIdx.x, kh = h / (gridDim.x / nkv), kw = nkv * HD; + int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5; + if (pos_ptr) { int pos = *pos_ptr; rows = min(pos + 1, ring); at = pos % ring; } + int i0 = blockIdx.y * 128, n = i0 < rows ? min(128, rows - i0) : 0; + float* o = sc + ((size_t)h * gridDim.y + blockIdx.y) * (HD + 2); + if (n == 0) { // a chunk past the keys: a neutral partial for the merge (exp(-3e38) is 0) + if (tid < HD) o[2 + tid] = 0.f; + if (tid == 0) { o[0] = -3.0e38f; o[1] = 0.f; } + return; + } + if (tid < HD) qs[tid] = q[h * HD + tid] * rsqrtf((float)HD); + if (tid < nr) rs[tid] = r[h * nr + tid]; + for (int i = tid; i < 128 * 16; i += 128) { + int row = i >> 4, part = i & 15; + uint4 x = make_uint4(0u, 0u, 0u, 0u); + if (row < n) x = *(const uint4*)(k + (size_t)(i0 + row) * kw + kh * HD + part * 8); + *(uint4*)(ks + row * PQ + part * 8) = x; + } + __syncthreads(); + int i = i0 + warp * 32 + lane; + float l = -3.0e38f; + if (i < i0 + n) { + const u16* kr = ks + (warp * 32 + lane) * PQ; + float d = 0.f; + for (int m = 0; m < HD / 8; m++) { + uint4 w = *(const uint4*)(kr + 8 * m); + float2 a = ink_h2f2(w.x), b = ink_h2f2(w.y), c = ink_h2f2(w.z), e = ink_h2f2(w.w); + d += qs[8 * m + 0] * a.x + qs[8 * m + 1] * a.y + qs[8 * m + 2] * b.x + qs[8 * m + 3] * b.y + + qs[8 * m + 4] * c.x + qs[8 * m + 5] * c.y + qs[8 * m + 6] * e.x + qs[8 * m + 7] * e.y; + } + int dist = at - i; if (dist < 0) dist += rows; + if (dist < ext) for (int c = 0; c < nr; c++) d += rs[c] * bias[(size_t)dist * nr + c]; + l = d - sink[h]; + } + float mx = block_max(l); + float p = i < i0 + n ? expf(l - mx) : 0.f; + lg[tid] = p; + float z = block_sum(p); + __syncthreads(); + float a0 = 0.f, a1 = 0.f, a2 = 0.f, a3 = 0.f; + for (int j = warp; j < n; j += 4) { + float pj = lg[j]; + uint2 vw = *(const uint2*)(v + (size_t)(i0 + j) * kw + kh * HD + 4 * lane); + float2 v01 = ink_h2f2(vw.x), v23 = ink_h2f2(vw.y); + a0 += pj * v01.x; a1 += pj * v01.y; a2 += pj * v23.x; a3 += pj * v23.y; + } + *(float4*)&ac[warp][4 * lane] = make_float4(a0, a1, a2, a3); + __syncthreads(); + if (tid < HD) o[2 + tid] = ac[0][tid] + ac[1][tid] + ac[2][tid] + ac[3][tid]; + if (tid == 0) { o[0] = mx; o[1] = z; } +} +#else +// A quantized KV cache keeps the scalar kernel: this entry point is never selected (see ink_attn in cuda/mod.rs). +extern "C" __global__ void __launch_bounds__(128) ink_attn_128(const float*, const float*, const float*, const u16*, + const u16*, const float*, float*, int, int, int, int, int, int, int, const int*) { __trap(); } +#endif + extern "C" __global__ void ink_attn_merge(const float* sc, const float* gate, float* out, int chunks, int hd) { int h = blockIdx.x, t = threadIdx.x; const float* p = sc + (size_t)h * chunks * (hd + 2); diff --git a/src/cuda/mod.rs b/src/cuda/mod.rs index 672e8f32..42b95910 100644 --- a/src/cuda/mod.rs +++ b/src/cuda/mod.rs @@ -17,12 +17,12 @@ const QTYPES: [GgmlType; 29] = { use GgmlType::*; [F32, BF16, F8E4M3, Q8_0, Q2K, Q3K, Q4K, Q5K, Q6K, IQ1S, IQ1M, IQ2XXS, IQ2XS, IQ2S, IQ3XXS, IQ3S, IQ4XS, IQ4NL, Q2_0, TQ1_0, TQ2_0, TQ2T, TQK6, TQK7, Q4_1, Q5_1, Q4_0, Q5_0, NVFP4] }; -const KERNELS: [&str; 56] = [ +const KERNELS: [&str; 57] = [ "rope_freq", "qsa_pool", "qsa_score", "qsa_select", "rms_norm", "quant_xq", "argmax_part", "argmax_rows", "l2_norm", "rope_neox", "rms_norm_rope", "add", "swiglu", "situ", "situ_q", "softcap", "swiglu_q", "ssm_gates", "conv_silu", "deltanet_seq", "norm_gate", "kv_store", "attn_merge", "router_topk", "moe_combine", "moe_route", "conv_seq", "conv_state", "moe_combine_seq", "moe_prefetch", "attn_prefill_64", "attn_prefill_128", "attn_prefill_256", "quant_q8", "hc_silu", "hc_mix", "hc_write", "ple_gate", "ple_conv", "dflash2_conv", "hadamard", - "ink_mix", "ink_ctrl_gate", "ink_ctrl_out", "ink_ctrl_gate_b", "ink_ctrl_out_b", "ink_conv", "ink_conv_batch", "ink_clip", "ink_attn", "ink_attn_merge", + "ink_mix", "ink_ctrl_gate", "ink_ctrl_out", "ink_ctrl_gate_b", "ink_ctrl_out_b", "ink_conv", "ink_conv_batch", "ink_clip", "ink_attn", "ink_attn_128", "ink_attn_merge", "ink_attn_prefill_32", "ink_attn_prefill_64", "ink_attn_prefill_128", "ink_ffn_sum", "ink_route", ]; @@ -758,6 +758,14 @@ impl Gpu { } } +impl Gpu { + /// The decode attention entry point and its key positions per block: the f16 head_dim 128 kernel scores a + /// 128-key tile a block, the scalar one 64 keys (`STRATA_DS_ATTN_OLD=1` keeps it for a measurement window). + pub(crate) fn ink_attn_kernel(&self, hd: usize) -> (&'static str, usize) { + if hd == 128 && self.kv_mode == 0 && std::env::var_os("STRATA_DS_ATTN_OLD").is_none() { ("ink_attn_128", 128) } else { ("ink_attn", 64) } + } +} + impl Backend for Gpu { fn name(&self) -> &'static str { "cuda" } fn device(&self) -> String { self.ctx.name().unwrap_or_default() } @@ -1139,14 +1147,16 @@ impl Backend for Gpu { Ok(()) } fn ink_attn(&self, q: u64, r: u64, sink: u64, gate: u64, k: u64, v: u64, bias: u64, sc: u64, out: u64, rows: usize, at: usize, nh: usize, nkv: usize, hd: usize, nr: usize, ext: usize) -> anyhow::Result<()> { - let chunks = rows.div_ceil(64) as u32; - launch!(self, "ink_attn", cfg((nh as u32, chunks), 128, 0), q, r, sink, k, v, bias, sc, rows as i32, at as i32, 1i32, nkv as i32, hd as i32, nr as i32, ext as i32, 0u64); + let (kn, ck) = self.ink_attn_kernel(hd); + let chunks = rows.div_ceil(ck) as u32; + launch!(self, kn, cfg((nh as u32, chunks), 128, 0), q, r, sink, k, v, bias, sc, rows as i32, at as i32, 1i32, nkv as i32, hd as i32, nr as i32, ext as i32, 0u64); launch!(self, "ink_attn_merge", cfg((nh as u32, 1), 128, 0), sc, gate, out, chunks as i32, hd as i32); Ok(()) } fn ink_attn_pos(&self, q: u64, r: u64, sink: u64, gate: u64, k: u64, v: u64, bias: u64, sc: u64, out: u64, max_rows: usize, ring: usize, pos_ptr: u64, nh: usize, nkv: usize, hd: usize, nr: usize, ext: usize) -> anyhow::Result<()> { - let chunks = max_rows.div_ceil(64) as u32; - launch!(self, "ink_attn", cfg((nh as u32, chunks), 128, 0), q, r, sink, k, v, bias, sc, 0i32, 0i32, ring.max(1) as i32, nkv as i32, hd as i32, nr as i32, ext as i32, pos_ptr); + let (kn, ck) = self.ink_attn_kernel(hd); + let chunks = max_rows.div_ceil(ck) as u32; + launch!(self, kn, cfg((nh as u32, chunks), 128, 0), q, r, sink, k, v, bias, sc, 0i32, 0i32, ring.max(1) as i32, nkv as i32, hd as i32, nr as i32, ext as i32, pos_ptr); launch!(self, "ink_attn_merge", cfg((nh as u32, 1), 128, 0), sc, gate, out, chunks as i32, hd as i32); Ok(()) } @@ -1513,8 +1523,8 @@ mod tests { #[test] fn kernel_names() { let (sm70, sm80) = (super::kernel_names(false), super::kernel_names(true)); - assert_eq!(sm80.len(), 372); - assert_eq!(sm70.len(), 326); + assert_eq!(sm80.len(), 373); + assert_eq!(sm70.len(), 327); assert!(sm70.iter().all(|n| !n.starts_with("gemmi") && !n.starts_with("gemmis")), "sm_70 must not load the int8 prefill GEMM: {:?}", sm70.iter().filter(|n| n.starts_with("gemmi")).collect::>()); From 0bc2c576a38c451f4d2384df78a841308a0e36f2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Sacilotti?= Date: Mon, 23 Nov 2026 11:34:14 -0300 Subject: [PATCH 7/9] cuda: key-parallel ink_attn_prefill_128 One warp ran one (query, head) and walked the keys one at a time: two warp reductions and a dozen shuffles per key. The new kernel gives a 128-thread block four queries of one head, shares a 32-key K/V tile in shared memory, scores one key per lane (its own 128-long dot) and reduces once per tile for the online softmax. Needs nr <= 32 and nr % 4 == 0; the old kernel stays as ink_attn_prefill_128_old behind STRATA_DS_ATTN_OLD. (cherry picked from commit eb66a544dd32be49d5353f0e7ed1cfcefbdcd6d5) --- src/cuda/kernels.cu | 137 ++++++++++++++++++++++++++++++++++++++++++++ src/cuda/mod.rs | 10 ++-- 2 files changed, 142 insertions(+), 5 deletions(-) diff --git a/src/cuda/kernels.cu b/src/cuda/kernels.cu index 343312e9..ee4d17ff 100644 --- a/src/cuda/kernels.cu +++ b/src/cuda/kernels.cu @@ -2827,6 +2827,143 @@ __device__ void ink_attn_prefill_t(const float* q, const float* r, const float* ink_attn_prefill_t(q, r, sink, gate, kc, vc, kc_new, vc_new, bias, outp, pos, nt, nh, nkv, nr, ext, ring, win); \ } DEF_INK_PREFILL(32) DEF_INK_PREFILL(64) DEF_INK_PREFILL(128) +#if KV_MODE == 0 +// Local patch: key-parallel version of `ink_attn_prefill_t` for hd = 128 and an f16 cache. The old kernel gave a warp one +// (query, head) and walked the keys one at a time: two warp reductions and a dozen shuffles per key. Here the block's four +// warps (four queries, one head) share a 32-key K/V tile in shared memory, lane i scores key i of the tile (the 128-long +// dot product is its own, no shuffles), and a warp reduces once per tile for the online softmax. Same math, summed in +// another order. Needs nr <= 32 and nr % 4 == 0 (the relative-bias rows are read as float4). +__device__ __forceinline__ float2 ink_h2f2(unsigned w) { return make_float2(h2f((u16)(w & 0xFFFFu)), h2f((u16)(w >> 16))); } +__device__ __forceinline__ float ink_warp_max(float v) { + for (int o = 16; o; o >>= 1) v = fmaxf(v, __shfl_xor_sync(0xffffffff, v, o)); + return v; +} +__device__ void ink_attn_prefill_kp(const float* q, const float* r, const float* sink, const float* gate, + const u16* kc, const u16* vc, const u16* kc_new, const u16* vc_new, + const float* bias, float* outp, + int pos, int nt, int nh, int nkv, int nr, int ext, int ring, int win) { + constexpr int HD = 128, PQ = HD + 8; + __shared__ __align__(16) u16 ks[32 * PQ]; + __shared__ __align__(16) u16 vs[32 * PQ]; + __shared__ __align__(16) float qs[4][HD]; + __shared__ __align__(16) float rs[4][32]; + __shared__ float ps[4][32]; + const int tid = threadIdx.x, warp = tid >> 5, lane = tid & 31, h = blockIdx.y; + const int t0 = blockIdx.x * 4, t = t0 + warp; + const bool act = t < nt; + const int kh = h / (nh / nkv), kw = nkv * HD; + const int q_pos = pos + t; + const int start = (win > 0 && q_pos + 1 > win) ? (q_pos + 1 - win) : 0; + float sink_val = 0.f; + if (act) { + const float scale = 1.f / sqrtf((float)HD); + for (int d = lane; d < HD; d += 32) qs[warp][d] = q[((size_t)t * nh + h) * HD + d] * scale; + rs[warp][lane] = lane < nr ? r[((size_t)t * nh + h) * nr + lane] : 0.f; + sink_val = sink[(size_t)t * nh + h]; + } + const int kmax = pos + min(t0 + 3, nt - 1); + const int pq0 = pos + t0; + const int kmin = (win > 0 && pq0 + 1 > win) ? (pq0 + 1 - win) : 0; + float m = 0.f, l = 1.f, acc[4] = {0.f, 0.f, 0.f, 0.f}; + for (int k0 = kmin; k0 <= kmax; k0 += 32) { + __syncthreads(); +#pragma unroll + for (int n = 0; n < 4; n++) { + int i = tid + n * 128, rr = i >> 4, c = (i & 15) * 8, kp = k0 + rr; + uint4 kv = make_uint4(0, 0, 0, 0), vv = kv; + if (kp <= kmax) { + bool un = kc_new && kp >= pos; + size_t row = un ? (size_t)(kp - pos) : (win > 0 ? (size_t)(kp % ring) : (size_t)kp); + size_t off = row * kw + (size_t)kh * HD + c; + kv = *(const uint4*)((un ? kc_new : kc) + off); + vv = *(const uint4*)((un ? vc_new : vc) + off); + } + *(uint4*)(ks + rr * PQ + c) = kv; + *(uint4*)(vs + rr * PQ + c) = vv; + } + __syncthreads(); + if (!act) continue; + const int kp = k0 + lane; + const bool valid = kp >= start && kp <= q_pos; + float sd = 0.f; + const u16* kr = ks + lane * PQ; +#pragma unroll + for (int mm = 0; mm < 16; mm++) { + uint4 w = *(const uint4*)(kr + 8 * mm); + float4 qa = *(const float4*)(&qs[warp][8 * mm]); + float4 qb = *(const float4*)(&qs[warp][8 * mm + 4]); + float2 f0 = ink_h2f2(w.x), f1 = ink_h2f2(w.y); + float2 f2 = ink_h2f2(w.z), f3 = ink_h2f2(w.w); + sd += qa.x * f0.x + qa.y * f0.y + qa.z * f1.x + qa.w * f1.y + qb.x * f2.x + qb.y * f2.y + qb.z * f3.x + qb.w * f3.y; + } + float b = 0.f; + const int dist = q_pos - kp; + if (valid && dist < ext) { + const float4* br = (const float4*)(bias + (size_t)dist * nr); + for (int c = 0; c < nr; c += 4) { + float4 bv = br[c >> 2]; + b += rs[warp][c] * bv.x + rs[warp][c + 1] * bv.y + rs[warp][c + 2] * bv.z + rs[warp][c + 3] * bv.w; + } + } + const float logit = valid ? sd + b - sink_val : -INFINITY; + const float mn = fmaxf(m, ink_warp_max(logit)); + const float cc = expf(m - mn); + const float p = valid ? expf(logit - mn) : 0.f; + l = l * cc + warp_sum(p); + m = mn; + acc[0] *= cc; acc[1] *= cc; acc[2] *= cc; acc[3] *= cc; + ps[warp][lane] = p; + __syncwarp(); + const int nk = min(32, q_pos - k0 + 1); + for (int i = 0; i < nk; i++) { + float pi = ps[warp][i]; + uint2 vw = *(const uint2*)(vs + i * PQ + 4 * lane); + float2 v01 = ink_h2f2(vw.x), v23 = ink_h2f2(vw.y); + acc[0] += pi * v01.x; acc[1] += pi * v01.y; acc[2] += pi * v23.x; acc[3] += pi * v23.y; + } + __syncwarp(); + } + if (act) { + const float inv = 1.f / l; +#pragma unroll + for (int j = 0; j < 4; j++) { + size_t idx = ((size_t)t * nh + h) * HD + 4 * lane + j; + outp[idx] = acc[j] * inv * sigmoid(gate[idx]); + } + } +} +// The old kernel stays reachable as ink_attn_prefill_128_old (STRATA_DS_ATTN_OLD=1) and takes the shapes the new one does not. +extern "C" __global__ void __launch_bounds__(128) ink_attn_prefill_128_old( + const float* q, const float* r, const float* sink, const float* gate, + const u16* kc, const u16* vc, const u16* kc_new, const u16* vc_new, + const float* bias, float* outp, + int pos, int nt, int nh, int nkv, int nr, int ext, int ring, int win) { + ink_attn_prefill_t<4>(q, r, sink, gate, kc, vc, kc_new, vc_new, bias, outp, pos, nt, nh, nkv, nr, ext, ring, win); +} +extern "C" __global__ void __launch_bounds__(128) ink_attn_prefill_128_kp( + const float* q, const float* r, const float* sink, const float* gate, + const u16* kc, const u16* vc, const u16* kc_new, const u16* vc_new, + const float* bias, float* outp, + int pos, int nt, int nh, int nkv, int nr, int ext, int ring, int win) { + if (nr <= 32 && (nr & 3) == 0) ink_attn_prefill_kp(q, r, sink, gate, kc, vc, kc_new, vc_new, bias, outp, pos, nt, nh, nkv, nr, ext, ring, win); + else ink_attn_prefill_t<4>(q, r, sink, gate, kc, vc, kc_new, vc_new, bias, outp, pos, nt, nh, nkv, nr, ext, ring, win); +} +#else +extern "C" __global__ void __launch_bounds__(128) ink_attn_prefill_128_old( + const float* q, const float* r, const float* sink, const float* gate, + const u16* kc, const u16* vc, const u16* kc_new, const u16* vc_new, + const float* bias, float* outp, + int pos, int nt, int nh, int nkv, int nr, int ext, int ring, int win) { + ink_attn_prefill_t<4>(q, r, sink, gate, kc, vc, kc_new, vc_new, bias, outp, pos, nt, nh, nkv, nr, ext, ring, win); +} +extern "C" __global__ void __launch_bounds__(128) ink_attn_prefill_128_kp( + const float* q, const float* r, const float* sink, const float* gate, + const u16* kc, const u16* vc, const u16* kc_new, const u16* vc_new, + const float* bias, float* outp, + int pos, int nt, int nh, int nkv, int nr, int ext, int ring, int win) { + ink_attn_prefill_t<4>(q, r, sink, gate, kc, vc, kc_new, vc_new, bias, outp, pos, nt, nh, nkv, nr, ext, ring, win); +} +#endif template __device__ void attn_decode_llama(const float* q, const u16* kc, const u16* vc, float* part, const int* step, const int* sel, int nh, int nkv, float scale, int bx, int win) { diff --git a/src/cuda/mod.rs b/src/cuda/mod.rs index 42b95910..8841f6fd 100644 --- a/src/cuda/mod.rs +++ b/src/cuda/mod.rs @@ -17,13 +17,13 @@ const QTYPES: [GgmlType; 29] = { use GgmlType::*; [F32, BF16, F8E4M3, Q8_0, Q2K, Q3K, Q4K, Q5K, Q6K, IQ1S, IQ1M, IQ2XXS, IQ2XS, IQ2S, IQ3XXS, IQ3S, IQ4XS, IQ4NL, Q2_0, TQ1_0, TQ2_0, TQ2T, TQK6, TQK7, Q4_1, Q5_1, Q4_0, Q5_0, NVFP4] }; -const KERNELS: [&str; 57] = [ +const KERNELS: [&str; 59] = [ "rope_freq", "qsa_pool", "qsa_score", "qsa_select", "rms_norm", "quant_xq", "argmax_part", "argmax_rows", "l2_norm", "rope_neox", "rms_norm_rope", "add", "swiglu", "situ", "situ_q", "softcap", "swiglu_q", "ssm_gates", "conv_silu", "deltanet_seq", "norm_gate", "kv_store", "attn_merge", "router_topk", "moe_combine", "moe_route", "conv_seq", "conv_state", "moe_combine_seq", "moe_prefetch", "attn_prefill_64", "attn_prefill_128", "attn_prefill_256", "quant_q8", "hc_silu", "hc_mix", "hc_write", "ple_gate", "ple_conv", "dflash2_conv", "hadamard", "ink_mix", "ink_ctrl_gate", "ink_ctrl_out", "ink_ctrl_gate_b", "ink_ctrl_out_b", "ink_conv", "ink_conv_batch", "ink_clip", "ink_attn", "ink_attn_128", "ink_attn_merge", - "ink_attn_prefill_32", "ink_attn_prefill_64", "ink_attn_prefill_128", "ink_ffn_sum", "ink_route", + "ink_attn_prefill_32", "ink_attn_prefill_64", "ink_attn_prefill_128", "ink_attn_prefill_128_old", "ink_attn_prefill_128_kp", "ink_ffn_sum", "ink_route", ]; pub use crate::backend::{ATT_GQA_MIN, ATT_SPLITS, GEMM_BM, GpuTensor}; @@ -1167,7 +1167,7 @@ impl Backend for Gpu { let kn = match hd { 32 => "ink_attn_prefill_32", 64 => "ink_attn_prefill_64", - 128 => "ink_attn_prefill_128", + 128 => if std::env::var_os("STRATA_DS_ATTN_OLD").is_some() { "ink_attn_prefill_128_old" } else { "ink_attn_prefill_128_kp" }, _ => anyhow::bail!("ink_attn_prefill: unsupported hd={hd}"), }; launch!(self, kn, cfg((nt.div_ceil(4) as u32, nh as u32), 128, 0), @@ -1523,8 +1523,8 @@ mod tests { #[test] fn kernel_names() { let (sm70, sm80) = (super::kernel_names(false), super::kernel_names(true)); - assert_eq!(sm80.len(), 373); - assert_eq!(sm70.len(), 327); + assert_eq!(sm80.len(), 375); + assert_eq!(sm70.len(), 329); assert!(sm70.iter().all(|n| !n.starts_with("gemmi") && !n.starts_with("gemmis")), "sm_70 must not load the int8 prefill GEMM: {:?}", sm70.iter().filter(|n| n.starts_with("gemmi")).collect::>()); From 7a2f4665af3093b33e0caf8a7604a57ebf1d3afc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Sacilotti?= Date: Mon, 23 Nov 2026 16:24:05 -0300 Subject: [PATCH 8/9] cuda: prompt attention tiles sixteen queries a block The kp kernel staged a 32-key K/V tile for four queries (one a warp), and the tile load plus the per-tile softmax reductions were paid four times more often than the FMAs need. kp16 gives a warp four queries and a block sixteen: the K row is read once per 32 keys and used by four dots, V is read once a key for all four. Prompt prefill at 32k of context: 757 to 809 tok/s at 2048 tokens, 714 to 779 at 4096, 658 to 736 at 8192 (the gain grows with depth, as the K/V re-read did). STRATA_DS_ATTN_KP4=1 keeps the four-query kernel. tests/inkling2_forward still matches llama.cpp (24/24, 47/48 with the same near tie, chunked and speculative tests pass). (cherry picked from commit 0a386791ab36a5cae0d131f8e97c8aab4e19e112) --- src/cuda/kernels.cu | 133 +++++++++++++++++++++++++++++++++++++++++++- src/cuda/mod.rs | 22 +++++--- 2 files changed, 144 insertions(+), 11 deletions(-) diff --git a/src/cuda/kernels.cu b/src/cuda/kernels.cu index ee4d17ff..fa3d7b39 100644 --- a/src/cuda/kernels.cu +++ b/src/cuda/kernels.cu @@ -2828,12 +2828,11 @@ __device__ void ink_attn_prefill_t(const float* q, const float* r, const float* } DEF_INK_PREFILL(32) DEF_INK_PREFILL(64) DEF_INK_PREFILL(128) #if KV_MODE == 0 -// Local patch: key-parallel version of `ink_attn_prefill_t` for hd = 128 and an f16 cache. The old kernel gave a warp one +// Key-parallel version of `ink_attn_prefill_t` for hd = 128 and an f16 cache. The old kernel gave a warp one // (query, head) and walked the keys one at a time: two warp reductions and a dozen shuffles per key. Here the block's four // warps (four queries, one head) share a 32-key K/V tile in shared memory, lane i scores key i of the tile (the 128-long // dot product is its own, no shuffles), and a warp reduces once per tile for the online softmax. Same math, summed in // another order. Needs nr <= 32 and nr % 4 == 0 (the relative-bias rows are read as float4). -__device__ __forceinline__ float2 ink_h2f2(unsigned w) { return make_float2(h2f((u16)(w & 0xFFFFu)), h2f((u16)(w >> 16))); } __device__ __forceinline__ float ink_warp_max(float v) { for (int o = 16; o; o >>= 1) v = fmaxf(v, __shfl_xor_sync(0xffffffff, v, o)); return v; @@ -2932,6 +2931,121 @@ __device__ void ink_attn_prefill_kp(const float* q, const float* r, const float* } } } +// The same attention with four queries a warp and sixteen a block: a 32-key K/V tile is staged once for 16 queries +// instead of 4, so the loads, the staging and the softmax reductions are amortized over four times the queries. The +// earlier kernel ran at 2.3 TFLOP/s (DRAM- and issue-bound) and was 28% of a 4k-token prefill. +__device__ void ink_attn_prefill_kp16(const float* q, const float* r, const float* sink, const float* gate, + const u16* kc, const u16* vc, const u16* kc_new, const u16* vc_new, + const float* bias, float* outp, + int pos, int nt, int nh, int nkv, int nr, int ext, int ring, int win) { + constexpr int HD = 128, PQ = HD + 8, QW = 4, QB = 16; + __shared__ __align__(16) u16 ks[32 * PQ], vs[32 * PQ]; + __shared__ __align__(16) float qs[QB][HD], rs[QB][32], ps[QB][32]; + const int tid = threadIdx.x, warp = tid >> 5, lane = tid & 31, h = blockIdx.y; + const int t0 = blockIdx.x * QB, qh = warp * QW; + const int kh = h / (nh / nkv), kw = nkv * HD; + const float scale = 1.f / sqrtf((float)HD); + int start[QW], qpos[QW], valid_t[QW]; + float sk[QW]; + for (int j = 0; j < QW; j++) { + const int t = t0 + qh + j; + valid_t[j] = t < nt; + qpos[j] = pos + t; + start[j] = (win > 0 && qpos[j] + 1 > win) ? (qpos[j] + 1 - win) : 0; + sk[j] = 0.f; + if (!valid_t[j]) continue; + const float* qr = q + ((size_t)t * nh + h) * HD; + for (int d = lane; d < HD; d += 32) qs[qh + j][d] = qr[d] * scale; + rs[qh + j][lane] = lane < nr ? r[((size_t)t * nh + h) * nr + lane] : 0.f; + sk[j] = sink[(size_t)t * nh + h]; + } + const int kmax = pos + min(t0 + QB - 1, nt - 1); + const int kmin = (win > 0 && pos + t0 + 1 > win) ? (pos + t0 + 1 - win) : 0; + float m[QW], l[QW], acc[QW][4]; + for (int j = 0; j < QW; j++) { + m[j] = 0.f; l[j] = 1.f; + for (int i = 0; i < 4; i++) acc[j][i] = 0.f; + } + const int kp_last = qpos[QW - 1]; + for (int k0 = kmin; k0 <= kmax; k0 += 32) { + __syncthreads(); +#pragma unroll + for (int n = 0; n < 4; n++) { + const int i = tid + n * 128, rr = i >> 4, c = (i & 15) * 8, kp = k0 + rr; + uint4 kv = make_uint4(0, 0, 0, 0), vv = kv; + if (kp <= kmax) { + const bool un = kc_new && kp >= pos; + const size_t row = un ? (size_t)(kp - pos) : (win > 0 ? (size_t)(kp % ring) : (size_t)kp); + const size_t off = row * kw + (size_t)kh * HD + c; + kv = *(const uint4*)((un ? kc_new : kc) + off); + vv = *(const uint4*)((un ? vc_new : vc) + off); + } + *(uint4*)(ks + rr * PQ + c) = kv; + *(uint4*)(vs + rr * PQ + c) = vv; + } + __syncthreads(); + const int kp = k0 + lane; + const u16* kr = ks + lane * PQ; + uint4 krow[HD / 8]; +#pragma unroll + for (int mm = 0; mm < HD / 8; mm++) krow[mm] = *(const uint4*)(kr + 8 * mm); +#pragma unroll + for (int j = 0; j < QW; j++) { + if (!valid_t[j]) continue; + const float* qj = qs[qh + j]; + float sd = 0.f; +#pragma unroll + for (int mm = 0; mm < HD / 8; mm++) { + const uint4 w = krow[mm]; + const float2 a = ink_h2f2(w.x), b = ink_h2f2(w.y), c2 = ink_h2f2(w.z), e = ink_h2f2(w.w); + sd += qj[8 * mm + 0] * a.x + qj[8 * mm + 1] * a.y + qj[8 * mm + 2] * b.x + qj[8 * mm + 3] * b.y + + qj[8 * mm + 4] * c2.x + qj[8 * mm + 5] * c2.y + qj[8 * mm + 6] * e.x + qj[8 * mm + 7] * e.y; + } + const bool valid = kp >= start[j] && kp <= qpos[j]; + const int dist = qpos[j] - kp; + float b = 0.f; + if (valid && dist < ext) { + const float4* br = (const float4*)(bias + (size_t)dist * nr); + for (int c = 0; c < nr; c += 4) { + const float4 bv = br[c >> 2]; + b += rs[qh + j][c] * bv.x + rs[qh + j][c + 1] * bv.y + rs[qh + j][c + 2] * bv.z + rs[qh + j][c + 3] * bv.w; + } + } + const float logit = valid ? sd + b - sk[j] : -INFINITY; + const float mn = fmaxf(m[j], ink_warp_max(logit)); + const float cc = expf(m[j] - mn); + const float p = valid ? expf(logit - mn) : 0.f; + l[j] = l[j] * cc + warp_sum(p); + m[j] = mn; + acc[j][0] *= cc; acc[j][1] *= cc; acc[j][2] *= cc; acc[j][3] *= cc; + ps[qh + j][lane] = p; + } + __syncwarp(); + const int nk = min(32, kp_last - k0 + 1); + for (int i = 0; i < nk; i++) { + const uint2 vw = *(const uint2*)(vs + i * PQ + 4 * lane); + const float2 v01 = ink_h2f2(vw.x), v23 = ink_h2f2(vw.y); +#pragma unroll + for (int j = 0; j < QW; j++) { + if (!valid_t[j]) continue; + const float pi = ps[qh + j][i]; + acc[j][0] += pi * v01.x; acc[j][1] += pi * v01.y; acc[j][2] += pi * v23.x; acc[j][3] += pi * v23.y; + } + } + __syncwarp(); + } +#pragma unroll + for (int j = 0; j < QW; j++) { + if (!valid_t[j]) continue; + const int t = t0 + qh + j; + const float inv = 1.f / l[j]; +#pragma unroll + for (int i = 0; i < 4; i++) { + const size_t idx = ((size_t)t * nh + h) * HD + 4 * lane + i; + outp[idx] = acc[j][i] * inv * sigmoid(gate[idx]); + } + } +} // The old kernel stays reachable as ink_attn_prefill_128_old (STRATA_DS_ATTN_OLD=1) and takes the shapes the new one does not. extern "C" __global__ void __launch_bounds__(128) ink_attn_prefill_128_old( const float* q, const float* r, const float* sink, const float* gate, @@ -2948,6 +3062,14 @@ extern "C" __global__ void __launch_bounds__(128) ink_attn_prefill_128_kp( if (nr <= 32 && (nr & 3) == 0) ink_attn_prefill_kp(q, r, sink, gate, kc, vc, kc_new, vc_new, bias, outp, pos, nt, nh, nkv, nr, ext, ring, win); else ink_attn_prefill_t<4>(q, r, sink, gate, kc, vc, kc_new, vc_new, bias, outp, pos, nt, nh, nkv, nr, ext, ring, win); } +extern "C" __global__ void __launch_bounds__(128) ink_attn_prefill_128_kp16( + const float* q, const float* r, const float* sink, const float* gate, + const u16* kc, const u16* vc, const u16* kc_new, const u16* vc_new, + const float* bias, float* outp, + int pos, int nt, int nh, int nkv, int nr, int ext, int ring, int win) { + if (nr <= 32 && (nr & 3) == 0) ink_attn_prefill_kp16(q, r, sink, gate, kc, vc, kc_new, vc_new, bias, outp, pos, nt, nh, nkv, nr, ext, ring, win); + else ink_attn_prefill_t<4>(q, r, sink, gate, kc, vc, kc_new, vc_new, bias, outp, pos, nt, nh, nkv, nr, ext, ring, win); +} #else extern "C" __global__ void __launch_bounds__(128) ink_attn_prefill_128_old( const float* q, const float* r, const float* sink, const float* gate, @@ -2963,6 +3085,13 @@ extern "C" __global__ void __launch_bounds__(128) ink_attn_prefill_128_kp( int pos, int nt, int nh, int nkv, int nr, int ext, int ring, int win) { ink_attn_prefill_t<4>(q, r, sink, gate, kc, vc, kc_new, vc_new, bias, outp, pos, nt, nh, nkv, nr, ext, ring, win); } +extern "C" __global__ void __launch_bounds__(128) ink_attn_prefill_128_kp16( + const float* q, const float* r, const float* sink, const float* gate, + const u16* kc, const u16* vc, const u16* kc_new, const u16* vc_new, + const float* bias, float* outp, + int pos, int nt, int nh, int nkv, int nr, int ext, int ring, int win) { + ink_attn_prefill_t<4>(q, r, sink, gate, kc, vc, kc_new, vc_new, bias, outp, pos, nt, nh, nkv, nr, ext, ring, win); +} #endif template __device__ void attn_decode_llama(const float* q, const u16* kc, const u16* vc, float* part, const int* step, diff --git a/src/cuda/mod.rs b/src/cuda/mod.rs index 8841f6fd..5eafe791 100644 --- a/src/cuda/mod.rs +++ b/src/cuda/mod.rs @@ -17,13 +17,13 @@ const QTYPES: [GgmlType; 29] = { use GgmlType::*; [F32, BF16, F8E4M3, Q8_0, Q2K, Q3K, Q4K, Q5K, Q6K, IQ1S, IQ1M, IQ2XXS, IQ2XS, IQ2S, IQ3XXS, IQ3S, IQ4XS, IQ4NL, Q2_0, TQ1_0, TQ2_0, TQ2T, TQK6, TQK7, Q4_1, Q5_1, Q4_0, Q5_0, NVFP4] }; -const KERNELS: [&str; 59] = [ +const KERNELS: [&str; 60] = [ "rope_freq", "qsa_pool", "qsa_score", "qsa_select", "rms_norm", "quant_xq", "argmax_part", "argmax_rows", "l2_norm", "rope_neox", "rms_norm_rope", "add", "swiglu", "situ", "situ_q", "softcap", "swiglu_q", "ssm_gates", "conv_silu", "deltanet_seq", "norm_gate", "kv_store", "attn_merge", "router_topk", "moe_combine", "moe_route", "conv_seq", "conv_state", "moe_combine_seq", "moe_prefetch", "attn_prefill_64", "attn_prefill_128", "attn_prefill_256", "quant_q8", "hc_silu", "hc_mix", "hc_write", "ple_gate", "ple_conv", "dflash2_conv", "hadamard", "ink_mix", "ink_ctrl_gate", "ink_ctrl_out", "ink_ctrl_gate_b", "ink_ctrl_out_b", "ink_conv", "ink_conv_batch", "ink_clip", "ink_attn", "ink_attn_128", "ink_attn_merge", - "ink_attn_prefill_32", "ink_attn_prefill_64", "ink_attn_prefill_128", "ink_attn_prefill_128_old", "ink_attn_prefill_128_kp", "ink_ffn_sum", "ink_route", + "ink_attn_prefill_32", "ink_attn_prefill_64", "ink_attn_prefill_128", "ink_attn_prefill_128_old", "ink_attn_prefill_128_kp", "ink_attn_prefill_128_kp16", "ink_ffn_sum", "ink_route", ]; pub use crate::backend::{ATT_GQA_MIN, ATT_SPLITS, GEMM_BM, GpuTensor}; @@ -1164,13 +1164,17 @@ impl Backend for Gpu { &self, q: u64, r: u64, sink: u64, gate: u64, kc: u64, vc: u64, kc_new: u64, vc_new: u64, bias: u64, out: u64, pos: usize, nt: usize, nh: usize, nkv: usize, hd: usize, nr: usize, ext: usize, ring: usize, win: usize, ) -> anyhow::Result<()> { - let kn = match hd { - 32 => "ink_attn_prefill_32", - 64 => "ink_attn_prefill_64", - 128 => if std::env::var_os("STRATA_DS_ATTN_OLD").is_some() { "ink_attn_prefill_128_old" } else { "ink_attn_prefill_128_kp" }, + // The f16 head_dim 128 path scores a 16-query tile a block (kp16), the kp kernel four (a measurement + // window, STRATA_DS_ATTN_KP4=1) and the first one a query a warp (STRATA_DS_ATTN_OLD=1). + let (kn, qb) = match hd { + 32 => ("ink_attn_prefill_32", 4), + 64 => ("ink_attn_prefill_64", 4), + 128 if std::env::var_os("STRATA_DS_ATTN_OLD").is_some() => ("ink_attn_prefill_128_old", 4), + 128 if std::env::var_os("STRATA_DS_ATTN_KP4").is_some() || self.kv_mode != 0 => ("ink_attn_prefill_128_kp", 4), + 128 => ("ink_attn_prefill_128_kp16", 16), _ => anyhow::bail!("ink_attn_prefill: unsupported hd={hd}"), }; - launch!(self, kn, cfg((nt.div_ceil(4) as u32, nh as u32), 128, 0), + launch!(self, kn, cfg((nt.div_ceil(qb) as u32, nh as u32), 128, 0), q, r, sink, gate, kc, vc, kc_new, vc_new, bias, out, pos as i32, nt as i32, nh as i32, nkv as i32, nr as i32, ext as i32, ring.max(1) as i32, win as i32); Ok(()) @@ -1523,8 +1527,8 @@ mod tests { #[test] fn kernel_names() { let (sm70, sm80) = (super::kernel_names(false), super::kernel_names(true)); - assert_eq!(sm80.len(), 375); - assert_eq!(sm70.len(), 329); + assert_eq!(sm80.len(), 376); + assert_eq!(sm70.len(), 330); assert!(sm70.iter().all(|n| !n.starts_with("gemmi") && !n.starts_with("gemmis")), "sm_70 must not load the int8 prefill GEMM: {:?}", sm70.iter().filter(|n| n.starts_with("gemmi")).collect::>()); From 0c9a4dbf745886941691f881c6f238793701adb9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Sacilotti?= Date: Tue, 24 Nov 2026 07:34:42 -0300 Subject: [PATCH 9/9] review: the kp16 fallback covers all sixteen queries, and the other findings The 16-query prefill entry point is launched with a 16-token grid; when the relative-bias width does not fit the four-query kernel (nr > 32 or nr % 4 != 0), the fallback now calls it four times with a tbase, so tokens 4..15 of each tile are written. kp and kp16 become one template (QPB) and ink_attn_prefill_t takes the base. The 128-key decode kernel keeps the bias row in 32 shared floats: only select it for nr <= 32, and the scalar kernel otherwise. The plain-first branch keeps 768 MB of live free VRAM for the state, KV and prefill scratch (the state is allocated outside the weight budget); checking `room` alone would move the plain weights to GPU 1. The expert group is consumed on a cache hit, the CUDA flags are cached on the Gpu, the bench script survives a failed or silent row and passes PLAIN_FIRST=0, and the KLD compare streams the files. Tests cover the kp16 fallback (nr 28/30/40), the bench script and the streaming compare. --- src/cuda/kernels.cu | 160 ++++++++------------------------- src/cuda/mod.rs | 75 +++++++++++++--- src/deepseek/mat.rs | 45 +++++++++- src/inkling2/forward/device.rs | 9 +- tests/bench_script.rs | 150 +++++++++++++++++++++++++++++++ tests/kernels.rs | 52 +++++++++++ tools/bench_2x3060.sh | 22 +++-- tools/kld_compare.py | 15 +++- tools/test_kld_compare.py | 63 +++++++++++++ 9 files changed, 439 insertions(+), 152 deletions(-) create mode 100644 tests/bench_script.rs create mode 100644 tools/test_kld_compare.py diff --git a/src/cuda/kernels.cu b/src/cuda/kernels.cu index fa3d7b39..f6eecd43 100644 --- a/src/cuda/kernels.cu +++ b/src/cuda/kernels.cu @@ -2770,8 +2770,8 @@ template __device__ void ink_attn_prefill_t(const float* q, const float* r, const float* sink, const float* gate, const u16* kc, const u16* vc, const u16* kc_new, const u16* vc_new, const float* bias, float* outp, - int pos, int nt, int nh, int nkv, int nr, int ext, int ring, int win) { - int t = blockIdx.x * 4 + (threadIdx.x >> 5), h = blockIdx.y, lane = threadIdx.x & 31; + int pos, int nt, int nh, int nkv, int nr, int ext, int ring, int win, int tbase) { + int t = tbase + (threadIdx.x >> 5), h = blockIdx.y, lane = threadIdx.x & 31; if (t >= nt) return; constexpr int HD = 32 * PER; int kh = h / (nh / nkv), kw = nkv * HD; @@ -2824,130 +2824,35 @@ __device__ void ink_attn_prefill_t(const float* q, const float* r, const float* const u16* kc, const u16* vc, const u16* kc_new, const u16* vc_new, \ const float* bias, float* outp, \ int pos, int nt, int nh, int nkv, int nr, int ext, int ring, int win) { \ - ink_attn_prefill_t(q, r, sink, gate, kc, vc, kc_new, vc_new, bias, outp, pos, nt, nh, nkv, nr, ext, ring, win); \ + ink_attn_prefill_t(q, r, sink, gate, kc, vc, kc_new, vc_new, bias, outp, pos, nt, nh, nkv, nr, ext, ring, win, blockIdx.x * 4); \ } DEF_INK_PREFILL(32) DEF_INK_PREFILL(64) DEF_INK_PREFILL(128) #if KV_MODE == 0 -// Key-parallel version of `ink_attn_prefill_t` for hd = 128 and an f16 cache. The old kernel gave a warp one -// (query, head) and walked the keys one at a time: two warp reductions and a dozen shuffles per key. Here the block's four -// warps (four queries, one head) share a 32-key K/V tile in shared memory, lane i scores key i of the tile (the 128-long -// dot product is its own, no shuffles), and a warp reduces once per tile for the online softmax. Same math, summed in -// another order. Needs nr <= 32 and nr % 4 == 0 (the relative-bias rows are read as float4). +// Key-parallel prefill attention for hd = 128 and an f16 cache, QPB queries a warp. The old kernel gave a warp one +// (query, head) and walked the keys one at a time: two warp reductions and a dozen shuffles per key. Here the block's +// four warps share a 32-key K/V tile in shared memory, lane i scores key i of the tile (the 128-long dot product is +// its own, no shuffles), and a warp reduces once per tile for the online softmax. QPB=1 is one query a warp (four a +// block), QPB=4 is four a warp (sixteen a block). Same math, summed in another order. Needs nr <= 32 and +// nr % 4 == 0 (the relative-bias rows are read as float4). __device__ __forceinline__ float ink_warp_max(float v) { for (int o = 16; o; o >>= 1) v = fmaxf(v, __shfl_xor_sync(0xffffffff, v, o)); return v; } -__device__ void ink_attn_prefill_kp(const float* q, const float* r, const float* sink, const float* gate, - const u16* kc, const u16* vc, const u16* kc_new, const u16* vc_new, - const float* bias, float* outp, - int pos, int nt, int nh, int nkv, int nr, int ext, int ring, int win) { - constexpr int HD = 128, PQ = HD + 8; - __shared__ __align__(16) u16 ks[32 * PQ]; - __shared__ __align__(16) u16 vs[32 * PQ]; - __shared__ __align__(16) float qs[4][HD]; - __shared__ __align__(16) float rs[4][32]; - __shared__ float ps[4][32]; - const int tid = threadIdx.x, warp = tid >> 5, lane = tid & 31, h = blockIdx.y; - const int t0 = blockIdx.x * 4, t = t0 + warp; - const bool act = t < nt; - const int kh = h / (nh / nkv), kw = nkv * HD; - const int q_pos = pos + t; - const int start = (win > 0 && q_pos + 1 > win) ? (q_pos + 1 - win) : 0; - float sink_val = 0.f; - if (act) { - const float scale = 1.f / sqrtf((float)HD); - for (int d = lane; d < HD; d += 32) qs[warp][d] = q[((size_t)t * nh + h) * HD + d] * scale; - rs[warp][lane] = lane < nr ? r[((size_t)t * nh + h) * nr + lane] : 0.f; - sink_val = sink[(size_t)t * nh + h]; - } - const int kmax = pos + min(t0 + 3, nt - 1); - const int pq0 = pos + t0; - const int kmin = (win > 0 && pq0 + 1 > win) ? (pq0 + 1 - win) : 0; - float m = 0.f, l = 1.f, acc[4] = {0.f, 0.f, 0.f, 0.f}; - for (int k0 = kmin; k0 <= kmax; k0 += 32) { - __syncthreads(); -#pragma unroll - for (int n = 0; n < 4; n++) { - int i = tid + n * 128, rr = i >> 4, c = (i & 15) * 8, kp = k0 + rr; - uint4 kv = make_uint4(0, 0, 0, 0), vv = kv; - if (kp <= kmax) { - bool un = kc_new && kp >= pos; - size_t row = un ? (size_t)(kp - pos) : (win > 0 ? (size_t)(kp % ring) : (size_t)kp); - size_t off = row * kw + (size_t)kh * HD + c; - kv = *(const uint4*)((un ? kc_new : kc) + off); - vv = *(const uint4*)((un ? vc_new : vc) + off); - } - *(uint4*)(ks + rr * PQ + c) = kv; - *(uint4*)(vs + rr * PQ + c) = vv; - } - __syncthreads(); - if (!act) continue; - const int kp = k0 + lane; - const bool valid = kp >= start && kp <= q_pos; - float sd = 0.f; - const u16* kr = ks + lane * PQ; -#pragma unroll - for (int mm = 0; mm < 16; mm++) { - uint4 w = *(const uint4*)(kr + 8 * mm); - float4 qa = *(const float4*)(&qs[warp][8 * mm]); - float4 qb = *(const float4*)(&qs[warp][8 * mm + 4]); - float2 f0 = ink_h2f2(w.x), f1 = ink_h2f2(w.y); - float2 f2 = ink_h2f2(w.z), f3 = ink_h2f2(w.w); - sd += qa.x * f0.x + qa.y * f0.y + qa.z * f1.x + qa.w * f1.y + qb.x * f2.x + qb.y * f2.y + qb.z * f3.x + qb.w * f3.y; - } - float b = 0.f; - const int dist = q_pos - kp; - if (valid && dist < ext) { - const float4* br = (const float4*)(bias + (size_t)dist * nr); - for (int c = 0; c < nr; c += 4) { - float4 bv = br[c >> 2]; - b += rs[warp][c] * bv.x + rs[warp][c + 1] * bv.y + rs[warp][c + 2] * bv.z + rs[warp][c + 3] * bv.w; - } - } - const float logit = valid ? sd + b - sink_val : -INFINITY; - const float mn = fmaxf(m, ink_warp_max(logit)); - const float cc = expf(m - mn); - const float p = valid ? expf(logit - mn) : 0.f; - l = l * cc + warp_sum(p); - m = mn; - acc[0] *= cc; acc[1] *= cc; acc[2] *= cc; acc[3] *= cc; - ps[warp][lane] = p; - __syncwarp(); - const int nk = min(32, q_pos - k0 + 1); - for (int i = 0; i < nk; i++) { - float pi = ps[warp][i]; - uint2 vw = *(const uint2*)(vs + i * PQ + 4 * lane); - float2 v01 = ink_h2f2(vw.x), v23 = ink_h2f2(vw.y); - acc[0] += pi * v01.x; acc[1] += pi * v01.y; acc[2] += pi * v23.x; acc[3] += pi * v23.y; - } - __syncwarp(); - } - if (act) { - const float inv = 1.f / l; -#pragma unroll - for (int j = 0; j < 4; j++) { - size_t idx = ((size_t)t * nh + h) * HD + 4 * lane + j; - outp[idx] = acc[j] * inv * sigmoid(gate[idx]); - } - } -} -// The same attention with four queries a warp and sixteen a block: a 32-key K/V tile is staged once for 16 queries -// instead of 4, so the loads, the staging and the softmax reductions are amortized over four times the queries. The -// earlier kernel ran at 2.3 TFLOP/s (DRAM- and issue-bound) and was 28% of a 4k-token prefill. -__device__ void ink_attn_prefill_kp16(const float* q, const float* r, const float* sink, const float* gate, +template +__device__ void ink_attn_prefill_kp_t(const float* q, const float* r, const float* sink, const float* gate, const u16* kc, const u16* vc, const u16* kc_new, const u16* vc_new, const float* bias, float* outp, int pos, int nt, int nh, int nkv, int nr, int ext, int ring, int win) { - constexpr int HD = 128, PQ = HD + 8, QW = 4, QB = 16; + constexpr int HD = 128, PQ = HD + 8, QB = 4 * QPB; __shared__ __align__(16) u16 ks[32 * PQ], vs[32 * PQ]; __shared__ __align__(16) float qs[QB][HD], rs[QB][32], ps[QB][32]; const int tid = threadIdx.x, warp = tid >> 5, lane = tid & 31, h = blockIdx.y; - const int t0 = blockIdx.x * QB, qh = warp * QW; + const int t0 = blockIdx.x * QB, qh = warp * QPB; const int kh = h / (nh / nkv), kw = nkv * HD; const float scale = 1.f / sqrtf((float)HD); - int start[QW], qpos[QW], valid_t[QW]; - float sk[QW]; - for (int j = 0; j < QW; j++) { + int start[QPB], qpos[QPB], valid_t[QPB]; + float sk[QPB]; + for (int j = 0; j < QPB; j++) { const int t = t0 + qh + j; valid_t[j] = t < nt; qpos[j] = pos + t; @@ -2961,12 +2866,12 @@ __device__ void ink_attn_prefill_kp16(const float* q, const float* r, const floa } const int kmax = pos + min(t0 + QB - 1, nt - 1); const int kmin = (win > 0 && pos + t0 + 1 > win) ? (pos + t0 + 1 - win) : 0; - float m[QW], l[QW], acc[QW][4]; - for (int j = 0; j < QW; j++) { + float m[QPB], l[QPB], acc[QPB][4]; + for (int j = 0; j < QPB; j++) { m[j] = 0.f; l[j] = 1.f; for (int i = 0; i < 4; i++) acc[j][i] = 0.f; } - const int kp_last = qpos[QW - 1]; + const int kp_last = qpos[QPB - 1]; for (int k0 = kmin; k0 <= kmax; k0 += 32) { __syncthreads(); #pragma unroll @@ -2990,7 +2895,7 @@ __device__ void ink_attn_prefill_kp16(const float* q, const float* r, const floa #pragma unroll for (int mm = 0; mm < HD / 8; mm++) krow[mm] = *(const uint4*)(kr + 8 * mm); #pragma unroll - for (int j = 0; j < QW; j++) { + for (int j = 0; j < QPB; j++) { if (!valid_t[j]) continue; const float* qj = qs[qh + j]; float sd = 0.f; @@ -3026,7 +2931,7 @@ __device__ void ink_attn_prefill_kp16(const float* q, const float* r, const floa const uint2 vw = *(const uint2*)(vs + i * PQ + 4 * lane); const float2 v01 = ink_h2f2(vw.x), v23 = ink_h2f2(vw.y); #pragma unroll - for (int j = 0; j < QW; j++) { + for (int j = 0; j < QPB; j++) { if (!valid_t[j]) continue; const float pi = ps[qh + j][i]; acc[j][0] += pi * v01.x; acc[j][1] += pi * v01.y; acc[j][2] += pi * v23.x; acc[j][3] += pi * v23.y; @@ -3035,7 +2940,7 @@ __device__ void ink_attn_prefill_kp16(const float* q, const float* r, const floa __syncwarp(); } #pragma unroll - for (int j = 0; j < QW; j++) { + for (int j = 0; j < QPB; j++) { if (!valid_t[j]) continue; const int t = t0 + qh + j; const float inv = 1.f / l[j]; @@ -3046,29 +2951,33 @@ __device__ void ink_attn_prefill_kp16(const float* q, const float* r, const floa } } } + // The old kernel stays reachable as ink_attn_prefill_128_old (STRATA_DS_ATTN_OLD=1) and takes the shapes the new one does not. extern "C" __global__ void __launch_bounds__(128) ink_attn_prefill_128_old( const float* q, const float* r, const float* sink, const float* gate, const u16* kc, const u16* vc, const u16* kc_new, const u16* vc_new, const float* bias, float* outp, int pos, int nt, int nh, int nkv, int nr, int ext, int ring, int win) { - ink_attn_prefill_t<4>(q, r, sink, gate, kc, vc, kc_new, vc_new, bias, outp, pos, nt, nh, nkv, nr, ext, ring, win); + ink_attn_prefill_t<4>(q, r, sink, gate, kc, vc, kc_new, vc_new, bias, outp, pos, nt, nh, nkv, nr, ext, ring, win, blockIdx.x * 4); } extern "C" __global__ void __launch_bounds__(128) ink_attn_prefill_128_kp( const float* q, const float* r, const float* sink, const float* gate, const u16* kc, const u16* vc, const u16* kc_new, const u16* vc_new, const float* bias, float* outp, int pos, int nt, int nh, int nkv, int nr, int ext, int ring, int win) { - if (nr <= 32 && (nr & 3) == 0) ink_attn_prefill_kp(q, r, sink, gate, kc, vc, kc_new, vc_new, bias, outp, pos, nt, nh, nkv, nr, ext, ring, win); - else ink_attn_prefill_t<4>(q, r, sink, gate, kc, vc, kc_new, vc_new, bias, outp, pos, nt, nh, nkv, nr, ext, ring, win); + if (nr <= 32 && (nr & 3) == 0) ink_attn_prefill_kp_t<1>(q, r, sink, gate, kc, vc, kc_new, vc_new, bias, outp, pos, nt, nh, nkv, nr, ext, ring, win); + else ink_attn_prefill_t<4>(q, r, sink, gate, kc, vc, kc_new, vc_new, bias, outp, pos, nt, nh, nkv, nr, ext, ring, win, blockIdx.x * 4); } extern "C" __global__ void __launch_bounds__(128) ink_attn_prefill_128_kp16( const float* q, const float* r, const float* sink, const float* gate, const u16* kc, const u16* vc, const u16* kc_new, const u16* vc_new, const float* bias, float* outp, int pos, int nt, int nh, int nkv, int nr, int ext, int ring, int win) { - if (nr <= 32 && (nr & 3) == 0) ink_attn_prefill_kp16(q, r, sink, gate, kc, vc, kc_new, vc_new, bias, outp, pos, nt, nh, nkv, nr, ext, ring, win); - else ink_attn_prefill_t<4>(q, r, sink, gate, kc, vc, kc_new, vc_new, bias, outp, pos, nt, nh, nkv, nr, ext, ring, win); + if (nr <= 32 && (nr & 3) == 0) ink_attn_prefill_kp_t<4>(q, r, sink, gate, kc, vc, kc_new, vc_new, bias, outp, pos, nt, nh, nkv, nr, ext, ring, win); + // The 4-query kernel writes four tokens a block; the host launches this entry point with a 16-token grid, so a + // fallback that calls it once would leave tokens 4..15 of every tile unwritten. Four calls cover the whole tile. + else for (int q0 = 0; q0 < 16; q0 += 4) + ink_attn_prefill_t<4>(q, r, sink, gate, kc, vc, kc_new, vc_new, bias, outp, pos, nt, nh, nkv, nr, ext, ring, win, blockIdx.x * 16 + q0); } #else extern "C" __global__ void __launch_bounds__(128) ink_attn_prefill_128_old( @@ -3076,21 +2985,22 @@ extern "C" __global__ void __launch_bounds__(128) ink_attn_prefill_128_old( const u16* kc, const u16* vc, const u16* kc_new, const u16* vc_new, const float* bias, float* outp, int pos, int nt, int nh, int nkv, int nr, int ext, int ring, int win) { - ink_attn_prefill_t<4>(q, r, sink, gate, kc, vc, kc_new, vc_new, bias, outp, pos, nt, nh, nkv, nr, ext, ring, win); + ink_attn_prefill_t<4>(q, r, sink, gate, kc, vc, kc_new, vc_new, bias, outp, pos, nt, nh, nkv, nr, ext, ring, win, blockIdx.x * 4); } extern "C" __global__ void __launch_bounds__(128) ink_attn_prefill_128_kp( const float* q, const float* r, const float* sink, const float* gate, const u16* kc, const u16* vc, const u16* kc_new, const u16* vc_new, const float* bias, float* outp, int pos, int nt, int nh, int nkv, int nr, int ext, int ring, int win) { - ink_attn_prefill_t<4>(q, r, sink, gate, kc, vc, kc_new, vc_new, bias, outp, pos, nt, nh, nkv, nr, ext, ring, win); + ink_attn_prefill_t<4>(q, r, sink, gate, kc, vc, kc_new, vc_new, bias, outp, pos, nt, nh, nkv, nr, ext, ring, win, blockIdx.x * 4); } extern "C" __global__ void __launch_bounds__(128) ink_attn_prefill_128_kp16( const float* q, const float* r, const float* sink, const float* gate, const u16* kc, const u16* vc, const u16* kc_new, const u16* vc_new, const float* bias, float* outp, int pos, int nt, int nh, int nkv, int nr, int ext, int ring, int win) { - ink_attn_prefill_t<4>(q, r, sink, gate, kc, vc, kc_new, vc_new, bias, outp, pos, nt, nh, nkv, nr, ext, ring, win); + for (int q0 = 0; q0 < 16; q0 += 4) + ink_attn_prefill_t<4>(q, r, sink, gate, kc, vc, kc_new, vc_new, bias, outp, pos, nt, nh, nkv, nr, ext, ring, win, blockIdx.x * 16 + q0); } #endif template diff --git a/src/cuda/mod.rs b/src/cuda/mod.rs index 5eafe791..76980acf 100644 --- a/src/cuda/mod.rs +++ b/src/cuda/mod.rs @@ -29,6 +29,33 @@ const KERNELS: [&str; 60] = [ pub use crate::backend::{ATT_GQA_MIN, ATT_SPLITS, GEMM_BM, GpuTensor}; use crate::backend::ATT_SPLITS_1; +/// Kernel-choice flags read from the environment once, when the `Gpu` is made: they sit on the token path, so a +/// lookup per launch is not worth it. +#[derive(Clone, Copy)] +struct InkFlags { + /// `STRATA_CTRL_TILE=0` forces the per-token `ink_ctrl_*` pair (unset or any other value: tiled). + ctrl_tile: bool, + /// `STRATA_DS_ATTN_OLD=1` keeps the scalar/one-query-a-warp attention kernels for a measurement window. + attn_old: bool, + /// `STRATA_DS_ATTN_KP4=1` selects the four-query 128-key tile prefill kernel. + attn_kp4: bool, +} + +impl InkFlags { + fn from_parts(ctrl: Option<&str>, attn_old: Option<&str>, attn_kp4: Option<&str>) -> Self { + // The same truthiness for all three: unset is the default, `0` turns the option off. + let on = |v: Option<&str>, default: bool| v.map_or(default, |v| v != "0"); + Self { ctrl_tile: on(ctrl, true), attn_old: on(attn_old, false), attn_kp4: on(attn_kp4, false) } + } + fn from_env() -> Self { + Self::from_parts( + std::env::var("STRATA_CTRL_TILE").ok().as_deref(), + std::env::var("STRATA_DS_ATTN_OLD").ok().as_deref(), + std::env::var("STRATA_DS_ATTN_KP4").ok().as_deref(), + ) + } +} + pub struct Gpu { pub ctx: Arc, pub stream: Arc, @@ -44,6 +71,8 @@ pub struct Gpu { q8: std::sync::Mutex<(CudaSlice, Option<[u64; 4]>)>, /// The kernels were compiled for KV cache mode (0 = f16, 1 = q8, 2 = q4). pub kv_mode: u32, + /// The environment's kernel-choice flags, read once at creation. + flags: InkFlags, /// The GPU has int8 tensor-core mma (sm_80+). Turing runs the prefill GEMM on the f16 path instead. pub int8_mma: bool, /// sm_75: m16n8k8 mma, 64 KB of shared memory a block (no int8 mma, unlike sm_80+; unlike sm_70 it has no m8n8k4). @@ -523,7 +552,7 @@ impl Gpu { let am = stream.alloc_zeros(64 * AMAX_PARTS)?; let ring = std::sync::Mutex::new((unsafe { ctx.alloc_pinned::(RING)? }, 0, VecDeque::new())); let done = ctx.new_event(None)?; - Ok(Gpu { ctx, side: stream.fork()?, stream, nb: AtomicUsize::new(usize::MAX), fns, i8_gemm, q8, kv_mode, int8_mma, turing, max_smem: max_optin, am, graphs: Default::default(), ring, done, lag: Default::default(), fr: Default::default() }) + Ok(Gpu { ctx, side: stream.fork()?, stream, nb: AtomicUsize::new(usize::MAX), fns, i8_gemm, q8, kv_mode, flags: InkFlags::from_env(), int8_mma, turing, max_smem: max_optin, am, graphs: Default::default(), ring, done, lag: Default::default(), fr: Default::default() }) } fn f(&self, name: &str) -> &CudaFunction { &self.fns[name] } @@ -760,9 +789,11 @@ impl Gpu { impl Gpu { /// The decode attention entry point and its key positions per block: the f16 head_dim 128 kernel scores a - /// 128-key tile a block, the scalar one 64 keys (`STRATA_DS_ATTN_OLD=1` keeps it for a measurement window). - pub(crate) fn ink_attn_kernel(&self, hd: usize) -> (&'static str, usize) { - if hd == 128 && self.kv_mode == 0 && std::env::var_os("STRATA_DS_ATTN_OLD").is_none() { ("ink_attn_128", 128) } else { ("ink_attn", 64) } + /// 128-key tile a block, the scalar one 64 keys (`STRATA_DS_ATTN_OLD=1` keeps it for a measurement window; + /// the flag is cached in `flags` at `Gpu` creation). The 128-key kernel keeps the relative-bias row in 32 + /// shared floats, so a wider `nr` uses the scalar kernel. + pub(crate) fn ink_attn_kernel(&self, hd: usize, nr: usize) -> (&'static str, usize) { + if hd == 128 && nr <= 32 && self.kv_mode == 0 && !self.flags.attn_old { ("ink_attn_128", 128) } else { ("ink_attn", 64) } } } @@ -783,6 +814,7 @@ impl Backend for Gpu { i8_gemm: self.i8_gemm, q8, kv_mode: self.kv_mode, + flags: self.flags, int8_mma: self.int8_mma, turing: self.turing, max_smem: self.max_smem, @@ -1092,8 +1124,9 @@ impl Backend for Gpu { fn ink_ctrl_n(&self, down: u64, gain: u64, forget: u64, cur: u64, nins: usize, msg: u64, gate: u64, out: u64, n: usize, rank: usize, count: usize, nt: usize) -> anyhow::Result<()> { // A prompt chunk uses the tiled pair (a weight row is read once per 64 tokens); a decoded token the // per-token pair, which has no tile to reuse. Both pairs read and write the same gate layout. - // STRATA_CTRL_TILE=0 forces the per-token pair, to compare the two on the same text. - let tiled = nt >= 64 && rank <= 64 && n % 64 == 0 && std::env::var("STRATA_CTRL_TILE").map_or(true, |v| v != "0"); + // STRATA_CTRL_TILE=0 forces the per-token pair, to compare the two on the same text (the flag is cached + // in `flags` at `Gpu` creation). + let tiled = nt >= 64 && rank <= 64 && n % 64 == 0 && self.flags.ctrl_tile; if tiled { let g1 = cfg((count as u32, nt.div_ceil(64) as u32), 256, 0); let g2 = LaunchConfig { grid_dim: (count as u32, n.div_ceil(64) as u32, nt.div_ceil(64) as u32), block_dim: (256, 1, 1), shared_mem_bytes: 0 }; @@ -1125,7 +1158,7 @@ impl Backend for Gpu { pos0: usize, log_alpha: f32, log_floor: f32, ) -> anyhow::Result<()> { anyhow::ensure!(w <= 128, "ink_clip_n: w={w} > 128"); - anyhow::ensure!(kv_mode() == 0 || dst == 0 || w % 32 == 0, "ink_clip_n: quantized KV requires w % 32 == 0 (got {w})"); + anyhow::ensure!(self.kv_mode == 0 || dst == 0 || w % 32 == 0, "ink_clip_n: quantized KV requires w % 32 == 0 (got {w})"); let ring = if dst != 0 { dst_ring.max(1) } else { 1 }; let fl = if log_alpha == 0.0 && log_floor == 0.0 { 1.0 } else { log_floor }; launch!(self, "ink_clip", cfg((rows as u32, nt as u32), 128, 0), @@ -1139,7 +1172,7 @@ impl Backend for Gpu { pos_ptr: u64, log_alpha: f32, log_floor: f32, ) -> anyhow::Result<()> { anyhow::ensure!(w <= 128, "ink_clip_pos: w={w} > 128"); - anyhow::ensure!(kv_mode() == 0 || dst == 0 || w % 32 == 0, "ink_clip_pos: quantized KV requires w % 32 == 0 (got {w})"); + anyhow::ensure!(self.kv_mode == 0 || dst == 0 || w % 32 == 0, "ink_clip_pos: quantized KV requires w % 32 == 0 (got {w})"); let ring = if dst != 0 { dst_ring.max(1) } else { 1 }; let fl = if log_alpha == 0.0 && log_floor == 0.0 { 1.0 } else { log_floor }; launch!(self, "ink_clip", cfg((rows as u32, nt as u32), 128, 0), @@ -1147,14 +1180,14 @@ impl Backend for Gpu { Ok(()) } fn ink_attn(&self, q: u64, r: u64, sink: u64, gate: u64, k: u64, v: u64, bias: u64, sc: u64, out: u64, rows: usize, at: usize, nh: usize, nkv: usize, hd: usize, nr: usize, ext: usize) -> anyhow::Result<()> { - let (kn, ck) = self.ink_attn_kernel(hd); + let (kn, ck) = self.ink_attn_kernel(hd, nr); let chunks = rows.div_ceil(ck) as u32; launch!(self, kn, cfg((nh as u32, chunks), 128, 0), q, r, sink, k, v, bias, sc, rows as i32, at as i32, 1i32, nkv as i32, hd as i32, nr as i32, ext as i32, 0u64); launch!(self, "ink_attn_merge", cfg((nh as u32, 1), 128, 0), sc, gate, out, chunks as i32, hd as i32); Ok(()) } fn ink_attn_pos(&self, q: u64, r: u64, sink: u64, gate: u64, k: u64, v: u64, bias: u64, sc: u64, out: u64, max_rows: usize, ring: usize, pos_ptr: u64, nh: usize, nkv: usize, hd: usize, nr: usize, ext: usize) -> anyhow::Result<()> { - let (kn, ck) = self.ink_attn_kernel(hd); + let (kn, ck) = self.ink_attn_kernel(hd, nr); let chunks = max_rows.div_ceil(ck) as u32; launch!(self, kn, cfg((nh as u32, chunks), 128, 0), q, r, sink, k, v, bias, sc, 0i32, 0i32, ring.max(1) as i32, nkv as i32, hd as i32, nr as i32, ext as i32, pos_ptr); launch!(self, "ink_attn_merge", cfg((nh as u32, 1), 128, 0), sc, gate, out, chunks as i32, hd as i32); @@ -1165,12 +1198,13 @@ impl Backend for Gpu { pos: usize, nt: usize, nh: usize, nkv: usize, hd: usize, nr: usize, ext: usize, ring: usize, win: usize, ) -> anyhow::Result<()> { // The f16 head_dim 128 path scores a 16-query tile a block (kp16), the kp kernel four (a measurement - // window, STRATA_DS_ATTN_KP4=1) and the first one a query a warp (STRATA_DS_ATTN_OLD=1). + // window, STRATA_DS_ATTN_KP4=1) and the first one a query a warp (STRATA_DS_ATTN_OLD=1); both flags are + // cached in `flags` at `Gpu` creation. let (kn, qb) = match hd { 32 => ("ink_attn_prefill_32", 4), 64 => ("ink_attn_prefill_64", 4), - 128 if std::env::var_os("STRATA_DS_ATTN_OLD").is_some() => ("ink_attn_prefill_128_old", 4), - 128 if std::env::var_os("STRATA_DS_ATTN_KP4").is_some() || self.kv_mode != 0 => ("ink_attn_prefill_128_kp", 4), + 128 if self.flags.attn_old => ("ink_attn_prefill_128_old", 4), + 128 if self.flags.attn_kp4 || self.kv_mode != 0 => ("ink_attn_prefill_128_kp", 4), 128 => ("ink_attn_prefill_128_kp16", 16), _ => anyhow::bail!("ink_attn_prefill: unsupported hd={hd}"), }; @@ -1705,4 +1739,19 @@ mod tests { assert_eq!(super::smem_log("attn_decode_*", 98304, 2112, None, None), "cuda shared memory: opt-in 98304 B per block, attn_decode_*: 2112 B static, dynamic max default (48 KiB), carveout default"); } + + /// `STRATA_CTRL_TILE` is read as text: unset or any value but "0" keeps the tiled `ink_ctrl_*` pair. The + /// attention flags are plain presence checks and must pass through unchanged. + #[test] + fn ink_flags_parse_ctrl_tile() { + assert!(super::InkFlags::from_parts(None, None, None).ctrl_tile); + assert!(!super::InkFlags::from_parts(Some("0"), None, None).ctrl_tile); + assert!(super::InkFlags::from_parts(Some("1"), None, None).ctrl_tile); + let old = super::InkFlags::from_parts(None, Some("1"), None); + assert!(old.attn_old && !old.attn_kp4); + let kp4 = super::InkFlags::from_parts(Some("0"), None, Some("1")); + assert!(kp4.attn_kp4 && !kp4.attn_old && !kp4.ctrl_tile); + let off = super::InkFlags::from_parts(Some("0"), Some("0"), Some("0")); + assert!(!off.ctrl_tile && !off.attn_old && !off.attn_kp4); + } } diff --git a/src/deepseek/mat.rs b/src/deepseek/mat.rs index db164271..5b626625 100644 --- a/src/deepseek/mat.rs +++ b/src/deepseek/mat.rs @@ -73,12 +73,44 @@ pub(crate) mod dev { let f: Vec = v.split(',').filter_map(|p| p.trim().parse().ok()).collect(); match f[..] { [small, large] => if free < 8 << 30 { small } else { large }, [v] => v, _ => 0.8 } } + /// Free VRAM GPU 0 keeps after the plain weights for the decode state, the KV growth and the prefill scratch. + /// Those buffers are allocated outside the weight budget, so the reserve is checked against live free VRAM. + const STATE_RESERVE: usize = 768 << 20; + /// Whether `len` more plain-weight bytes fit GPU 0's budget and still leave `STATE_RESERVE` free there. + fn plain_first_fits(bytes: usize, len: usize, budget: usize, free: usize) -> bool { + bytes.saturating_add(len) <= budget && free >= len.saturating_add(STATE_RESERVE) + } + fn plain_first_enabled_from(v: Option<&str>) -> bool { v.is_some_and(|v| v != "0") } + fn plain_first_enabled() -> bool { plain_first_enabled_from(std::env::var("STRATA_DS_PLAIN_FIRST").ok().as_deref()) } #[test] fn gpu_fraction_takes_one_value_or_a_pair() { let gb = |n: usize| n << 30; assert_eq!([gpu_fraction("", gb(4)), gpu_fraction("0.9", gb(4)), gpu_fraction("x", gb(4))], [0.8, 0.9, 0.8]); assert_eq!([gpu_fraction("0.6,0.9", gb(4)), gpu_fraction("0.6, 0.9", gb(11))], [0.6, 0.9]); } + #[test] + fn plain_first_reserves_the_state() { + let budget = 1 << 30; + assert!(plain_first_fits(0, 100, budget, 100 + STATE_RESERVE)); + assert!(!plain_first_fits(0, 100, budget, 100 + STATE_RESERVE - 1)); // free VRAM too low + assert!(!plain_first_fits(budget, 100, budget, 1 << 40)); // budget full + } + #[test] + fn plain_first_env_zero_is_off() { + assert!(!plain_first_enabled_from(None)); + assert!(!plain_first_enabled_from(Some("0"))); + assert!(plain_first_enabled_from(Some("1"))); + } + #[test] + fn expert_group_is_consumed_on_a_cache_hit() { + let mut d = Dev::default(); + let data = vec![0u8; 8]; + let k = data.as_ptr() as usize; + d.ex.insert(k, 0); + d.exs.push((0, k, 1, 1.0)); + assert_eq!(d.expert_grouped((0x1000, 64), &data, GgmlType::F32, 0, 0, 1.0, false), Some(0)); + assert!(d.group.is_none()); + } fn open() -> Option { // Unset or 0: every matvec runs on the CPU. if std::env::var("STRATA_DS_GPU").map_or(true, |v| v == "0") { return None; } @@ -165,9 +197,13 @@ pub(crate) mod dev { pub fn pick(&mut self, len: usize) -> usize { self.reclaim(); // Local patch (Inkling 2 on several GPUs): the decode state lives on GPU 0 and reads the plain weights - // there, so they stay on GPU 0 while the weight budget has room (the old `room` was ~0.3 GB at 0.9). - if self.parts.len() > 1 && self.cur == 0 && std::env::var_os("STRATA_DS_PLAIN_FIRST").is_some() - && self.parts[0].bytes + len <= self.parts[0].budget { return 0; } + // there, so they stay on GPU 0 while the budget has room and the live free VRAM keeps the state reserve. + // The state, KV and prefill scratch are allocated outside the budget; `room` alone would move the plain + // weights to GPU 1 (it is ~0.4 GB at 0.9), which is what this branch avoids. + if self.parts.len() > 1 && self.cur == 0 && plain_first_enabled() { + let free = self.parts[0].be.mem_info().map_or(usize::MAX, |m| m.0); + if plain_first_fits(self.parts[0].bytes, len, self.parts[0].budget, free) { return 0; } + } while self.cur + 1 < self.parts.len() && self.parts[self.cur].bytes + len > self.parts[self.cur].room { self.cur += 1; } self.cur } @@ -239,6 +275,7 @@ pub(crate) mod dev { self.expert(data, ty, rows, cols, scale, evict) } pub fn expert(&mut self, data: &[u8], ty: GgmlType, rows: usize, cols: usize, scale: f32, evict: bool) -> Option { + let group = self.group.take(); self.reclaim(); let k = data.as_ptr() as usize; self.now += 1; @@ -255,7 +292,7 @@ pub(crate) mod dev { // Local patch: all experts of one stacked tensor (a layer's gate_up or down) go to the same GPU, so a // layer's matvecs hit `batch_mats`' single-GPU path instead of two sequential batches with two readbacks. // The GPU with the most free budget used to win per expert, which spread every layer over both cards. - let pref = self.group.take().and_then(|(base, len)| self.affinity(base, len)); + let pref = group.and_then(|(base, len)| self.affinity(base, len)); let room = |p: &Part| (p.bytes + data.len() <= p.budget).then(|| p.budget - p.bytes); let pick = pref.filter(|&d| room(&self.parts[d]).is_some()) .or_else(|| (0..self.parts.len()).filter_map(|d| room(&self.parts[d]).map(|r| (r, d))).max().map(|(_, d)| d)); diff --git a/src/inkling2/forward/device.rs b/src/inkling2/forward/device.rs index 6f5d510e..ce8dbe60 100644 --- a/src/inkling2/forward/device.rs +++ b/src/inkling2/forward/device.rs @@ -1644,7 +1644,14 @@ impl Device { match gpu { Some(tg) => { m.balance(&m.cpu_share, adapt, tg, tc); - let host: Vec = match rem { Some(r) => cpu.iter().zip(&r).map(|(a, b)| a + b).collect(), None => cpu }; + // `cpu` and `r` are per-dimension sums (`run_experts` returns the weighted mix), not per-expert + // weights: both have length `n`, and the elementwise add is the host total. + debug_assert_eq!(cpu.len(), n); + let host: Vec = match rem { + Some(r) => { debug_assert_eq!(r.len(), n); cpu.iter().zip(&r).map(|(a, b)| a + b).collect() } + None => cpu, + }; + debug_assert_eq!(host.len(), n); let wc: Vec = (0..c.n_used).map(|i| list.get(i).map_or(0.0, |e| e.2)).chain(host).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, list.len(), n, s.wc + f(c.n_used)).expect("inkling2 device step"); diff --git a/tests/bench_script.rs b/tests/bench_script.rs new file mode 100644 index 00000000..210f4f51 --- /dev/null +++ b/tests/bench_script.rs @@ -0,0 +1,150 @@ +//! `tools/bench_2x3060.sh`: a row that fails or prints nothing must not end the sweep, the sweep must exit nonzero +//! when a row was lost, and the environment must reach `bench` (`gpu_defaults` sets `STRATA_DS_PLAIN_FIRST=1` only +//! when it is unset, so the script must not unset it). +#![cfg(unix)] + +use std::os::unix::fs::PermissionsExt; +use std::path::PathBuf; + +/// Run the sweep with `--pp 512,2048 --ctx 32768` against `body` as `BIN`; `out` adds `--out`. Returns the temp +/// dir and the output. +fn sweep(tag: &str, body: &str, out: bool) -> (PathBuf, std::process::Output) { + let dir = + std::env::temp_dir().join(format!("strata-bench-script-{}-{tag}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + // `BIN` is checked with `-f` after the script cds to the repo root, so it is a path, not a name on PATH. + let bin = dir.join("fake"); + std::fs::write(&bin, body).unwrap(); + std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap(); + let json = dir.join("out").to_string_lossy().into_owned(); + let mut cmd = std::process::Command::new("bash"); + cmd.arg(concat!( + env!("CARGO_MANIFEST_DIR"), + "/tools/bench_2x3060.sh" + )) + .args(["--pp", "512,2048", "--ctx", "32768"]) + .env("BIN", &bin) + .env("STRATA_INKLING2_MODEL", "/dev/null") + .env("FAKE_LOG", dir.join("calls")) + .env("STRATA_DS_PLAIN_FIRST", "0"); + if out { + cmd.args(["--out", &json]); + } + let out = cmd.output().unwrap(); + (dir, out) +} + +fn report(out: &std::process::Output) -> String { + format!( + "status {}\nstdout:\n{}\nstderr:\n{}", + out.status, + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr) + ) +} + +#[test] +fn a_failed_row_does_not_end_the_sweep() { + let (dir, out) = sweep( + "failed-row", + r#"#!/bin/sh +if echo "$*" | grep -q -- "--pp 512"; then echo boom >&2; exit 1; fi +echo "pp 2048: prefill 100.0 (100.0-100.0) tok/s | tg 32: decode 50.0 (50.0-50.0) tok/s" +echo "${STRATA_DS_PLAIN_FIRST:-unset}" >> "$FAKE_LOG" +"#, + false, + ); + let stdout = String::from_utf8_lossy(&out.stdout); + assert!( + !out.status.success(), + "a sweep with a lost row must exit nonzero: {}", + report(&out) + ); + // The table row of the second prompt: ctx pp prefill decode. + assert!( + stdout + .lines() + .any(|l| l.split_whitespace().eq(["32768", "2048", "100.0", "50.0"])), + "the row after the failure is missing: {}", + report(&out) + ); + assert!( + stdout.lines().any( + |l| l.contains("pp 512") && (l.contains("no result") || l.contains("bench failed")) + ), + "no diagnostic for the failed row: {}", + report(&out) + ); + let calls = std::fs::read_to_string(dir.join("calls")).unwrap_or_default(); + assert!( + !calls.is_empty(), + "the fake bench never ran: {}", + report(&out) + ); + for (i, line) in calls.lines().enumerate() { + assert_eq!( + line, + "0", + "call {} saw STRATA_DS_PLAIN_FIRST={line:?}, so the script unset it: {}", + i + 1, + report(&out) + ); + } + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_row_with_no_output_does_not_end_the_sweep() { + let (dir, out) = sweep("silent-row", "#!/bin/sh\nexit 0\n", false); + let stdout = String::from_utf8_lossy(&out.stdout); + assert!( + !out.status.success(), + "a sweep with no rows must exit nonzero: {}", + report(&out) + ); + let missing = stdout + .lines() + .filter(|l| l.contains("no result") || l.contains("bench failed")) + .count(); + assert_eq!( + missing, + 2, + "both rows must report no result: {}", + report(&out) + ); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_successful_sweep_exits_zero_with_out() { + let (dir, out) = sweep( + "ok-out", + r#"#!/bin/sh +pp="" +prev="" +for a in "$@"; do + [ "$prev" = "--pp" ] && pp="$a" + prev="$a" +done +echo "pp $pp: prefill 100.0 (100.0-100.0) tok/s | tg 32: decode 50.0 (50.0-50.0) tok/s" +"#, + true, + ); + let stdout = String::from_utf8_lossy(&out.stdout); + assert!( + out.status.success(), + "a successful sweep must exit zero: {}", + report(&out) + ); + for pp in ["512", "2048"] { + assert!( + stdout + .lines() + .any(|l| l.split_whitespace().eq(["32768", pp, "100.0", "50.0"])), + "the pp {pp} row is missing: {}", + report(&out) + ); + } + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/tests/kernels.rs b/tests/kernels.rs index 8313ed50..7da87d69 100644 --- a/tests/kernels.rs +++ b/tests/kernels.rs @@ -2675,3 +2675,55 @@ fn ink_prefill_and_batch_match_decode() { assert!(rel_l2(&down::(gpu, &dacc0), &want_sum_null) < 1e-6, "{bk} ink_ffn_sum_n null"); } } + +/// The 16-query prefill entry point is launched with a 16-token grid. When the relative-bias width does not fit its +/// four-query fallback (`nr > 32` or `nr % 4 != 0`), the wrapper must still cover all 16 tokens: one call to the +/// four-query kernel leaves tokens 4..15 of every tile unwritten. `nr=28` is the fast path, `nr=30` the tile fallback +/// and `nr=40` the wide-bias fallback (which also makes decode use the scalar kernel). +#[test] +fn ink_attn_prefill_kp16_fallback_covers_every_query() { + for (bk, gpu) in common::backends() { + let gpu = &*gpu; + // kp16 is the CUDA f16-cache path; Vulkan has its own prefill, and a quantized KV or the measurement knobs + // select another kernel. + if bk != "cuda" + || std::env::var_os("STRATA_KV").is_some() + || std::env::var_os("STRATA_DS_ATTN_OLD").is_some() + || std::env::var_os("STRATA_DS_ATTN_KP4").is_some() { continue; } + for nr in [28usize, 30, 40] { + let (nh, nkv, hd, ext, nt) = (2usize, 1usize, 128usize, 8usize, 20usize); + let q = xs(nt * nh * hd + 3)[3..].to_vec(); + let r = xs(nt * nh * nr + 5)[5..].to_vec(); + let sink = xs(nt * nh + 7)[7..].to_vec(); + let gate = xs(nt * nh * hd + 11)[11..].to_vec(); + let k = xs(nt * nkv * hd + 13)[13..].to_vec(); + let v = xs(nt * nkv * hd + 17)[17..].to_vec(); + let bias = xs(ext * nr + 19)[19..].to_vec(); + let kc: Vec = k.iter().map(|&x| half::f16::from_f32(x).to_bits()).collect(); + let vc: Vec = v.iter().map(|&x| half::f16::from_f32(x).to_bits()).collect(); + let (dq, dr, dsink, dgate) = (up(gpu, &q), up(gpu, &r), up(gpu, &sink), up(gpu, &gate)); + let (dkc, dvc, dbias) = (up(gpu, &kc), up(gpu, &vc), up(gpu, &bias)); + let dout = gpu.zeros::(nt * nh * hd).unwrap(); + gpu.ink_attn_prefill( + dq.addr(), dr.addr(), dsink.addr(), dgate.addr(), dkc.addr(), dvc.addr(), 0, 0, dbias.addr(), dout.addr(), + 0, nt, nh, nkv, hd, nr, ext, nt, 0, + ).unwrap(); + let dsc = gpu.zeros::(nh * nt.div_ceil(64) * (hd + 2)).unwrap(); + let mut want = Vec::with_capacity(nt * nh * hd); + for tok in 0..nt { + let dout1 = gpu.zeros::(nh * hd).unwrap(); + gpu.ink_attn( + dq.addr() + (tok * nh * hd * 4) as u64, + dr.addr() + (tok * nh * nr * 4) as u64, + dsink.addr() + (tok * nh * 4) as u64, + dgate.addr() + (tok * nh * hd * 4) as u64, + dkc.addr(), dvc.addr(), dbias.addr(), dsc.addr(), dout1.addr(), + tok + 1, tok, nh, nkv, hd, nr, ext, + ).unwrap(); + want.extend_from_slice(&down::(gpu, &dout1)); + } + let got = down::(gpu, &dout); + assert!(rel_l2(&got, &want) < 1e-6, "{bk} ink_attn_prefill kp16 fallback nr={nr} nt={nt}"); + } + } +} diff --git a/tools/bench_2x3060.sh b/tools/bench_2x3060.sh index e794af1f..87687e3b 100755 --- a/tools/bench_2x3060.sh +++ b/tools/bench_2x3060.sh @@ -24,30 +24,40 @@ while [ $# -gt 0 ]; do esac done bin=${BIN:-target/release/rustingstrata} +# `bench` turns the plain-weights path on itself (`gpu_defaults` sets STRATA_DS_PLAIN_FIRST=1 when it is unset), so +# the environment is passed through: set STRATA_DS_PLAIN_FIRST=0 here to measure the other path (mat.rs reads "0" as off). # The runtime CUDA libraries the driver ships (cu13 here) come first: an older /usr/local/cuda libnvrtc compiles # the kernels and the forward falls back to the host. export LD_LIBRARY_PATH=$HOME/nvrtc13/lib/python3.11/site-packages/nvidia/cu13/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH} [ -f "$bin" ] || { echo "no $bin (cargo build --release)" >&2; exit 1; } printf '%-8s %-10s %10s %10s\n' ctx pp prefill decode +fail=0 for ctx in $ctx_list; do for pp in ${pp_list//,/ }; do log=$(mktemp) # A fresh process per row: the prefill scratch and the KV are sized by the context, and a second prompt in the # same process reuses them (a different measurement). if [ -n "$out" ]; then - env -u STRATA_DS_PLAIN_FIRST STRATA_DS_KV_TOKENS="$ctx" STRATA_DS_PF_TOKENS=512 \ + if ! env STRATA_DS_KV_TOKENS="$ctx" STRATA_DS_PF_TOKENS=512 \ "$bin" bench --model "$model" --pp "$pp" --tg "$tg" --reps 1 --ctx "$ctx" --device 0,1 --gpu \ - --json-out "$out-$ctx-$pp.json" >"$log" 2>&1 + --json-out "$out-$ctx-$pp.json" >"$log" 2>&1; then + echo "ctx $ctx pp $pp: no result"; sed -n '1,20p' "$log"; rm -f "$log"; fail=$((fail+1)); continue + fi else - env -u STRATA_DS_PLAIN_FIRST STRATA_DS_KV_TOKENS="$ctx" STRATA_DS_PF_TOKENS=512 \ + if ! env STRATA_DS_KV_TOKENS="$ctx" STRATA_DS_PF_TOKENS=512 \ "$bin" bench --model "$model" --pp "$pp" --tg "$tg" --reps 1 --ctx "$ctx" --device 0,1 --gpu \ - >"$log" 2>&1 + >"$log" 2>&1; then + echo "ctx $ctx pp $pp: no result"; sed -n '1,20p' "$log"; rm -f "$log"; fail=$((fail+1)); continue + fi + fi + row=$(grep -E '^pp ' "$log" | tail -1 || true) + if [ -z "$row" ]; then + echo "ctx $ctx pp $pp: no result"; sed -n '1,20p' "$log"; rm -f "$log"; fail=$((fail+1)); continue fi - row=$(grep -E '^pp ' "$log" | tail -1) - [ -n "$row" ] || { echo "ctx $ctx pp $pp: no result"; sed -n '1,20p' "$log"; rm -f "$log"; continue; } # `pp 512: prefill V (...) tok/s | tg 32: decode D (...) tok/s`. printf '%-8s %-10s %10s %10s\n' "$ctx" "$pp" "$(awk '{print $4}' <<<"$row")" "$(awk '{print $11}' <<<"$row")" grep -E '^inkling2: preloaded' "$log" | sed 's/^inkling2: / /' || true rm -f "$log" done done +[ "$fail" -eq 0 ] || exit 1 diff --git a/tools/kld_compare.py b/tools/kld_compare.py index 6f49d45f..fb07e40a 100644 --- a/tools/kld_compare.py +++ b/tools/kld_compare.py @@ -45,6 +45,17 @@ def rows(f, n, nv, nch): yield c, i, scale, offset, q +def same_bytes(a, b, chunk=1 << 20): + """Compare two files in chunks, without holding either one in memory.""" + with open(a, "rb") as fa, open(b, "rb") as fb: + while True: + x, y = fa.read(chunk), fb.read(chunk) + if x != y: + return False + if not x: + return True + + def main(): ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("base") @@ -62,9 +73,7 @@ def main(): first = na // 2 per = na - 1 - first - same = fa.read() == fb.read() - fa.seek(0), fb.seek(0) - header(fa), header(fb) + same = same_bytes(a.base, a.new) klds, top1, cells, moved, worst, nll_a, nll_b = [], 0, 0, 0, 0.0, 0.0, 0.0 for (c, i, sa, oa, qa), (_, _, sb, ob, qb) in zip(rows(fa, na, nva, ncha), rows(fb, nb, nvb, nchb)): diff --git a/tools/test_kld_compare.py b/tools/test_kld_compare.py new file mode 100644 index 00000000..4fbc2fd9 --- /dev/null +++ b/tools/test_kld_compare.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python3 +"""Tests for kld_compare.py's streaming file comparison. + + python3 tools/test_kld_compare.py +""" + +import os +import tempfile +import unittest + +from kld_compare import same_bytes + + +def blob(n): + """Deterministic n bytes.""" + return (bytes(range(256)) * (n // 256 + 1))[:n] + + +class SameBytesTest(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + + def path(self, name): + return os.path.join(self.tmp.name, name) + + def write(self, name, data): + p = self.path(name) + with open(p, "wb") as f: + f.write(data) + return p + + def test_equal_across_chunks(self): + # More than one 1 MiB chunk, so the loop reads past the first one. + data = blob(2 * (1 << 20) + 12345) + a = self.write("a.bin", data) + b = self.write("b.bin", data) + self.assertTrue(same_bytes(a, b)) + + def test_differing_byte_in_second_chunk(self): + data = blob(2 * (1 << 20) + 12345) + off = (1 << 20) + 7 + changed = bytearray(data) + changed[off] ^= 0xFF + a = self.write("a.bin", data) + b = self.write("b.bin", bytes(changed)) + self.assertFalse(same_bytes(a, b)) + + def test_different_lengths(self): + data = blob(2 * (1 << 20) + 12345) + a = self.write("a.bin", data) + # One extra trailing byte: equal up to the shorter file's end. + b = self.write("b.bin", data + b"x") + self.assertFalse(same_bytes(a, b)) + self.assertFalse(same_bytes(b, a)) + # A strict prefix, so the last read of the shorter file is non-empty but short. + c = self.write("c.bin", data[:-1]) + self.assertFalse(same_bytes(a, c)) + self.assertFalse(same_bytes(c, a)) + + +if __name__ == "__main__": + unittest.main()