From e0d652c30d7b7c7ab7281c514d9febe80af61b53 Mon Sep 17 00:00:00 2001 From: sayampy Date: Tue, 24 Nov 2026 03:39:09 +0530 Subject: [PATCH 001/515] bench: record MTP draft acceptance in the JSON record --- src/main.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/main.rs b/src/main.rs index 39820459..30f8ee18 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1337,7 +1337,10 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { reps, }; let unix_time = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).map_or(0, |d| d.as_secs()); - let record = bench_record(&meta, &results, r.expert_summary().as_ref(), unix_time); + let mut record = bench_record(&meta, &results, r.expert_summary().as_ref(), unix_time); + // The arch-specific benchners print this; putting it in the JSON too gives tools one reliable source. + let drafts = if let Runner::Gpu(g) = &r { g.drafts } else { (0, 0) }; + record["drafts"] = json!({"made": drafts.0, "accepted": drafts.1}); let mut line = serde_json::to_string(&record)?; line.push('\n'); std::fs::write(&path, line).with_context(|| format!("writing the JSON record to {}", path.display()))?; From 874524deb898faefd24f8f42da38969efb09b2a4 Mon Sep 17 00:00:00 2001 From: Volt Date: Mon, 23 Nov 2026 23:13:44 +0100 Subject: [PATCH 002/515] inkling2: support mainline llama.cpp DSpark GGUF schema (markov_w2, ctx_mix, per-slot mask_embd) --- src/inkling2/dspark.rs | 160 ++++++++++++++++++++++++++------- src/inkling2/forward.rs | 27 ++++++ src/inkling2/forward/device.rs | 23 +++++ 3 files changed, 176 insertions(+), 34 deletions(-) diff --git a/src/inkling2/dspark.rs b/src/inkling2/dspark.rs index 1d184c8a..85e7b0a1 100644 --- a/src/inkling2/dspark.rs +++ b/src/inkling2/dspark.rs @@ -37,6 +37,13 @@ struct DsparkLayer { ffn_down: Mat<'static>, } +enum MarkovHead { + /// Legacy Unsloth DSpark: projects `latent` (`[rank]`) to hidden space (`[n_embd]`), adds `h_row`, then runs target LM head. + HiddenOut { weight: Mat<'static>, bias: Vec }, + /// Mainline llama.cpp DSpark: adds low-rank logit delta `markov_w2 @ latent + bias` onto batched target LM head logits. + Logits { w2: Mat<'static>, bias: Vec }, +} + pub struct DsparkDrafter { pub n_layer: usize, pub n_embd: usize, @@ -52,13 +59,13 @@ pub struct DsparkDrafter { pub target_layers: [usize; 4], fuse: Vec, dspark_norm: Vec, + token_embd_norm: Option>, mask_embd: Vec, output_norm: Vec, markov_w1: Mat<'static>, joint_proj: Mat<'static>, joint_proj_b: Vec, - hidden_out: Mat<'static>, - hidden_out_b: Vec, + markov_head: MarkovHead, layers: Vec, k_cache: Vec>, v_cache: Vec>, @@ -122,24 +129,61 @@ impl DsparkDrafter { let markov_w1 = host_mat(g_ref, "markov_w1.weight")?; let rank = markov_w1.cols; - let fuse = f32s(g_ref, "dspark_fuse.weight")?; - ensure!(fuse.len() == 4 * (n_layer + 1), "dspark_fuse.weight len {} != {}", fuse.len(), 4 * (n_layer + 1)); - let dspark_norm = f32s(g_ref, "dspark_norm.weight")?; + let fuse = if g_ref.tensors.contains_key("dspark_fuse.weight") { + let f = f32s(g_ref, "dspark_fuse.weight")?; + ensure!(f.len() == 4 * (n_layer + 1), "dspark_fuse.weight len {} != {}", f.len(), 4 * (n_layer + 1)); + f + } else { + let mut f = Vec::with_capacity(4 * (n_layer + 1)); + for il in 0..n_layer { + let row = f32s(g_ref, &format!("blk.{il}.ctx_mix.weight"))?; + ensure!(row.len() == 4, "blk.{il}.ctx_mix.weight len {} != 4", row.len()); + f.extend_from_slice(&row); + } + let row = f32s(g_ref, "markov_ctx_mix.weight")?; + ensure!(row.len() == 4, "markov_ctx_mix.weight len {} != 4", row.len()); + f.extend_from_slice(&row); + f + }; + let dspark_norm = if g_ref.tensors.contains_key("dspark_norm.weight") { + f32s(g_ref, "dspark_norm.weight")? + } else { + f32s(g_ref, "markov_ctx_norm.weight")? + }; + let token_embd_norm = if g_ref.tensors.contains_key("token_embd_norm.weight") { + Some(f32s(g_ref, "token_embd_norm.weight")?) + } else { + None + }; let mask_embd = f32s(g_ref, "mask_embd.weight")?; let output_norm = f32s(g_ref, "output_norm.weight")?; let joint_proj = host_mat(g_ref, "joint_proj.weight")?; let joint_proj_b = f32s(g_ref, "joint_proj.bias")?; - let hidden_out = host_mat(g_ref, "dspark_hidden_out.weight")?; - let hidden_out_b = f32s(g_ref, "dspark_hidden_out.bias")?; + let markov_head = if g_ref.tensors.contains_key("markov_w2.weight") { + MarkovHead::Logits { + w2: host_mat(g_ref, "markov_w2.weight")?, + bias: f32s(g_ref, "markov_w2.bias")?, + } + } else { + MarkovHead::HiddenOut { + weight: host_mat(g_ref, "dspark_hidden_out.weight")?, + bias: f32s(g_ref, "dspark_hidden_out.bias")?, + } + }; let mut layers = Vec::with_capacity(n_layer); for il in 0..n_layer { let p = |s: &str| format!("blk.{il}.{s}"); let m = |s: &str| Mat::load(g_ref, &p(s)); let v = |s: &str| f32s(g_ref, &p(s)); + let dflare_norm = if g_ref.tensors.contains_key(&p("dflare_norm.weight")) { + v("dflare_norm.weight")? + } else { + v("ctx_norm.weight")? + }; layers.push(DsparkLayer { swa: swa[il], - dflare_norm: v("dflare_norm.weight")?, + dflare_norm, attn_k_ctx: m("attn_k_ctx.weight")?, attn_v_ctx: m("attn_v_ctx.weight")?, attn_k_ctx_norm: v("attn_k_ctx_norm.weight")?, @@ -172,13 +216,13 @@ impl DsparkDrafter { target_layers, fuse, dspark_norm, + token_embd_norm, mask_embd, output_norm, markov_w1, joint_proj, joint_proj_b, - hidden_out, - hidden_out_b, + markov_head, layers, k_cache: vec![Vec::new(); n_layer], v_cache: vec![Vec::new(); n_layer], @@ -270,9 +314,17 @@ impl DsparkDrafter { // 1. Build 8-token input: slot 0 is normed target token embedding of `anchor_tok`, slots 1..8 are `mask_embd`. let mut inp = vec![0.0f32; bs * n]; - target.embed_normed(anchor_tok, &mut inp[..n]); + if let Some(norm_w) = &self.token_embd_norm { + let mut emb = vec![0.0f32; n]; + target.embed_raw(anchor_tok, &mut emb); + rms_norm_w(&emb, norm_w, self.eps, &mut inp[..n]); + } else { + target.embed_normed(anchor_tok, &mut inp[..n]); + } + let per_pos_mask = self.mask_embd.len() >= (bs - 1) * n; for i in 1..bs { - inp[i * n..(i + 1) * n].copy_from_slice(&self.mask_embd); + let src = if per_pos_mask { &self.mask_embd[(i - 1) * n..i * n] } else { &self.mask_embd[..n] }; + inp[i * n..(i + 1) * n].copy_from_slice(src); } // 2. Run the 3 non-causal DSpark transformer layers over the 8-token block. @@ -372,34 +424,74 @@ impl DsparkDrafter { joint_in[2 * r + n..].copy_from_slice(ctx_feat); let mut joint = vec![0.0f32; 3 * r]; let mut latent = vec![0.0f32; r]; - let mut corr = vec![0.0f32; n]; let mut prev = anchor_tok; let mut drafts = Vec::with_capacity(count); - for step in 0..count { - let h_row = &hidden[(step + 1) * n..(step + 2) * n]; - self.markov_w1.row_into(prev as usize, &mut prev_embd); - joint_in[..r].copy_from_slice(&state); - joint_in[r..2 * r].copy_from_slice(&prev_embd); - joint_in[2 * r..2 * r + n].copy_from_slice(h_row); - - self.joint_proj.matvec(&joint_in, &mut joint); - for (v, &b) in joint.iter_mut().zip(&self.joint_proj_b) { *v += b; } - - for k in 0..r { - let gate = crate::ops::sigmoid(joint[k]); - let cand = joint[r + k].tanh(); - state[k] = cand + gate * (state[k] - cand); - latent[k] = joint[2 * r + k].tanh(); - } + match &self.markov_head { + MarkovHead::HiddenOut { weight, bias } => { + let mut corr = vec![0.0f32; n]; + for step in 0..count { + let h_row = &hidden[(step + 1) * n..(step + 2) * n]; + self.markov_w1.row_into(prev as usize, &mut prev_embd); + joint_in[..r].copy_from_slice(&state); + joint_in[r..2 * r].copy_from_slice(&prev_embd); + joint_in[2 * r..2 * r + n].copy_from_slice(h_row); + + self.joint_proj.matvec(&joint_in, &mut joint); + for (v, &b) in joint.iter_mut().zip(&self.joint_proj_b) { *v += b; } - self.hidden_out.matvec(&latent, &mut corr); - for ((c, &b), &h_v) in corr.iter_mut().zip(&self.hidden_out_b).zip(h_row) { - *c = *c + b + h_v; + for k in 0..r { + let gate = crate::ops::sigmoid(joint[k]); + let cand = joint[r + k].tanh(); + state[k] = cand + gate * (state[k] - cand); + latent[k] = joint[2 * r + k].tanh(); + } + + weight.matvec(&latent, &mut corr); + for ((c, &b), &h_v) in corr.iter_mut().zip(bias).zip(h_row) { + *c = *c + b + h_v; + } + + prev = target.lm_head_argmax(&corr); + drafts.push(prev); + } } + MarkovHead::Logits { w2, bias } => { + let n_vocab = target.cfg.n_vocab; + let base_logits = target.lm_head_batch(&hidden[n..(1 + count) * n], count); + let mut delta = vec![0.0f32; w2.rows]; + for step in 0..count { + let h_row = &hidden[(step + 1) * n..(step + 2) * n]; + self.markov_w1.row_into(prev as usize, &mut prev_embd); + joint_in[..r].copy_from_slice(&state); + joint_in[r..2 * r].copy_from_slice(&prev_embd); + joint_in[2 * r..2 * r + n].copy_from_slice(h_row); + + self.joint_proj.matvec(&joint_in, &mut joint); + for (v, &b) in joint.iter_mut().zip(&self.joint_proj_b) { *v += b; } - prev = target.lm_head_argmax(&corr); - drafts.push(prev); + for k in 0..r { + let gate = crate::ops::sigmoid(joint[k]); + let cand = joint[r + k].tanh(); + state[k] = cand + gate * (state[k] - cand); + latent[k] = joint[2 * r + k].tanh(); + } + + w2.matvec(&latent, &mut delta); + let base = &base_logits[step * n_vocab..(step + 1) * n_vocab]; + let nv = n_vocab.min(w2.rows).min(bias.len()); + let (mut best_i, mut best_v) = (0usize, f32::NEG_INFINITY); + for i in 0..nv { + let v = base[i] + delta[i] + bias[i]; + if v > best_v { + best_v = v; + best_i = i; + } + } + prev = best_i as u32; + drafts.push(prev); + } + } } drafts } diff --git a/src/inkling2/forward.rs b/src/inkling2/forward.rs index 5ad7bc7c..e8d18af6 100644 --- a/src/inkling2/forward.rs +++ b/src/inkling2/forward.rs @@ -577,6 +577,11 @@ impl<'a> Inkling2Model<'a> { } /// Look up `tok` in `tok_embd` and RMS-normalize with `tok_norm` (`cfg.eps`), writing `out` (`[n_embd]`). + pub fn embed_raw(&self, tok: u32, out: &mut [f32]) { + assert!((tok as usize) < self.tok_embd.rows, "token {tok} is outside the vocabulary"); + self.tok_embd.row_into(tok as usize, out); + } + pub fn embed_normed(&self, tok: u32, out: &mut [f32]) { assert!((tok as usize) < self.tok_embd.rows, "token {tok} is outside the vocabulary"); let mut emb = vec![0.0f32; self.cfg.n_embd]; @@ -584,6 +589,28 @@ impl<'a> Inkling2Model<'a> { rms_norm_w(&emb, &self.tok_norm, self.cfg.eps, out); } + /// Project `nt` hidden states (`[nt, n_embd]`) through the target LM head (`output.weight`) and return + /// `[nt, cfg.n_vocab]` logits before softcap. + pub fn lm_head_batch(&mut self, h_rows: &[f32], nt: usize) -> Vec { + if let Some(mut d) = self.device.take() { + let res = d.lm_head_batch(self, h_rows, nt); + self.device = Some(d); + if let Ok(v) = res { + return v; + } + } + let rows: Vec<&[f32]> = h_rows.chunks_exact(self.cfg.n_embd).take(nt).collect(); + let raw = matvec_rows(&self.output, &rows); + if self.output.rows == self.cfg.n_vocab { + return raw; + } + let mut out = Vec::with_capacity(nt * self.cfg.n_vocab); + for row in raw.chunks_exact(self.output.rows) { + out.extend_from_slice(&row[..self.cfg.n_vocab]); + } + out + } + /// Project a single hidden state `h` (`[n_embd]`) through the target LM head (`output.weight`) and return the /// greedy argmax token ID (`0..cfg.n_vocab`) of the logits before the softcap. For drafts. pub fn lm_head_argmax(&self, h: &[f32]) -> u32 { diff --git a/src/inkling2/forward/device.rs b/src/inkling2/forward/device.rs index d3787ab4..94677671 100644 --- a/src/inkling2/forward/device.rs +++ b/src/inkling2/forward/device.rs @@ -688,6 +688,29 @@ impl Device { Ok(id) } + /// Project `nt` hidden vectors (`[nt, n_embd]`) through the target's LM head on GPU in one batched matvec + /// and return `[nt, c.n_vocab]` logits (before softcap). + pub(super) fn lm_head_batch(&mut self, m: &Inkling2Model, h_rows: &[f32], nt: usize) -> Result> { + let c = &m.cfg; + let vrows = m.output.rows; + let d = dev::get().unwrap().lock().unwrap(); + let be = &*d.parts[0].be; + self.ensure_pf(be, c, vrows, nt)?; + let pf = self.pf.as_ref().unwrap(); + let o = pf.buf.addr(); + be.put(h_rows, &pf.buf, ((pf.p.hn - o) / 4) as usize)?; + be.gemvq(d.tensor(m.output.gpu.unwrap()), pf.p.hn, c.n_embd, 0, pf.logits_buf.addr(), vrows, nt)?; + let raw = be.get::(&pf.logits_buf, 0, nt * vrows)?; + if vrows == c.n_vocab { + return Ok(raw); + } + let mut out = Vec::with_capacity(nt * c.n_vocab); + for row in raw.chunks_exact(vrows) { + out.extend_from_slice(&row[..c.n_vocab]); + } + Ok(out) + } + fn record_dspark_visit(&self, visit: usize, cur_a: u64, nt: usize, n: usize) -> Result<()> { let Some(k) = DSPARK_VISITS.iter().position(|&v| v == visit) else { return Ok(()) }; let d = dev::get().unwrap().lock().unwrap(); From 64ded698e2cfe7ff06366a5fccdaff0539f6f6be Mon Sep 17 00:00:00 2001 From: Volt Date: Mon, 23 Nov 2026 23:22:44 +0100 Subject: [PATCH 003/515] inkling2: run mainline DSpark markov_w2 + logit argmax on GPU --- src/inkling2/dspark.rs | 115 ++++++++++++++++++++++++--------- src/inkling2/forward.rs | 19 ++++++ src/inkling2/forward/device.rs | 38 ++++++++++- 3 files changed, 139 insertions(+), 33 deletions(-) diff --git a/src/inkling2/dspark.rs b/src/inkling2/dspark.rs index 85e7b0a1..5a336083 100644 --- a/src/inkling2/dspark.rs +++ b/src/inkling2/dspark.rs @@ -37,11 +37,16 @@ struct DsparkLayer { ffn_down: Mat<'static>, } +struct MarkovW2Gpu { + w2: crate::backend::GpuTensor, + bias: crate::backend::Buf, +} + enum MarkovHead { /// Legacy Unsloth DSpark: projects `latent` (`[rank]`) to hidden space (`[n_embd]`), adds `h_row`, then runs target LM head. HiddenOut { weight: Mat<'static>, bias: Vec }, /// Mainline llama.cpp DSpark: adds low-rank logit delta `markov_w2 @ latent + bias` onto batched target LM head logits. - Logits { w2: Mat<'static>, bias: Vec }, + Logits { w2: Mat<'static>, bias: Vec, gpu: std::sync::OnceLock> }, } pub struct DsparkDrafter { @@ -163,6 +168,7 @@ impl DsparkDrafter { MarkovHead::Logits { w2: host_mat(g_ref, "markov_w2.weight")?, bias: f32s(g_ref, "markov_w2.bias")?, + gpu: std::sync::OnceLock::new(), } } else { MarkovHead::HiddenOut { @@ -456,40 +462,89 @@ impl DsparkDrafter { drafts.push(prev); } } - MarkovHead::Logits { w2, bias } => { - let n_vocab = target.cfg.n_vocab; - let base_logits = target.lm_head_batch(&hidden[n..(1 + count) * n], count); - let mut delta = vec![0.0f32; w2.rows]; - for step in 0..count { - let h_row = &hidden[(step + 1) * n..(step + 2) * n]; - self.markov_w1.row_into(prev as usize, &mut prev_embd); - joint_in[..r].copy_from_slice(&state); - joint_in[r..2 * r].copy_from_slice(&prev_embd); - joint_in[2 * r..2 * r + n].copy_from_slice(h_row); - - self.joint_proj.matvec(&joint_in, &mut joint); - for (v, &b) in joint.iter_mut().zip(&self.joint_proj_b) { *v += b; } + MarkovHead::Logits { w2, bias, gpu } => { + let gpu_w2 = gpu.get_or_init(|| { + if w2.rows > target.output_rows() || w2.cols > n { + return None; + } + let dm = crate::deepseek::mat::dev::get()?; + let d = dm.lock().ok()?; + let be = &*d.parts[0].be; + let w2_gpu = be.upload(&crate::weights::Tensor { + ty: w2.ty, + rows: w2.rows, + cols: w2.cols, + data: w2.data, + scale: w2.scale, + }).ok()?; + let bias_buf = be.alloc(bias.len() * 4).ok()?; + be.put(bias, &bias_buf, 0).ok()?; + Some(MarkovW2Gpu { w2: w2_gpu, bias: bias_buf }) + }); + let use_gpu = gpu_w2.is_some() + && target.lm_head_batch_gpu(&hidden[n..(1 + count) * n], count); + if use_gpu { + let g = gpu_w2.as_ref().unwrap(); + let bias_addr = g.bias.addr(); + for step in 0..count { + let h_row = &hidden[(step + 1) * n..(step + 2) * n]; + self.markov_w1.row_into(prev as usize, &mut prev_embd); + joint_in[..r].copy_from_slice(&state); + joint_in[r..2 * r].copy_from_slice(&prev_embd); + joint_in[2 * r..2 * r + n].copy_from_slice(h_row); + + self.joint_proj.matvec(&joint_in, &mut joint); + for (v, &b) in joint.iter_mut().zip(&self.joint_proj_b) { *v += b; } + + for k in 0..r { + let gate = crate::ops::sigmoid(joint[k]); + let cand = joint[r + k].tanh(); + state[k] = cand + gate * (state[k] - cand); + latent[k] = joint[2 * r + k].tanh(); + } - for k in 0..r { - let gate = crate::ops::sigmoid(joint[k]); - let cand = joint[r + k].tanh(); - state[k] = cand + gate * (state[k] - cand); - latent[k] = joint[2 * r + k].tanh(); + if let Some(id) = target.markov_w2_argmax_gpu(&g.w2, bias_addr, &latent, step) { + prev = id; + drafts.push(prev); + } else { + break; + } } + } else { + let n_vocab = target.cfg.n_vocab; + let base_logits = target.lm_head_batch(&hidden[n..(1 + count) * n], count); + let mut delta = vec![0.0f32; w2.rows]; + for step in 0..count { + let h_row = &hidden[(step + 1) * n..(step + 2) * n]; + self.markov_w1.row_into(prev as usize, &mut prev_embd); + joint_in[..r].copy_from_slice(&state); + joint_in[r..2 * r].copy_from_slice(&prev_embd); + joint_in[2 * r..2 * r + n].copy_from_slice(h_row); + + self.joint_proj.matvec(&joint_in, &mut joint); + for (v, &b) in joint.iter_mut().zip(&self.joint_proj_b) { *v += b; } + + for k in 0..r { + let gate = crate::ops::sigmoid(joint[k]); + let cand = joint[r + k].tanh(); + state[k] = cand + gate * (state[k] - cand); + latent[k] = joint[2 * r + k].tanh(); + } - w2.matvec(&latent, &mut delta); - let base = &base_logits[step * n_vocab..(step + 1) * n_vocab]; - let nv = n_vocab.min(w2.rows).min(bias.len()); - let (mut best_i, mut best_v) = (0usize, f32::NEG_INFINITY); - for i in 0..nv { - let v = base[i] + delta[i] + bias[i]; - if v > best_v { - best_v = v; - best_i = i; + w2.matvec(&latent, &mut delta); + let base = &base_logits[step * n_vocab..(step + 1) * n_vocab]; + let nv = n_vocab.min(w2.rows).min(bias.len()); + let (mut best_i, mut best_v) = (0usize, f32::NEG_INFINITY); + for i in 0..nv { + let v = base[i] + delta[i] + bias[i]; + if v > best_v { + best_v = v; + best_i = i; + } } + prev = best_i as u32; + drafts.push(prev); } - prev = best_i as u32; - drafts.push(prev); } } } diff --git a/src/inkling2/forward.rs b/src/inkling2/forward.rs index e8d18af6..c4c4954f 100644 --- a/src/inkling2/forward.rs +++ b/src/inkling2/forward.rs @@ -589,6 +589,25 @@ impl<'a> Inkling2Model<'a> { rms_norm_w(&emb, &self.tok_norm, self.cfg.eps, out); } + /// Project `nt` hidden states (`[nt, n_embd]`) through the target LM head on GPU, keeping the logits on device. + pub(super) fn lm_head_batch_gpu(&mut self, h_rows: &[f32], nt: usize) -> bool { + if let Some(mut d) = self.device.take() { + let ok = d.lm_head_batch_gpu(self, h_rows, nt).is_ok(); + self.device = Some(d); + return ok; + } + false + } + + /// Add `w2 @ latent + bias` onto `pf.logits_buf[step]` on GPU and return the argmax token ID. + pub(super) fn markov_w2_argmax_gpu( + &self, w2: &crate::backend::GpuTensor, bias_addr: u64, latent: &[f32], step: usize, + ) -> Option { + self.device.as_ref()?.markov_w2_argmax_gpu(self, w2, bias_addr, latent, step).ok() + } + + pub(super) fn output_rows(&self) -> usize { self.output.rows } + /// Project `nt` hidden states (`[nt, n_embd]`) through the target LM head (`output.weight`) and return /// `[nt, cfg.n_vocab]` logits before softcap. pub fn lm_head_batch(&mut self, h_rows: &[f32], nt: usize) -> Vec { diff --git a/src/inkling2/forward/device.rs b/src/inkling2/forward/device.rs index 94677671..061dbb65 100644 --- a/src/inkling2/forward/device.rs +++ b/src/inkling2/forward/device.rs @@ -688,9 +688,9 @@ impl Device { Ok(id) } - /// Project `nt` hidden vectors (`[nt, n_embd]`) through the target's LM head on GPU in one batched matvec - /// and return `[nt, c.n_vocab]` logits (before softcap). - pub(super) fn lm_head_batch(&mut self, m: &Inkling2Model, h_rows: &[f32], nt: usize) -> Result> { + /// Project `nt` hidden vectors (`[nt, n_embd]`) through the target's LM head on GPU into `pf.logits_buf` + /// (`[nt, m.output.rows]`), keeping the logits on device for `markov_w2_argmax_gpu`. + pub(super) fn lm_head_batch_gpu(&mut self, m: &Inkling2Model, h_rows: &[f32], nt: usize) -> Result<()> { let c = &m.cfg; let vrows = m.output.rows; let d = dev::get().unwrap().lock().unwrap(); @@ -700,6 +700,38 @@ impl Device { let o = pf.buf.addr(); be.put(h_rows, &pf.buf, ((pf.p.hn - o) / 4) as usize)?; be.gemvq(d.tensor(m.output.gpu.unwrap()), pf.p.hn, c.n_embd, 0, pf.logits_buf.addr(), vrows, nt)?; + Ok(()) + } + + /// Add low-rank `w2 @ latent + bias` onto `pf.logits_buf[step]` on GPU and return the argmax token ID. + pub(super) fn markov_w2_argmax_gpu( + &self, m: &Inkling2Model, w2: &crate::backend::GpuTensor, bias_addr: u64, latent: &[f32], step: usize, + ) -> Result { + let c = &m.cfg; + let vrows = m.output.rows; + let nv = c.n_vocab.min(w2.rows); + let pf = self.pf.as_ref().context("lm_head_batch_gpu not called")?; + let (s, o) = (self.s, self.scr.addr()); + let d = dev::get().unwrap().lock().unwrap(); + let be = &*d.parts[0].be; + be.put(latent, &self.scr, ((s.hn - o) / 4) as usize)?; + be.gemvq(w2, s.hn, w2.cols, 0, s.logits, w2.rows, 1)?; + be.add(s.logits, pf.logits_buf.addr() + (step * vrows * 4) as u64, nv)?; + be.add(s.logits, bias_addr, nv)?; + be.argmax_rows(s.logits, nv, 1, s.amax)?; + let id = be.get::(&self.scr, ((s.amax - o) / 4) as usize, 1)?[0] as u32; + Ok(id) + } + + /// Project `nt` hidden vectors (`[nt, n_embd]`) through the target's LM head on GPU in one batched matvec + /// and return `[nt, c.n_vocab]` logits (before softcap). + pub(super) fn lm_head_batch(&mut self, m: &Inkling2Model, h_rows: &[f32], nt: usize) -> Result> { + let c = &m.cfg; + let vrows = m.output.rows; + self.lm_head_batch_gpu(m, h_rows, nt)?; + let d = dev::get().unwrap().lock().unwrap(); + let be = &*d.parts[0].be; + let pf = self.pf.as_ref().unwrap(); let raw = be.get::(&pf.logits_buf, 0, nt * vrows)?; if vrows == c.n_vocab { return Ok(raw); From a2660463fbe61e5d88eb9c495e50d91bfd7c267b Mon Sep 17 00:00:00 2001 From: Hannes Klas Date: Mon, 16 Nov 2026 12:35:18 +0100 Subject: [PATCH 004/515] hip: ROCm backend for the same kernels, brought up on Qwen3.6-35B-A3B Compiles src/cuda/kernels.cu at run time with hiprtc for the card's gfx target and launches it through libamdhip64, both loaded by name (no ROCm headers, no hipcc, no C++ build step). Usage: --backend hip. Device side: src/hip/compat.h is prepended to the source and supplies the CUDA intrinsics it uses (__shfl_*_sync, __ballot_sync, __dp4a, __byte_perm, __vsub4/__vadd4, f16 conversions, __nanosleep, __trap) from HIP, with __CUDA_ARCH__ at the pre-Volta level so the source takes its portable paths (per-lane shared loads, plain copies, CUDA-core multiplicands). Kernels run as wave32, the assumption the source makes. kernels.cu keeps one source for both backends; the five places that cannot be shared are behind STRATA_HIP, so the CUDA build's preprocessed source is unchanged. Host side: src/hip/{mod,ffi}.rs implement the same Backend trait as src/cuda, including the code-object cache, the shared-memory ceiling (head_dim 256 prefill attention drops to a 16-key tile on RDNA's 64 KiB blocks), the MTP and prompt paths and the expert cache. Verified on RX 9070 XT (gfx1201, ROCm 7.2.3) with Qwen3.6-35B-A3B UD-Q4_K_XL: greedy output identical to the Vulkan backend on three prompts, decode 159 tok/s (--mtp 2) vs 232 for Vulkan, prefill 492 vs 1458 tok/s (matrix cores are the next step; docs/HIP.md). --- README.md | 5 +- THANKS.md | 5 + docs/HIP.md | 66 ++++ src/backend.rs | 7 +- src/cuda/kernels.cu | 35 +- src/cuda/mod.rs | 26 +- src/hip/compat.h | 104 ++++++ src/hip/ffi.rs | 341 ++++++++++++++++++ src/hip/mod.rs | 854 ++++++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 1 + 10 files changed, 1425 insertions(+), 19 deletions(-) create mode 100644 docs/HIP.md create mode 100644 src/hip/compat.h create mode 100644 src/hip/ffi.rs create mode 100644 src/hip/mod.rs diff --git a/README.md b/README.md index 7870f08f..c55f7e73 100644 --- a/README.md +++ b/README.md @@ -63,8 +63,11 @@ Needs Rust (2024 edition) and one of: under `%CUDA_PATH%\bin`); `STRATA_NVRTC` names another file. Without it the run falls back to Vulkan. - a Vulkan 1.3 driver with shaderFloat64, int8/16/64 and subgroup size 32 or a fixed 64 (tested on RTX 3060, Radeon VII and V100; Intel Arc lacks shaderFloat64). +- for `--backend hip`: a ROCm runtime with hiprtc (`libamdhip64.so`, `libhiprtc.so`), also loaded at run time; the + kernels are compiled for the card's `gfx` target on first use. Experimental — status, numbers and limits are in + [docs/HIP.md](docs/HIP.md). -`--gpu` picks CUDA when it loads, else Vulkan; `--backend` chooses. The first CUDA run compiles the kernels (~15 s) and +`--gpu` picks CUDA when it loads, else Vulkan; `--backend` chooses (`cuda`, `vulkan` or `hip`). The first CUDA run compiles the kernels (~15 s) and caches them. Every GPU tried so far is in [docs/SUPPORTED_GPUS.md](docs/SUPPORTED_GPUS.md); AMD notes are in [docs/AMD.md](docs/AMD.md). diff --git a/THANKS.md b/THANKS.md index a4dba549..6c9de5b5 100644 --- a/THANKS.md +++ b/THANKS.md @@ -15,6 +15,11 @@ told us what they need. Thank you all. - [SugiKi1996](https://github.com/SugiKi1996): found that Turing (sm_75) was rejected on NVRTC 13.x, with the fix and RTX 2080 Ti numbers (issue #17). +## Code + +- [Niko1221](https://github.com/Niko1221/Strata): the HIP backend's device-side compatibility layer (`src/hip/compat.h`) + follows the structure and several implementations of Strata's `include/strata/hip_compat/intrinsics.hpp` (MIT). + ## Ideas - [FredWalter](https://github.com/FredWalter): multi-GPU and Qwen3.8-Flash-Next support (issue #1). diff --git a/docs/HIP.md b/docs/HIP.md new file mode 100644 index 00000000..d237139f --- /dev/null +++ b/docs/HIP.md @@ -0,0 +1,66 @@ +# HIP (ROCm) backend + +`--backend hip` runs the same `src/cuda/kernels.cu` on an AMD card through HIP, without `hipcc`, ROCm headers or a C++ +build step: the kernels are compiled at run time by hiprtc and launched through the HIP runtime, both loaded by name +(`libamdhip64.so`, `libhiprtc.so`), the way `src/cuda` loads NVRTC. `cargo build --release` is the whole build. + +**Status: experimental.** Brought up on Qwen3.6-35B-A3B (RX 9070 XT, gfx1201, ROCm 7.2). Greedy output is identical to +the Vulkan backend on the prompts tried. Not yet ported: matrix cores (prefill runs the f16 CUDA-core path, not WMMA), +graph capture (off by default), and the host-side pipeline details of the CUDA backend (ring staging, side stream). + +## What runs + +Everything the Vulkan backend runs, through the same kernels: + +| | HIP | Vulkan (same machine, same model) | +|---|---|---| +| Greedy tokens, 3 prompts | identical | identical | +| Prefill, pp 1024 | 492 tok/s | 1458 tok/s | +| Decode, tg 48, `--mtp 2` | 159 tok/s | 232 tok/s | + +Qwen3.6-35B-A3B UD-Q4_K_XL, `--ctx 4096 --vram-margin 256`, RX 9070 XT, Ryzen 7 5700X. Decode is within 1.5x of +Vulkan; prefill is 3x behind because the prefill GEMM has no matrix-core path on HIP yet (see below). + +## How it works + +- `src/hip/compat.h` is prepended to `kernels.cu`: it supplies the CUDA intrinsics the source uses (`__shfl_*_sync`, + `__ballot_sync`, `__dp4a`, `__byte_perm`, `__vsub4`, `__vadd4`, `__nanosleep`, `__trap`, the f16 conversions) with + their AMD equivalents, and sets `__CUDA_ARCH__` to the pre-Volta level so the source takes its portable paths: + per-lane shared loads instead of `ldmatrix`, plain copies instead of `cp.async`, and the CUDA-core multiplicands + instead of `mma.sync`. +- The kernels compile as **wave32** (lane = `threadIdx.x & 31`), which is the default wavefront size on RDNA and the + assumption the CUDA source already makes about a warp. The backend refuses a device that reports a 64-wide wave. +- `src/cuda/kernels.cu` keeps one source for both backends: the few places that cannot be shared are behind + `#if STRATA_HIP` (f16 conversions, the per-lane fragment loads, `mma884`, the KV f16x2 math, the L2 prefetch hint), + so the CUDA build's preprocessed source is unchanged. +- The code object is cached in `$XDG_CACHE_HOME/rusting_strata/.amdgcn`, keyed by the source, the `gfx` target + and the hiprtc version. + +## Requirements + +- A ROCm runtime with hiprtc: `libamdhip64.so` and `libhiprtc.so` on the loader path, in `/opt/rocm/lib`, or named by + `STRATA_HIP` and `STRATA_HIPRTC`. The card must be RDNA (wave32, gfx10+); head_dim 256 prefill attention uses a + 16-key tile because a 32-key tile needs 72 KiB of shared memory and a block may use 64 KiB. +- The device's `gfx` target is read from the driver's device properties; `STRATA_HIP_ARCH=gfx1201` overrides it. + +## Switches + +- `STRATA_HIP_SYNC=1` waits after every launch, so a hardware exception names the kernel that raised it. +- `STRATA_HIP_TRACE=1` names every launch before it goes out (grid, block, shared memory). +- `STRATA_HIP_GRAPH=1` turns on graph capture once the forward allocates nothing inside a step (HIP refuses an + allocation on a capturing stream; CUDA's stream-ordered allocator allows it). +- `STRATA_NO_GRAPH=1` turns capture off for both GPU backends. + +## Next + +1. gfx12 WMMA (`__builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12` and its int8 form) for the prefill GEMM: the 3x + prefill gap is exactly the missing matrix-core path. +2. Graph capture: move the per-step allocations (q8 cache growth, rope table) out of the captured region. +3. The CUDA host-side pipeline: a pinned ring for `htod` (expert streaming during prefill) and a side stream for + `beside`. + +## Credits + +The compatibility shim follows the structure and several implementations of Strata's +`include/strata/hip_compat/intrinsics.hpp` (MIT, (c) 2025 Niko1221, https://github.com/Niko1221/Strata), which runs +CUDA-shaped kernels on the same wave32 targets. See `THANKS.md`. diff --git a/src/backend.rs b/src/backend.rs index 1e7fe87d..011f4787 100644 --- a/src/backend.rs +++ b/src/backend.rs @@ -54,12 +54,13 @@ unsafe impl Plain for u64 {} /// Device memory, recorded graphs and kernel ops. Host copies are synchronous; device work runs in queue order. /// Pointer arguments are device addresses; strides are in floats unless named otherwise. -/// The backend `kind` ("cuda" or "vulkan") on GPU `device`; with no kind, CUDA if it loads, else Vulkan. +/// The backend `kind` ("cuda", "vulkan" or "hip") on GPU `device`; with no kind, CUDA if it loads, else Vulkan. pub fn open(kind: Option<&str>, device: usize) -> anyhow::Result> { match kind { Some("cuda") => Ok(Box::new(crate::cuda::Gpu::new(device)?)), Some("vulkan") => Ok(Box::new(crate::vulkan::Vk::new(device)?)), - Some(k) => anyhow::bail!("unknown backend {k:?} (cuda or vulkan)"), + Some("hip") => Ok(Box::new(crate::hip::Gpu::new(device)?)), + Some(k) => anyhow::bail!("unknown backend {k:?} (cuda, vulkan or hip)"), None => match crate::cuda::Gpu::new(device) { Ok(g) => Ok(Box::new(g)), Err(c) if format!("{c}") == "CUDA init" => { @@ -81,7 +82,7 @@ pub const SAME_X: i32 = 4; pub fn upload_type(ty: GgmlType) -> GgmlType { match ty { GgmlType::F16 => GgmlType::F32, GgmlType::Q4_0 | GgmlType::Q5_0 => GgmlType::Q8_0, ty => ty } } pub trait Backend: Send { - /// "cuda" or "vulkan". + /// "cuda", "vulkan" or "hip". fn name(&self) -> &'static str; /// The GPU's name as the driver reports it. fn device(&self) -> String; diff --git a/src/cuda/kernels.cu b/src/cuda/kernels.cu index 0ffb09f7..3c90061c 100644 --- a/src/cuda/kernels.cu +++ b/src/cuda/kernels.cu @@ -6,8 +6,14 @@ typedef unsigned short u16; typedef unsigned int u32; typedef unsigned long long u64; +#if STRATA_HIP +// AMD: the ISA converts f16 in one instruction, the compiler emits it for these. +__device__ __forceinline__ float h2f(u16 h) { return (float)*(const _Float16*)&h; } +__device__ __forceinline__ u16 f2h(float f) { _Float16 x = (_Float16)f; return *(const u16*)&x; } +#else __device__ __forceinline__ float h2f(u16 h) { float f; asm("cvt.f32.f16 %0, %1;" : "=f"(f) : "h"(h)); return f; } __device__ __forceinline__ u16 f2h(float f) { u16 h; asm("cvt.rn.f16.f32 %0, %1;" : "=h"(h) : "f"(f)); return h; } +#endif __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); } __device__ __forceinline__ float ldh(const u8* p) { return h2f((u16)ld16(p)); } @@ -926,8 +932,12 @@ __device__ __forceinline__ void ldsm4(u32* r, const u16* p) { #pragma unroll for (int m = 0; m < 4; m++) { int m_row = (RM ? (m & 1) : (m >> 1)) * 8, m_col = (RM ? (m >> 1) : (m & 1)) * 8; +#if STRATA_HIP + r[m] = *(const u32*)(p + (m_row + row) * PQ + m_col + col); +#else unsigned a = (unsigned)__cvta_generic_to_shared(p + (m_row + row) * PQ + m_col + col); asm("ld.shared.b32 %0, [%1];" : "=r"(r[m]) : "r"(a)); +#endif } #else unsigned a = (unsigned)__cvta_generic_to_shared(p); @@ -944,11 +954,16 @@ __device__ __forceinline__ void ldsm4t(u32* r, const u16* p) { #pragma unroll for (int m = 0; m < 4; m++) { int m_row = (RM ? (m & 1) : (m >> 1)) * 8, m_col = (RM ? (m >> 1) : (m & 1)) * 8; +#if STRATA_HIP + const u16* a = p + (m_row + row) * PQ + m_col + col; + r[m] = (u32)a[0] | ((u32)a[2 * PQ] << 16); +#else unsigned a = (unsigned)__cvta_generic_to_shared(p + (m_row + row) * PQ + m_col + col); unsigned short lo, hi; asm("ld.shared.u16 %0, [%1];" : "=h"(lo) : "r"(a)); asm("ld.shared.u16 %0, [%1];" : "=h"(hi) : "r"(a + 2 * PQ)); r[m] = (u32)lo | ((u32)hi << 16); +#endif } #else unsigned a = (unsigned)__cvta_generic_to_shared(p); @@ -1005,7 +1020,7 @@ __device__ __forceinline__ void mma16816(float* c, u32 a0, u32 a1, u32 a2, u32 a : "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3]) : "r"(a0), "r"(a1), "r"(a2), "r"(a3), "r"(b0), "r"(b1)); #endif } -#if __CUDA_ARCH__ < 800 +#if __CUDA_ARCH__ < 800 && !STRATA_HIP // D[8,8] += A[8,4] * B[4,8] with the four independent computations of mma.m8n8k4 (Volta, SASS HMMA.884) selected // by g & 3. PTX ISA 8.5 §9.7.13.4.1: lane l = 4*g + t owns A row t + 4*(g >= 4) at k 0..3 and D elements by the // column/row formulas implemented in gemm_q's sm_70 path. mma.m16n8k16 is sm_80+, so this helper only exists for @@ -1884,8 +1899,18 @@ template __device__ __forceinline__ void ldkv(const u16* c, size_t off // q * d rounded once to f16 equals f2h((float)q * d). auto deq = [&](unsigned x, unsigned sel) { unsigned h = __byte_perm(x ^ 0x80808080u, 0x64646464u, sel), r; +#if STRATA_HIP + // Same two f16 lanes without : a 2-element _Float16 vector (the ISA's packed f16 sub/mul). + typedef _Float16 f16x2 __attribute__((ext_vector_type(2))); + unsigned c64 = 0x64806480u; + f16x2 hh = *(f16x2*)&h, cc = *(f16x2*)&c64, dd = *(f16x2*)&d, rr; + rr[0] = (hh[0] - cc[0]) * dd[0]; + rr[1] = (hh[1] - cc[1]) * dd[1]; + r = *(unsigned*)&rr; +#else asm("sub.rn.f16x2 %0, %1, %2;" : "=r"(h) : "r"(h), "r"(0x64806480u)); asm("mul.rn.f16x2 %0, %1, %2;" : "=r"(r) : "r"(h), "r"(d)); +#endif return r; }; if (PER % 8 == 0 && hd % 128 == 0) { // rows 8-byte aligned @@ -2344,8 +2369,14 @@ extern "C" __global__ void moe_prefetch(const int* ids, int k, const int* table, if (s < 0) return; const char* p = base + (size_t)((unsigned int)s * (unsigned int)stride); int lines = bytes >> 7; - for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < lines; i += gridDim.x * blockDim.x) + for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < lines; i += gridDim.x * blockDim.x) { +#if STRATA_HIP + (void)p; // no L2 prefetch instruction to give: moe_prefetch is a CUDA-only hint + break; +#else asm volatile("prefetch.global.L2 [%0];" ::"l"(p + ((size_t)i << 7))); +#endif + } } // x += sum_j w[j] ye[j] + sigmoid(sg) sh + cpu. If a slot missed, wait for the CPU worker's done flag first. diff --git a/src/cuda/mod.rs b/src/cuda/mod.rs index 1a2e2857..1b89356d 100644 --- a/src/cuda/mod.rs +++ b/src/cuda/mod.rs @@ -13,11 +13,11 @@ use std::sync::Arc; mod nvrtc; -const QTYPES: [GgmlType; 24] = { +pub(crate) const QTYPES: [GgmlType; 24] = { use GgmlType::*; [F32, BF16, Q8_0, Q2K, Q3K, Q4K, Q5K, Q6K, IQ1S, IQ1M, IQ2XXS, IQ2XS, IQ2S, IQ3XXS, IQ3S, IQ4XS, IQ4NL, Q2_0, TQ1_0, TQ2_0, Q4_1, Q5_1, Q4_0, Q5_0] }; -const KERNELS: [&str; 36] = [ +pub(crate) const KERNELS: [&str; 36] = [ "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", "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", @@ -74,7 +74,7 @@ const BESIDE: usize = usize::MAX - 1; /// bound (cudarc leaves `CudaGraph` without `Send` only because it holds raw pointers). struct Graph(CudaGraph); -const AMAX_PARTS: usize = 64; +pub(crate) const AMAX_PARTS: usize = 64; unsafe impl Send for Graph {} /// `--llama-numerics`: quantize activations like llama.cpp's CPU q8_K (one scale per 256) for every integer matmul, @@ -93,11 +93,11 @@ pub fn gemm_fma() -> bool { std::env::var_os("STRATA_GEMM_FMA").is_some() } /// Prefill attention query / key tile sizes in positions. `FA_BQ` is one warp's 16 query rows times the four warps /// of the 128-thread block; `FA_BK` is the K/V tile depth and must stay a multiple of 32 for the sm_70 `m8n8k4` /// and sm_80+ `m16n8k16` fragment loops. Injected into kernels.cu by `source()`, never edited there. -const FA_BQ: usize = 64; -const FA_BK: usize = 32; +pub(crate) const FA_BQ: usize = 64; +pub(crate) const FA_BK: usize = 32; /// Prefill GEMM K tile in halves (default, candidate C3 overrides it with `STRATA_GEMM_BK=32`). `GEMM_BM` lives in /// `backend.rs` because the prefill tile-list builder shares it with Vulkan. -const GEMM_BK: usize = 64; +pub(crate) const GEMM_BK: usize = 64; /// Row padding of the attention shared-memory tiles (`PQ = HD + 8`, `FA_BK + 8` in `attn_prefill_t`). const ATTN_SMEM_PAD: usize = 8; @@ -131,13 +131,13 @@ impl Tune { } /// `default` unless `v` parses to a value accepted by `valid`. -fn tuned(v: Option<&str>, default: usize, valid: impl Fn(usize) -> bool) -> usize { +pub(crate) fn tuned(v: Option<&str>, default: usize, valid: impl Fn(usize) -> bool) -> usize { v.and_then(|s| s.trim().parse::().ok()).filter(|&x| valid(x)).unwrap_or(default) } /// Rows per warp: the family override (`STRATA_RPW_MOE`/`_DENSE`) first, then `STRATA_RPW`, then the shape default. /// 1..=64 keeps a block's row loop bounded; anything else falls back one level, as `tuned` does. -fn rpw_from(global: Option<&str>, family: Option<&str>, default: usize) -> usize { +pub(crate) fn rpw_from(global: Option<&str>, family: Option<&str>, default: usize) -> usize { let ok = |v: usize| (1..=64).contains(&v); family.and_then(|s| s.trim().parse().ok()).filter(|&v| ok(v)) .or_else(|| global.and_then(|s| s.trim().parse().ok()).filter(|&v| ok(v))) @@ -146,7 +146,7 @@ fn rpw_from(global: Option<&str>, family: Option<&str>, default: usize) -> usize /// Threads per block of the integer GEMV: the family override first, then the global value, then 256. Only the /// three warp counts the kernel's row mapping can tile are accepted (4/8/16 warps per block). -fn gemv_block_from(global: Option<&str>, family: Option<&str>) -> u32 { +pub(crate) fn gemv_block_from(global: Option<&str>, family: Option<&str>) -> u32 { let ok = |v: u32| matches!(v, 128 | 256 | 512); family.and_then(|s| s.trim().parse::().ok()).filter(|&v| ok(v)) .or_else(|| global.and_then(|s| s.trim().parse::().ok()).filter(|&v| ok(v))) @@ -196,7 +196,7 @@ fn source_with(kv_q8: bool, gemm_tc: bool, tune: Tune) -> String { fn attn_prefill_smem(hd: usize) -> usize { attn_prefill_smem_bk(hd, FA_BK) } /// `attn_prefill_smem` for a K/V tile depth of `bk` keys (16 on Turing at head_dim 256, else `FA_BK`). -fn attn_prefill_smem_bk(hd: usize, bk: usize) -> usize { +pub(crate) fn attn_prefill_smem_bk(hd: usize, bk: usize) -> usize { let pq = hd + ATTN_SMEM_PAD; 2 * (FA_BQ + 2 * bk) * pq + 2 * FA_BQ * (bk + ATTN_SMEM_PAD) } @@ -244,7 +244,7 @@ fn int8_gemm_arch(cc: (i32, i32)) -> bool { cc.0 >= 8 } /// decode GQA kernels (8 query slices per head group plus the cp.async K/V chunks at head_dim 128/256, `attn`), /// `usize::MAX` for `gemvn_*` whose request depends on the tensor shape (`xq_smem * nt`, `gemv_cfg`), and `None` /// for every kernel that never asks for more than the 48 KiB default (`attn_decode_*`, `attn_merge`, the rest). -fn dyn_shmem_need(name: &str) -> Option<(&'static str, usize)> { +pub(crate) fn dyn_shmem_need(name: &str) -> Option<(&'static str, usize)> { let family = if name.starts_with("attn_prefill") { "attn_prefill_*" } else if name.starts_with("attn_decode_gqa") { "attn_decode_gqa*" } else if name.starts_with("gemvn") { "gemvn_*" } @@ -343,7 +343,7 @@ fn smem_log(family: &str, optin: usize, stat: usize, set: Option, carveou /// The kernel names to load from the cubin: the full list on sm_80+, without the int8 prefill GEMM (`gemmi_*` and /// `gemmis_*`, 20 non-float types x 2) on a device where that code is not compiled in. Pure so a CPU test can pin /// both lists (282 / 242 names). -fn kernel_names(sm80: bool) -> Vec { +pub(crate) fn kernel_names(sm80: bool) -> Vec { let int8 = move |&&t: &&GgmlType| sm80 && !matches!(t, GgmlType::F32 | GgmlType::BF16); KERNELS.iter().map(|s| s.to_string()) .chain(QTYPES.iter().flat_map(|&t| ["dequant", "gemv", "gemvn", "moe_gemv", "gemm", "gemms"].map(|p| kname(p, t)))) @@ -427,7 +427,7 @@ macro_rules! launch { }}; } -fn kname(prefix: &str, ty: GgmlType) -> String { format!("{prefix}_{}", ty.name().to_lowercase()) } +pub(crate) fn kname(prefix: &str, ty: GgmlType) -> String { format!("{prefix}_{}", ty.name().to_lowercase()) } impl Gpu { pub fn new(device: usize) -> anyhow::Result { diff --git a/src/hip/compat.h b/src/hip/compat.h new file mode 100644 index 00000000..7e37eed8 --- /dev/null +++ b/src/hip/compat.h @@ -0,0 +1,104 @@ +// Device-side compatibility layer for the HIP backend. `src/hip/mod.rs` prepends this (and the quant tables) to +// `../cuda/kernels.cu`, which the CUDA backend hands to NVRTC unchanged: `kernels.cu` is one source with an explicit +// `STRATA_HIP` branch where the two architectures cannot share code, and this header supplies everything CUDA's +// headers give it for free (warp intrinsics, packed-byte helpers, the f16 SIMD ops) from HIP. +// +// The portable intrinsic implementations are adapted from Strata's include/strata/hip_compat/intrinsics.hpp +// (MIT, (c) 2025 Niko1221); see THANKS.md. They assume the wave32 model the kernels are written for (lane = +// threadIdx.x & 31), which is the default wavefront size on RDNA (gfx10+) — the same assumption the CUDA source +// makes about a warp. +// Prepended to a concatenated source string, so a plain include guard: `#pragma once` would warn in a main file. +#ifndef STRATA_HIP_COMPAT_H +#define STRATA_HIP_COMPAT_H +#include +#include + +// kernels.cu selects its code paths by the CUDA architecture level: ldmatrix from sm_75, cp.async/m16n8k16/int8-mma +// from sm_80, m8n8k4 (mma884) from sm_70. AMD has none of those instructions, so the build takes the portable +// pre-Volta level: per-lane shared loads instead of ldmatrix, plain typed copies instead of cp.async, and the +// CUDA-core (f16 FMA) multiplicands instead of mma.sync. Prefill therefore runs without matrix cores until the +// gfx12 WMMA path lands; decode is unaffected (it has no tensor-core path). +#ifndef __CUDA_ARCH__ +#define __CUDA_ARCH__ 700 +#endif +#define STRATA_HIP 1 +#ifndef __forceinline__ +#define __forceinline__ inline __attribute__((always_inline)) +#endif +#ifndef __align__ +#define __align__(n) __attribute__((aligned(n))) +#endif +// The wave is 32 lanes wide here; a kernel that ever runs with a 64-wide wave would corrupt its reductions. +#if defined(__AMDGCN_WAVEFRONT_SIZE) && __AMDGCN_WAVEFRONT_SIZE != 32 +#error "the HIP backend needs wave32 (RDNA); wave64 targets are not supported" +#endif + +namespace strata_hip { + +__device__ __forceinline__ int signed_byte(unsigned word, int lane) { + unsigned v = (word >> (lane * 8)) & 0xffu; + return v < 0x80u ? (int)v : (int)v - 0x100; +} + +// CUDA's signed __dp4a: four signed byte products accumulated modulo 2^32. +__device__ __forceinline__ int dp4a(int a, int b, int c) { +#if (defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1103__) || defined(__gfx1150__) || \ + defined(__gfx1151__) || defined(__gfx1200__) || defined(__gfx1201__)) && __has_builtin(__builtin_amdgcn_sudot4) + return __builtin_amdgcn_sudot4(true, a, true, b, c, false); +#elif (defined(__gfx1030__) || defined(__gfx1031__) || defined(__gfx1032__)) && __has_builtin(__builtin_amdgcn_sdot4) + return __builtin_amdgcn_sdot4(a, b, c, false); +#else + unsigned ua = (unsigned)a, ub = (unsigned)b, sum = (unsigned)c; +#pragma unroll + for (int i = 0; i < 4; ++i) sum += (unsigned)(signed_byte(ua, i) * signed_byte(ub, i)); + return (int)sum; +#endif +} + +// CUDA's __byte_perm: result byte i is byte s.nibble[i] & 7 of {y:x}. One v_perm_b32 instead of HIP's byte array. +__device__ __forceinline__ unsigned byte_perm(unsigned x, unsigned y, unsigned s) { + unsigned sel = (s & 0x7u) | ((s & 0x70u) << 4) | ((s & 0x700u) << 8) | ((s & 0x7000u) << 12); + return __builtin_amdgcn_perm(y, x, sel); +} + +// Packed byte arithmetic, four lanes at once (SWAR, Hacker's Delight 2-18): gfx11/gfx12 have no packed 8-bit +// add/sub, and a per-lane loop costs the Q3_K/Q6_K dots several times the instructions. +constexpr unsigned kHigh = 0x80808080u; + +__device__ __forceinline__ int vsub4(int a, int b) { + unsigned ua = (unsigned)a, ub = (unsigned)b; + return (int)(((ua | kHigh) - (ub & ~kHigh)) ^ ((ua ^ ~ub) & kHigh)); +} +__device__ __forceinline__ int vadd4(int a, int b) { + unsigned ua = (unsigned)a, ub = (unsigned)b; + return (int)(((ua & ~kHigh) + (ub & ~kHigh)) ^ ((ua ^ ub) & kHigh)); +} + +// The mask is informational here: an AMD wave either takes part in the corresponding `ds_bpermute` or does not, so a +// lane that is not in the mask still receives whatever the exchange computes (CUDA leaves it undefined). That matches +// CUDA whenever the lanes a participating lane exchanges with are participating too, which is how kernels.cu uses it +// (`quant8` shuffles inside groups of four active lanes; the rest pass 0xffffffff). +template __device__ __forceinline__ T shfl_xor_sync(unsigned, T v, int lane_mask, int width = 32) { return __shfl_xor(v, lane_mask, width); } +template __device__ __forceinline__ T shfl_down_sync(unsigned, T v, unsigned d, int width = 32) { return __shfl_down(v, d, width); } +template __device__ __forceinline__ T shfl_up_sync(unsigned, T v, unsigned d, int width = 32) { return __shfl_up(v, d, width); } +template __device__ __forceinline__ T shfl_sync(unsigned, T v, int src, int width = 32) { return __shfl(v, src, width); } +__device__ __forceinline__ unsigned ballot_sync(unsigned, int predicate) { return (unsigned)__ballot(predicate); } +__device__ __forceinline__ int any_sync(unsigned, int predicate) { return (int)(__ballot(predicate) != 0); } + +} // namespace strata_hip + +#define __dp4a(a, b, c) (strata_hip::dp4a((a), (b), (c))) +#define __byte_perm(x, y, s) (strata_hip::byte_perm((x), (y), (s))) +#define __vsub4(a, b) (strata_hip::vsub4((a), (b))) +#define __vadd4(a, b) (strata_hip::vadd4((a), (b))) +#define __shfl_xor_sync(...) (strata_hip::shfl_xor_sync(__VA_ARGS__)) +#define __shfl_down_sync(...) (strata_hip::shfl_down_sync(__VA_ARGS__)) +#define __shfl_up_sync(...) (strata_hip::shfl_up_sync(__VA_ARGS__)) +#define __shfl_sync(...) (strata_hip::shfl_sync(__VA_ARGS__)) +#define __ballot_sync(m, p) (strata_hip::ballot_sync((m), (p))) +#define __any_sync(m, p) (strata_hip::any_sync((m), (p))) +// The compiled-out sm_80+ paths still mention these; no CUDA-only helper may survive into a HIP build. +#define __trap() __builtin_trap() +#define __nanosleep(cycles) __builtin_amdgcn_s_sleep(1) + +#endif // STRATA_HIP_COMPAT_H diff --git a/src/hip/ffi.rs b/src/hip/ffi.rs new file mode 100644 index 00000000..ed6ea1cf --- /dev/null +++ b/src/hip/ffi.rs @@ -0,0 +1,341 @@ +//! HIP runtime and hiprtc, loaded by name like `cuda/nvrtc.rs` loads NVRTC: no ROCm headers, link flags or `hipcc` +//! at build time, and no C++ build step. Every entry point the backend uses is resolved once per process. + +use anyhow::{Context, bail}; +use libloading::Library; +use std::ffi::{CStr, c_char, c_int, c_void}; +use std::path::PathBuf; +use std::sync::OnceLock; + +pub type Stream = *mut c_void; +pub type Module = *mut c_void; +pub type Func = *mut c_void; +pub type Event = *mut c_void; +pub type Graph = *mut c_void; +pub type GraphExec = *mut c_void; +pub type RtcProgram = *mut c_void; + +// hipError_t / hiprtcResult +pub const HIP_SUCCESS: c_int = 0; + +// Values the ROCm 7 headers give these enums (probe-printed; see the module docs of `hip`). +pub const MEMCPY_H2D: c_int = 1; +pub const MEMCPY_D2H: c_int = 2; +pub const MEMCPY_D2D: c_int = 3; +pub const HOST_MALLOC_PORTABLE: u32 = 1; +pub const HOST_MALLOC_MAPPED: u32 = 2; +pub const EVENT_DISABLE_TIMING: u32 = 2; +pub const STREAM_NON_BLOCKING: u32 = 1; +pub const CAPTURE_MODE_THREAD_LOCAL: c_int = 1; +pub const ATTR_MAX_DYNAMIC_SHARED: c_int = 8; +pub const ATTR_SHARED_PER_BLOCK_OPTIN: c_int = 75; +pub const ATTR_SHARED_PER_BLOCK: c_int = 74; +pub const ATTR_WARP_SIZE: c_int = 87; +pub const ATTR_INTEGRATED: c_int = 16; +pub const ATTR_MULTIPROCESSOR_COUNT: c_int = 63; +pub const ATTR_MAX_THREADS_PER_BLOCK: c_int = 56; + +/// `hipDeviceProp_t` from ROCm 7: the field offsets the backend reads. The struct is version-specific, so every +/// read is validated (the architecture name must look like `gfxNNNN`) and `STRATA_HIP_ARCH` overrides it. +const PROP_SIZE: usize = 1472; +const PROP_GCN_ARCH_NAME: usize = 1160; + +type Fn = unsafe extern "C" fn(); + +/// Library names to try, in order. `STRATA_HIP` (a path or a name) replaces the whole list. +fn candidates(vars: Option, default_suffix: &[&str]) -> Vec { + if let Some(p) = vars { return vec![p]; } + let mut v: Vec = Vec::new(); + for s in default_suffix { v.push(PathBuf::from(s)); } + // A ROCm install that is not on the loader path (`/opt/rocm` may be a symlink chain). + for root in ["/opt/rocm/lib", "/opt/rocm/core-10.1/lib", "/usr/lib/x86_64-linux-gnu", "/usr/local/lib"] { + for s in default_suffix { v.push(PathBuf::from(root).join(s)); } + } + v +} + +pub struct Hip { + pub init: unsafe extern "C" fn(c_int) -> c_int, + pub device_count: unsafe extern "C" fn(*mut c_int) -> c_int, + pub set_device: unsafe extern "C" fn(c_int) -> c_int, + pub device_name: unsafe extern "C" fn(*mut c_char, c_int, c_int) -> c_int, + pub device_attribute: unsafe extern "C" fn(*mut c_int, c_int, c_int) -> c_int, + pub mem_get_info: unsafe extern "C" fn(*mut usize, *mut usize) -> c_int, + pub malloc: unsafe extern "C" fn(*mut *mut c_void, usize) -> c_int, + pub free: unsafe extern "C" fn(*mut c_void) -> c_int, + pub memset: unsafe extern "C" fn(*mut c_void, c_int, usize) -> c_int, + pub memcpy: unsafe extern "C" fn(*mut c_void, *const c_void, usize, c_int) -> c_int, + pub memcpy_async: unsafe extern "C" fn(*mut c_void, *const c_void, usize, c_int, Stream) -> c_int, + pub stream_create: unsafe extern "C" fn(*mut Stream, u32) -> c_int, + pub stream_destroy: unsafe extern "C" fn(Stream) -> c_int, + pub stream_sync: unsafe extern "C" fn(Stream) -> c_int, + pub stream_wait_event: unsafe extern "C" fn(Stream, Event, u32) -> c_int, + pub stream_begin_capture: unsafe extern "C" fn(Stream, c_int) -> c_int, + pub stream_end_capture: unsafe extern "C" fn(Stream, *mut Graph) -> c_int, + pub stream_is_capturing: unsafe extern "C" fn(Stream, *mut c_int) -> c_int, + pub graph_instantiate: unsafe extern "C" fn(*mut GraphExec, Graph, u64) -> c_int, + pub graph_launch: unsafe extern "C" fn(GraphExec, Stream) -> c_int, + pub graph_exec_destroy: unsafe extern "C" fn(GraphExec) -> c_int, + pub graph_destroy: unsafe extern "C" fn(Graph) -> c_int, + pub event_create: unsafe extern "C" fn(*mut Event, u32) -> c_int, + pub event_record: unsafe extern "C" fn(Event, Stream) -> c_int, + pub event_sync: unsafe extern "C" fn(Event) -> c_int, + pub event_query: unsafe extern "C" fn(Event) -> c_int, + pub event_destroy: unsafe extern "C" fn(Event) -> c_int, + pub host_malloc: unsafe extern "C" fn(*mut *mut c_void, usize, u32) -> c_int, + pub host_free: unsafe extern "C" fn(*mut c_void) -> c_int, + pub host_device_ptr: unsafe extern "C" fn(*mut *mut c_void, *mut c_void, u32) -> c_int, + pub module_load: unsafe extern "C" fn(*mut Module, *const c_void) -> c_int, + pub module_unload: unsafe extern "C" fn(Module) -> c_int, + pub function: unsafe extern "C" fn(*mut Func, Module, *const c_char) -> c_int, + pub launch: unsafe extern "C" fn(Func, u32, u32, u32, u32, u32, u32, u32, Stream, *mut *mut c_void, *mut *mut c_void) -> c_int, + pub func_set_attribute: unsafe extern "C" fn(*const c_void, c_int, c_int) -> c_int, + pub error_string: unsafe extern "C" fn(c_int) -> *const c_char, + pub last_error: unsafe extern "C" fn() -> c_int, + _lib: Library, +} + +impl Hip { + /// The runtime, or an error naming what was missing. "HIP init" lets `backend::open` fall back to Vulkan. + pub fn open() -> anyhow::Result { + let want = candidates(std::env::var_os("STRATA_HIP").map(Into::into), + &["libamdhip64.so", "libamdhip64.so.7", "libamdhip64.so.6"]); + let mut tried = Vec::new(); + for path in &want { + if let Ok(lib) = unsafe { Library::new(path) } { + if let Some(h) = unsafe { Self::bind(lib) } { return Ok(h); } + tried.push(format!("{}: missing symbols", path.display())); + } else { + tried.push(format!("{}: not loadable", path.display())); + } + } + Err(anyhow::anyhow!("no HIP runtime: {}", tried.join(", "))).context("HIP init") + } + + unsafe fn sym(lib: &Library, name: &str) -> Option { + let s = unsafe { lib.get::(format!("{name}\0").as_bytes()).ok() }?; + Some(*s) + } + + unsafe fn bind(lib: Library) -> Option { + macro_rules! g { ($n:literal) => { unsafe { Self::sym(&lib, $n)? } } } + Some(Hip { + init: g!("hipInit"), + device_count: g!("hipGetDeviceCount"), + set_device: g!("hipSetDevice"), + device_name: g!("hipDeviceGetName"), + device_attribute: g!("hipDeviceGetAttribute"), + mem_get_info: g!("hipMemGetInfo"), + malloc: g!("hipMalloc"), + free: g!("hipFree"), + memset: g!("hipMemset"), + memcpy: g!("hipMemcpy"), + memcpy_async: g!("hipMemcpyAsync"), + stream_create: g!("hipStreamCreateWithFlags"), + stream_destroy: g!("hipStreamDestroy"), + stream_sync: g!("hipStreamSynchronize"), + stream_wait_event: g!("hipStreamWaitEvent"), + stream_begin_capture: g!("hipStreamBeginCapture"), + stream_end_capture: g!("hipStreamEndCapture"), + stream_is_capturing: g!("hipStreamIsCapturing"), + graph_instantiate: g!("hipGraphInstantiateWithFlags"), + graph_launch: g!("hipGraphLaunch"), + graph_exec_destroy: g!("hipGraphExecDestroy"), + graph_destroy: g!("hipGraphDestroy"), + event_create: g!("hipEventCreateWithFlags"), + event_record: g!("hipEventRecord"), + event_sync: g!("hipEventSynchronize"), + event_query: g!("hipEventQuery"), + event_destroy: g!("hipEventDestroy"), + host_malloc: g!("hipHostMalloc"), + host_free: g!("hipHostFree"), + host_device_ptr: g!("hipHostGetDevicePointer"), + module_load: g!("hipModuleLoadData"), + module_unload: g!("hipModuleUnload"), + function: g!("hipModuleGetFunction"), + launch: g!("hipModuleLaunchKernel"), + func_set_attribute: g!("hipFuncSetAttribute"), + error_string: g!("hipGetErrorString"), + last_error: g!("hipGetLastError"), + _lib: lib, + }) + } + + pub fn err(&self, code: c_int) -> String { + let s = unsafe { (self.error_string)(code) }; + if s.is_null() { return format!("hip error {code}") } + unsafe { CStr::from_ptr(s) }.to_string_lossy().into_owned() + } + + pub fn check(&self, code: c_int, what: &str) -> anyhow::Result<()> { + if code == HIP_SUCCESS { return Ok(()) } + bail!("{what}: {}", self.err(code)) + } + + /// The device's `gfxNNNN` target, from `hipDeviceProp_t`'s `gcnArchName`. `STRATA_HIP_ARCH` overrides it. + /// ROCm 7 dropped the `hipDeviceAttributeArch`/`GcnArchName` attributes, so the property struct is the only + /// source; it is version-specific, hence the field-length and shape check before the value is trusted. + pub fn arch(&self, device: c_int) -> anyhow::Result { + if let Ok(a) = std::env::var("STRATA_HIP_ARCH") { return Ok(a) } + if let Some(a) = self.prop_arch(device) { return Ok(a) } + bail!("cannot read the device's gfx architecture; set STRATA_HIP_ARCH (e.g. gfx1201)") + } + + /// The device property struct is version-specific (`hipDeviceProp_t` and `hipDeviceProp_tR0600` differ, and ROCm 7 + /// resolves `hipGetDeviceProperties` to the latter), so the target name is found by shape inside the struct + /// instead of at a fixed offset: the first `gfxNNNN`-looking string, validated. + fn prop_arch(&self, device: c_int) -> Option { + // Resolved here and not in `bind`: this is the only use, and a missing symbol must not fail the backend. + let f: unsafe extern "C" fn(*mut c_void, c_int) -> c_int = unsafe { Self::sym(&self._lib, "hipGetDeviceProperties") }?; + let mut buf = vec![0u64; PROP_SIZE / 8]; + let r = unsafe { f(buf.as_mut_ptr().cast(), device) }; + if r != HIP_SUCCESS { return None } + let bytes = unsafe { std::slice::from_raw_parts(buf.as_ptr().cast::(), PROP_SIZE) }; + for i in (0..bytes.len().saturating_sub(8)).step_by(4) { + if &bytes[i..i + 3] != b"gfx" { continue } + let end = bytes[i..i + 16].iter().position(|&b| b == 0 || !(b as char).is_ascii_alphanumeric()).unwrap_or(16); + if end < 6 { continue } + let s = String::from_utf8(bytes[i..i + end].to_vec()).ok()?; + return Some(s); + } + None + } + + pub fn device_name(&self, device: c_int) -> String { + let mut buf = [0 as c_char; 256]; + let r = unsafe { (self.device_name)(buf.as_mut_ptr(), 256, device) }; + if r != HIP_SUCCESS { return "AMD GPU".into() } + unsafe { CStr::from_ptr(buf.as_ptr()) }.to_string_lossy().into_owned() + } + + pub fn attribute(&self, attr: c_int, device: c_int) -> anyhow::Result { + let mut v = 0; + self.check(unsafe { (self.device_attribute)(&mut v, attr, device) }, "hipDeviceGetAttribute")?; + Ok(v) + } +} + +pub struct Rtc { + version: unsafe extern "C" fn(*mut c_int, *mut c_int) -> c_int, + create: unsafe extern "C" fn(*mut RtcProgram, *const c_char, *const c_char, c_int, *const *const c_char, *const *const c_char) -> c_int, + compile: unsafe extern "C" fn(RtcProgram, c_int, *const *const c_char) -> c_int, + log_size: unsafe extern "C" fn(RtcProgram, *mut usize) -> c_int, + log: unsafe extern "C" fn(RtcProgram, *mut c_char) -> c_int, + code_size: unsafe extern "C" fn(RtcProgram, *mut usize) -> c_int, + code: unsafe extern "C" fn(RtcProgram, *mut c_char) -> c_int, + destroy: unsafe extern "C" fn(*mut RtcProgram) -> c_int, + error_string: unsafe extern "C" fn(c_int) -> *const c_char, + lib_path: PathBuf, + _lib: Library, +} + +static RTC: OnceLock> = OnceLock::new(); + +impl Rtc { + pub fn get() -> Option<&'static Rtc> { RTC.get_or_init(Self::open).as_ref() } + + fn open() -> Option { + let want = candidates(std::env::var_os("STRATA_HIPRTC").map(Into::into), + &["libhiprtc.so", "libhiprtc.so.7", "libhiprtc.so.6"]); + for path in &want { + let Ok(lib) = (unsafe { Library::new(path) }) else { continue }; + unsafe { + macro_rules! g { ($n:literal) => { match Self::sym(&lib, $n) { Some(f) => f, None => continue } } } + return Some(Rtc { + version: g!("hiprtcVersion"), + create: g!("hiprtcCreateProgram"), + compile: g!("hiprtcCompileProgram"), + log_size: g!("hiprtcGetProgramLogSize"), + log: g!("hiprtcGetProgramLog"), + code_size: g!("hiprtcGetCodeSize"), + code: g!("hiprtcGetCode"), + destroy: g!("hiprtcDestroyProgram"), + error_string: g!("hiprtcGetErrorString"), + lib_path: path.clone(), + _lib: lib, + }); + } + } + None + } + + unsafe fn sym(lib: &Library, name: &str) -> Option { + let s = unsafe { lib.get::(format!("{name}\0").as_bytes()).ok() }?; + Some(*s) + } + + pub fn version(&self) -> (i32, i32) { + let (mut maj, mut min) = (0, 0); + unsafe { (self.version)(&mut maj, &mut min) }; + (maj, min) + } + + fn err(&self, code: c_int) -> String { + let s = unsafe { (self.error_string)(code) }; + if s.is_null() { return format!("hiprtc error {code}") } + unsafe { CStr::from_ptr(s) }.to_string_lossy().into_owned() + } + + /// Directories holding `hip/hip_runtime.h`: hiprtc compiles a string in a scratch directory, so the ROCm headers + /// have to be named. Found next to the loaded `libhiprtc` and through the environment. + fn include_dirs(&self) -> Vec { + let mut v = Vec::new(); + for k in ["ROCM_PATH", "HIP_PATH"] { + if let Some(p) = std::env::var_os(k) { v.push(PathBuf::from(p).join("include")); } + } + if let Some(dir) = self.lib_path.parent() { + // libhiprtc.so -> /lib, headers in /include (also /include/hip). + v.push(dir.join("../include")); + } + for p in ["/opt/rocm/include", "/usr/include", "/usr/local/include"] { v.push(PathBuf::from(p)); } + v.retain(|p| p.join("hip/hip_runtime.h").exists()); + v + } + + /// Compile `src` to an AMDGPU code object for `arch` (`gfx1201`). `name` only labels diagnostics. + pub fn compile(&self, src: &str, name: &str, arch: &str, extra: &[&str]) -> anyhow::Result> { + let csrc = std::ffi::CString::new(src).context("kernel source contains a NUL byte")?; + let cname = std::ffi::CString::new(name)?; + let mut prog: RtcProgram = std::ptr::null_mut(); + let code = unsafe { (self.create)(&mut prog, csrc.as_ptr(), cname.as_ptr(), 0, std::ptr::null(), std::ptr::null()) }; + if code != HIP_SUCCESS { bail!("hiprtcCreateProgram: {}", self.err(code)) } + let guard = ProgGuard { prog, destroy: self.destroy }; + let mut opts: Vec = vec![ + std::ffi::CString::new(format!("--offload-arch={arch}"))?, + std::ffi::CString::new("-O3")?, + std::ffi::CString::new("--std=c++17")?, + ]; + for dir in self.include_dirs() { opts.push(std::ffi::CString::new(format!("-I{}", dir.display()))?); } + for e in extra { opts.push(std::ffi::CString::new(*e)?); } + let ptrs: Vec<*const c_char> = opts.iter().map(|o| o.as_ptr()).collect(); + let code = unsafe { (self.compile)(guard.prog, ptrs.len() as c_int, ptrs.as_ptr()) }; + let mut logsize = 0usize; + unsafe { (self.log_size)(guard.prog, &mut logsize) }; + if logsize > 1 { + let mut log = vec![0 as c_char; logsize]; + unsafe { (self.log)(guard.prog, log.as_mut_ptr()) }; + let text = unsafe { CStr::from_ptr(log.as_ptr()) }.to_string_lossy(); + if code != HIP_SUCCESS { bail!("hiprtc ({arch}): {}\n{}", self.err(code), text.trim_end()) } + let text = text.trim_end(); + if !text.is_empty() { eprintln!("hiprtc {name} ({arch}): {text}") } + } else if code != HIP_SUCCESS { + bail!("hiprtc ({arch}): {}", self.err(code)) + } + let mut n = 0usize; + unsafe { (self.code_size)(guard.prog, &mut n) }; + anyhow::ensure!(n > 0, "hiprtc produced no code for {arch}"); + let mut code_obj = vec![0u8; n]; + let r = unsafe { (self.code)(guard.prog, code_obj.as_mut_ptr().cast()) }; + if r != HIP_SUCCESS { bail!("hiprtcGetCode: {}", self.err(r)) } + Ok(code_obj) + } +} + +struct ProgGuard { + prog: RtcProgram, + destroy: unsafe extern "C" fn(*mut RtcProgram) -> c_int, +} + +impl Drop for ProgGuard { + fn drop(&mut self) { unsafe { (self.destroy)(&mut self.prog) }; } +} diff --git a/src/hip/mod.rs b/src/hip/mod.rs new file mode 100644 index 00000000..80030f72 --- /dev/null +++ b/src/hip/mod.rs @@ -0,0 +1,854 @@ +//! HIP (ROCm) backend: the same `kernels.cu` as `cuda`, with `STRATA_HIP` selecting its portable code paths, compiled +//! at run time by hiprtc for the device's `gfx` target and launched through the HIP runtime loaded by name (see +//! `ffi` and `compat.h`). No ROCm headers, no `hipcc`, no C++ build step: `cargo build --release` and `--backend hip`. +//! +//! The device side is one source: `kernels.cu` keeps its CUDA paths behind `#if !STRATA_HIP`, and `compat.h` supplies +//! what CUDA's headers give it for free. On RDNA the kernel is compiled as wave32 (lane = threadIdx.x & 31), which is +//! the assumption the source already makes about a warp. +//! +//! Status: the host layer and the wave32 device build are in place; ops are being wired up one family at a time +//! against the CPU reference (`cargo test --release hip`). Everything not yet ported returns an error naming the op, +//! so a run says exactly which kernel is missing instead of computing silently wrong numbers. + +use crate::backend::{ATT_SPLITS, ATT_SPLITS_1, Backend, Buf, GpuTensor, GEMM_BM, SAME_X}; +use crate::cuda::{AMAX_PARTS, FA_BK, attn_prefill_smem_bk, dyn_shmem_need, kname, rpw_from, gemv_block_from, tuned}; +use crate::quant::GgmlType; +use anyhow::{Context, bail}; +use std::any::Any; +use std::collections::HashMap; +use std::ffi::c_void; +use std::sync::{Arc, LazyLock, Mutex}; + +/// `STRATA_HIP_SYNC`: one sync per launch (see `Gpu::launch`). +static SYNC_EACH: LazyLock = LazyLock::new(|| std::env::var_os("STRATA_HIP_SYNC").is_some()); +/// `STRATA_HIP_TRACE`: name every launch before it goes out, so a fault that kills the process names the kernel. +static TRACE: LazyLock = LazyLock::new(|| std::env::var_os("STRATA_HIP_TRACE").is_some()); + +mod ffi; + +pub struct Gpu { + /// The runtime, shared with every allocation and graph so none of them outlives the library that frees it. + hip: Arc, + device: usize, + stream: ffi::Stream, + module: ffi::Module, + fns: HashMap, + /// "gfx1201": the target hiprtc compiled for. + arch: String, + /// `--kv q8` (the kernels were compiled with KV_Q8). + pub kv_q8: bool, + /// Opt-in shared memory per block on this device (64 KiB on RDNA). + max_smem: usize, + /// `argmax_rows` partials. + am: Buf, + /// q8 rows of the last integer GEMM's X (see quant_q8 in kernels.cu) and which x they hold; `None` after a call + /// without `SAME_X` that did not quantize. + q8: Mutex<(Buf, Option<[u64; 4]>)>, + /// Recorded graphs by `Backend::graph` key. + graphs: Mutex>, + /// Recorded by `sync`, so a wait can poll it instead of spinning in the driver. + done: ffi::Event, + /// Rope frequency tables, `base` and `n_rot` to the device buffer that holds them. + fr: Mutex<(HashMap<(u32, usize), Buf>, Vec<(f32, usize)>)>, +} + +// The HIP handles are raw pointers but the runtime is thread-safe for the calls the backend makes, and `Backend` +// requires `Send`: transfers, launches and synchronization may come from any thread. +unsafe impl Send for Gpu {} + +struct Graph { + exec: ffi::GraphExec, + graph: ffi::Graph, + hip: Arc, +} + +impl Drop for Graph { + fn drop(&mut self) { + unsafe { + (self.hip.graph_exec_destroy)(self.exec); + (self.hip.graph_destroy)(self.graph); + } + } +} + +/// One launch: grid and block dimensions and the dynamic shared memory the kernel asks for. +#[derive(Clone, Copy)] +pub struct LaunchConfig { + pub grid_dim: (u32, u32, u32), + pub block_dim: (u32, u32, u32), + pub shared_mem_bytes: u32, +} + +pub fn cfg(grid: (u32, u32), block: u32, smem: u32) -> LaunchConfig { + LaunchConfig { grid_dim: (grid.0, grid.1, 1), block_dim: (block, 1, 1), shared_mem_bytes: smem } +} + +/// Launch kernel `$name` with `cfg`. Every argument is evaluated into a local, so `hipModuleLaunchKernel` reads it +/// from a live address; the type of the expression gives the parameter width, as the kernel's signature expects. +macro_rules! launch { + ($g:expr, $name:expr, $cfg:expr, $($a:expr),* $(,)?) => {{ + let c = $cfg; + $g.launch(&$name, c, &mut [ $(&mut { $a } as &mut dyn Any),* ]) + .with_context(|| format!("launch {}", $name))?; + }}; +} + +/// `kernels.cu` assembled for hiprtc: the compatibility layer, the quant tables, the compile-time switches, the file. +fn source(kv_q8: bool) -> String { + use crate::quant::tables::*; + let join = |v: Vec| v.join(","); + format!( + "{}\n\ + __device__ const unsigned long long iq2xs_grid[512] = {{{}}};\n\ + __device__ const unsigned long long iq2xxs_grid[256] = {{{}}};\n\ + __device__ const unsigned long long iq2s_grid[1024] = {{{}}};\n\ + __device__ const unsigned long long iq1s_grid[2048] = {{{}}};\n\ + __device__ const unsigned int iq3xxs_grid[256] = {{{}}};\n\ + __device__ const unsigned int iq3s_grid[512] = {{{}}};\n\ + __device__ const unsigned char ksigns_iq2xs[128] = {{{}}};\n\ + __device__ const signed char kvalues_iq4nl[16] = {{{}}};\n\ + #define LLAMA_Q8 {}\n#define KV_Q8 {}\n#define GEMM_TC 0\n\ + #define GEMM_BM {}\n#define GEMM_BK {}\n#define GEMM_MIN_BLOCKS 1\n#define GEMV_LOADW {}\n\ + #define FA_BQ {}\n#define FA_BK {}\n{}", + include_str!("compat.h"), + join(IQ2XS_GRID.iter().map(|v| format!("{v:#x}ULL")).collect()), + join(IQ2XXS_GRID.iter().map(|v| format!("{v:#x}ULL")).collect()), + join(IQ2S_GRID.iter().map(|v| format!("{v:#x}ULL")).collect()), + join(IQ1S_GRID.iter().map(|v| format!("{v:#x}ULL")).collect()), + join(IQ3XXS_GRID.iter().map(|v| format!("{v:#x}ULL")).collect()), + join(IQ3S_GRID.iter().map(|v| format!("{v:#x}ULL")).collect()), + join(KSIGNS_IQ2XS.iter().map(|v| v.to_string()).collect()), + join(KVALUES_IQ4NL.iter().map(|v| v.to_string()).collect()), + crate::cuda::llama_numerics() as u8, + kv_q8 as u8, + GEMM_BM, + crate::cuda::GEMM_BK, + tuned(std::env::var("STRATA_GEMV_LOADW").ok().as_deref(), 0, |v| v <= 1), + crate::cuda::FA_BQ, + crate::cuda::FA_BK, + include_str!("../cuda/kernels.cu"), + ) +} + +/// Cache key for a compiled code object: the source, the target and the hiprtc version. +fn cache_key(src: &str, arch: &str, rtc: &str) -> u64 { + use std::hash::{Hash, Hasher}; + let mut h = std::collections::hash_map::DefaultHasher::new(); + (src, arch, rtc).hash(&mut h); + h.finish() +} + +impl Gpu { + pub fn new(device: usize) -> anyhow::Result { + let hip = Arc::new(ffi::Hip::open()?); + hip.check(unsafe { (hip.init)(0) }, "hipInit")?; + let n = { + let mut n = 0; + hip.check(unsafe { (hip.device_count)(&mut n) }, "hipGetDeviceCount")?; + n as usize + }; + anyhow::ensure!(device < n, "HIP device {device}: {n} device(s) present"); + hip.check(unsafe { (hip.set_device)(device as i32) }, "hipSetDevice")?; + let arch = hip.arch(device as i32)?; + let warp = hip.attribute(ffi::ATTR_WARP_SIZE, device as i32)?; + anyhow::ensure!(warp == 32, "H100 HIP backend needs wave32; {arch} reports warp size {warp}"); + // Opt-in (75) is what a kernel may ask for; fall back to the plain per-block limit (74) if a runtime does not + // know the attribute, and never trust a figure below the smallest tile the prefill attention needs. + let mut max_smem = hip.attribute(ffi::ATTR_SHARED_PER_BLOCK_OPTIN, device as i32).unwrap_or(0) as usize; + if max_smem < (16 << 10) { + max_smem = hip.attribute(ffi::ATTR_SHARED_PER_BLOCK, device as i32).unwrap_or(16 << 10) as usize; + } + anyhow::ensure!(max_smem >= (16 << 10), "HIP device reports {max_smem} B of shared memory a block"); + let kv_q8 = crate::cuda::kv_q8(); + let rtc = ffi::Rtc::get().context("HIP init").context("hiprtc is required to compile the kernels")?; + let (maj, min) = rtc.version(); + let tag = format!("{maj}.{min}"); + eprintln!("hip: {} ({arch}, wave{warp}, {} B shared memory a block)", + hip.device_name(device as i32), max_smem); + let src = source(kv_q8); + let obj = compile_cached(rtc, &src, &arch, &tag)?; + let mut stream: ffi::Stream = std::ptr::null_mut(); + hip.check(unsafe { (hip.stream_create)(&mut stream, ffi::STREAM_NON_BLOCKING) }, "hipStreamCreate")?; + let mut module: ffi::Module = std::ptr::null_mut(); + hip.check(unsafe { (hip.module_load)(&mut module, obj.as_ptr().cast()) }, "hipModuleLoadData")?; + let mut fns = HashMap::new(); + for name in kernel_names() { + let c = std::ffi::CString::new(name.clone())?; + let mut f: ffi::Func = std::ptr::null_mut(); + hip.check(unsafe { (hip.function)(&mut f, module, c.as_ptr()) }, &format!("hipModuleGetFunction({name})"))?; + // The kernels ask for up to 49 KiB of dynamic shared memory, more than HIP allows by default. The ceiling + // is the device's opt-in minus what the kernel already uses statically, which the runtime only checks + // here, so an over-ask is halved instead of failing the backend. + if let Some((_, need)) = dyn_shmem_need(&name) { + let mut want = need.min(max_smem); + loop { + let r = unsafe { (hip.func_set_attribute)(f, ffi::ATTR_MAX_DYNAMIC_SHARED, want as i32) }; + if r == ffi::HIP_SUCCESS { break } + if want < 8192 { + bail!("hipFuncSetAttribute({name}, {want}): {}", hip.err(r)); + } + want /= 2; + } + } + fns.insert(name, f); + } + let am_buf = alloc_raw(&hip, 64 * AMAX_PARTS)?; + let q8_buf = alloc_raw(&hip, 1)?; + let mut done: ffi::Event = std::ptr::null_mut(); + hip.check(unsafe { (hip.event_create)(&mut done, ffi::EVENT_DISABLE_TIMING) }, "hipEventCreate")?; + Ok(Gpu { hip, device, stream, module, fns, arch, kv_q8, max_smem, am: am_buf, q8: Mutex::new((q8_buf, None)), + graphs: Mutex::new(HashMap::new()), done, fr: Mutex::new((HashMap::new(), Vec::new())) }) + } + + fn h(&self) -> &ffi::Hip { &self.hip } + + pub fn arch(&self) -> &str { &self.arch } + + /// Launch kernel `name` with `cfg`; `args` are the kernel parameters, in order, read from the given addresses. + pub fn launch(&self, name: &str, c: LaunchConfig, args: &mut [&mut dyn Any]) -> anyhow::Result<()> { + let f = *self.fns.get(name).ok_or_else(|| anyhow::anyhow!("HIP kernel {name} is not loaded"))?; + if *TRACE { eprintln!("hip launch {name} grid {:?} block {:?} smem {}", c.grid_dim, c.block_dim, c.shared_mem_bytes); } + let mut params: Vec<*mut c_void> = args.iter_mut().map(|a| (*a as *mut dyn Any).cast::()).collect(); + let r = unsafe { + (self.hip.launch)(f, c.grid_dim.0, c.grid_dim.1, c.grid_dim.2, c.block_dim.0, c.block_dim.1, c.block_dim.2, + c.shared_mem_bytes, self.stream, params.as_mut_ptr(), std::ptr::null_mut()) + }; + if r != ffi::HIP_SUCCESS { bail!("{}: {}", name, self.hip.err(r)) } + // `STRATA_HIP_SYNC`: wait after every launch, so a hardware exception or bad argument names the kernel that + // raised it instead of the sync at the end of the pass. Debugging only: no overlap and no graphs. + if *SYNC_EACH { + self.hip.check(unsafe { (self.hip.stream_sync)(self.stream) }, &format!("kernel {name} failed"))?; + } + Ok(()) + } + + fn wait(&self) -> anyhow::Result<()> { + self.hip.check(unsafe { (self.hip.stream_sync)(self.stream) }, "hipStreamSynchronize") + } + + fn ptr(&self, b: &Buf) -> u64 { b.addr() } + + fn f(&self, name: &str) -> anyhow::Result { + self.fns.get(name).copied().ok_or_else(|| anyhow::anyhow!("HIP kernel {name} is not loaded")) + } + + /// qwen35moe and the other models this backend targets dequantize in the kernel, so the ops below are the + /// generic ones. + fn float_ty(ty: GgmlType) -> bool { matches!(ty, GgmlType::F32 | GgmlType::BF16) } + + fn gemv_cols(prefix: &str, ty: GgmlType, cols: usize) -> anyhow::Result<(i32, String)> { + let b = ty.block_elems().max(32); + if cols % b != 0 { bail!("{} tensor with {cols} columns: GEMV needs a multiple of {b}", ty.name()); } + Ok((cols as i32, kname(prefix, ty) + if cols % 256 != 0 { "_p" } else { "" })) + } + + fn rpw(rows: usize, cols: usize, k: usize) -> usize { + let d = if k > 1 { if cols <= 512 { 4 } else { (2048 / cols).max(1) } } else if rows >= 65536 { 8 } else if rows >= 8192 || rows == 2048 { 2 } else { 1 }; + let fam = if k > 1 { "STRATA_RPW_MOE" } else { "STRATA_RPW_DENSE" }; + let family = std::env::var(fam).ok(); + rpw_from(std::env::var("STRATA_RPW").ok().as_deref(), family.as_deref(), d) + } + + fn gemv_block(k: usize) -> u32 { + let fam = if k > 1 { "STRATA_GEMV_BLOCK_MOE" } else { "STRATA_GEMV_BLOCK_DENSE" }; + let family = std::env::var(fam).ok(); + gemv_block_from(std::env::var("STRATA_GEMV_BLOCK").ok().as_deref(), family.as_deref()) + } + + fn xq_smem(ty: GgmlType, cols: usize) -> u32 { + if Self::float_ty(ty) { 0 } else { (cols + cols / 8) as u32 } + } + + fn gemv_cfg(ty: GgmlType, rows: usize, cols: usize, k: usize) -> (LaunchConfig, i32) { + if Self::float_ty(ty) { + let wpb = if rows >= 4096 { 8 } else { 1 }; + return (cfg((rows.div_ceil(wpb) as u32, k as u32), 32 * wpb as u32, 0), 1); + } + let (rpw, wpb) = (Self::rpw(rows, cols, k), Self::gemv_block(k) as usize / 32); + (cfg((rows.div_ceil(wpb * rpw) as u32, k as u32), (32 * wpb) as u32, Self::xq_smem(ty, cols)), rpw as i32) + } + + /// The rope frequencies base^(-2i / n_rot) as `rms_norm_rope` computes them in f64, made once by `rope_freq`. + fn rope_fr(&self, base: f32, n_rot: usize) -> anyhow::Result { + let mut fr = self.fr.lock().unwrap(); + if let Some(b) = fr.0.get(&(base.to_bits(), n_rot)) { return Ok(b.addr()) } + let buf = alloc_raw(&self.hip, 8 * (n_rot / 2).max(1))?; + let p = buf.addr(); + let (bs, nr) = (base, n_rot as i32); + launch!(self, "rope_freq", cfg((1, 1), 256, 0), p, bs, nr); + self.wait()?; + fr.0.insert((base.to_bits(), n_rot), buf); + Ok(p) + } + + /// `gemvq`; with z = 2 also the matrix of `pair.2` rows at byte offset `pair.0` into the output at byte offset + /// `pair.1` (token stride `pair.2`). + fn gemvq_pair(&self, w: &GpuTensor, x: u64, x_stride: usize, xq: u64, y: u64, y_stride: usize, nt: usize, + pair: (i64, i64, i32), z: u32) -> anyhow::Result<()> { + if !(1..=4).contains(&nt) { bail!("gemvn: {nt} inputs (1 to 4)"); } + let (ncols, k1) = Self::gemv_cols("gemv", w.ty, w.cols)?; + let (mut c, rpw) = Self::gemv_cfg(w.ty, w.rows, w.cols, 1); + let per = c.shared_mem_bytes; + c.shared_mem_bytes = if xq == 0 { per * nt as u32 } else { 0 }; + c.grid_dim.2 = z; + // gemvn caches one x row per token in shared memory; when that exceeds the block's limit, run a token at a time. + if xq == 0 && c.shared_mem_bytes as usize > self.max_smem { + c.shared_mem_bytes = per; + for t in 0..nt { + let (xt, yt) = (x + 4 * t as u64 * x_stride as u64, y + 4 * t as u64 * y_stride as u64); + launch!(self, &k1, c, w.ptr, xt, yt, w.rows as i32, ncols, rpw, xq, pair.0, pair.1, pair.2); + } + return Ok(()); + } + if nt == 1 { + launch!(self, &k1, c, w.ptr, x, y, w.rows as i32, ncols, rpw, xq, pair.0, pair.1, pair.2); + return Ok(()); + } + let kn = k1.replacen("gemv", "gemvn", 1); + launch!(self, &kn, c, w.ptr, x, x_stride as i32, y, y_stride as i32, w.rows as i32, ncols, rpw, nt as i32, xq, pair.0, pair.1, pair.2); + Ok(()) + } + + /// Prefill GEMM over a tile list (or one dense matrix when `tiles` is 0). Without int8 tensor cores the f16 + /// `gemm_*`/`gemms_*` kernels run; `gemm_tc` is compiled out of this build (`GEMM_TC 0`). + fn gemm_raw(&self, ty: GgmlType, rows: usize, cols: usize, tiles: u64, n_tiles: usize, wd: u64, nd: usize, + x: u64, x_stride: usize, _n_x: usize, xrow: u64, y: u64, y_stride: usize, act: i32) -> anyhow::Result<()> { + if cols % 64 != 0 { bail!("{} matrix with {cols} columns: GEMM needs a multiple of 64", ty.name()); } + if n_tiles == 0 { return Ok(()) } + let (same, act) = (act & SAME_X != 0, act & !SAME_X); + let _ = same; + let grid = (rows.div_ceil(64) as u32, n_tiles as u32); + let sm = tiles == 0 && (grid.0 * grid.1 < 112 || nd <= 32); + let grid = if sm { (grid.0, nd.div_ceil(32) as u32) } else { grid }; + launch!(self, &kname(if sm { "gemms" } else { "gemm" }, ty), cfg(grid, 2 * GEMM_BM as u32, 0), + tiles, wd, nd as i32, x, x_stride as i32, xrow, y, y_stride as i32, rows as i32, (cols / 64) as i32, act); + // Tile lists: gemm_* skips the tiles of at most 32 positions, which gemms_* takes. + if tiles != 0 { + launch!(self, &kname("gemms", ty), cfg(grid, 2 * GEMM_BM as u32, 0), + tiles, wd, nd as i32, x, x_stride as i32, xrow, y, y_stride as i32, rows as i32, (cols / 64) as i32, act); + } + Ok(()) + } + + /// Decode attention: `attn_decode_gq` plus `attn_merge`, which also writes `out` quantized into xq. + fn attn(&self, q: u64, kc: u64, vc: u64, qg: u64, out: u64, part: u64, step: u64, nh: usize, nkv: usize, hd: usize, + scale: f32, gq_min: i32, nt: usize, xq: u64, sel: u64, sst: usize, sink: u64, win: usize, kvt: u64, ns1: usize) -> anyhow::Result<()> { + if ![64, 128, 256, 512].contains(&hd) { bail!("attention head_dim {hd} unsupported (64, 128, 256 or 512)"); } + let group = nh / nkv; + let g = [8, 4, 2, 1].into_iter().find(|&g| group % g == 0 && g * hd <= 2048).unwrap(); + let ns = if kvt != 0 { ns1 } else { ATT_SPLITS }; + let pz = (nh * ns * (hd + 2)) as i32; + if gq_min != 0 { + launch!(self, &format!("attn_decode_{hd}"), cfg(((nh * nt) as u32, ns1 as u32), 256, (8 * hd * 4) as u32), + q, kc, vc, part, step, nh as i32, nkv as i32, hd as i32, scale, gq_min, pz, nt as i32, sel, sst as i32, sink, win as i32, kvt); + } + // No cp.async double buffering here: that path is the sm_80+ one (`ATT_RUN_CP`), so the K/V tile comes + // through registers and the kernel needs no extra shared memory. + let g4 = false; + let (name, cp) = if g4 { ("attn_decode_gqa4_128".to_string(), 0) } else { (format!("attn_decode_gqa_{hd}"), 0) }; + if gq_min != i32::MAX { + launch!(self, &name, cfg(((nh / g * nt) as u32, ns as u32), 256, (8 * hd * 4 + cp) as u32), + q, kc, vc, part, step, nh as i32, nkv as i32, hd as i32, scale, gq_min, pz, nt as i32, sel, sst as i32, sink, win as i32, kvt); + } + launch!(self, "attn_merge", LaunchConfig { grid_dim: (nh as u32, 1, nt as u32), block_dim: (256, 1, 1), shared_mem_bytes: 0 }, + part, qg, out, hd as i32, ns as i32, step, ns1 as i32, gq_min, xq, sink); + Ok(()) + } + + fn grid(n: usize) -> LaunchConfig { cfg((n.div_ceil(256) as u32, 1), 256, 0) } +} + +fn alloc_raw(hip: &Arc, bytes: usize) -> anyhow::Result { + let mut p: *mut c_void = std::ptr::null_mut(); + hip.check(unsafe { (hip.malloc)(&mut p, bytes.max(1)) }, "hipMalloc")?; + // The Buf owns the allocation through its address; the free happens when the owner (the backend or the tensor) + // drops, so the owner is a small RAII handle. + struct DevAlloc { hip: Arc, p: *mut c_void } + unsafe impl Send for DevAlloc {} + unsafe impl Sync for DevAlloc {} + impl Drop for DevAlloc { + fn drop(&mut self) { unsafe { (self.hip.free)(self.p) }; } + } + Ok(Buf::new(p as u64, bytes.max(1), DevAlloc { hip: hip.clone(), p })) +} + +fn compile_cached(rtc: &ffi::Rtc, src: &str, arch: &str, tag: &str) -> anyhow::Result> { + let dir = std::env::var_os("XDG_CACHE_HOME").map(Into::into) + .unwrap_or_else(|| std::path::PathBuf::from(std::env::var_os("HOME").unwrap_or_default()).join(".cache")) + .join("rusting_strata"); + let path = dir.join(format!("{:016x}.amdgcn", cache_key(src, arch, tag))); + if let Ok(b) = std::fs::read(&path) { return Ok(b) } + eprintln!("compiling HIP kernels for {arch} with hiprtc {tag} (first run only)"); + let b = rtc.compile(src, "kernels.cu", arch, &[])?; + let _ = std::fs::create_dir_all(&dir).and_then(|_| std::fs::write(&path, &b)); + Ok(b) +} + +/// The kernel names to load: `cuda::kernel_names(false)` has no int8-mma GEMM, which needs no separate list here. +fn kernel_names() -> Vec { crate::cuda::kernel_names(false) } + +impl Backend for Gpu { + fn name(&self) -> &'static str { "hip" } + + fn device(&self) -> String { self.hip.device_name(self.device as i32) } + + fn alloc(&self, bytes: usize) -> anyhow::Result { + let b = alloc_raw(&self.hip, bytes)?; + self.hip.check(unsafe { (self.hip.memset)(b.addr() as *mut c_void, 0, b.len()) }, "hipMemset")?; + Ok(b) + } + + /// Synchronous copy: HIP does not promise that an async copy from pageable memory has staged the host buffer when + /// the call returns, and a caller that reuses `src` (every caller does) cannot wait for that. The stream is + /// drained first so the copy cannot pass kernels already queued that write `dst`. + fn htod(&self, src: &[u8], dst: &Buf, off: usize) -> anyhow::Result<()> { + anyhow::ensure!(off + src.len() <= dst.len(), "htod: {} bytes at {off} into {}", src.len(), dst.len()); + self.wait()?; + let r = unsafe { (self.hip.memcpy)((dst.addr() + off as u64) as *mut c_void, src.as_ptr().cast(), src.len(), ffi::MEMCPY_H2D) }; + self.hip.check(r, "hipMemcpy(htod)") + } + + fn dtoh(&self, src: &Buf, off: usize, dst: &mut [u8]) -> anyhow::Result<()> { + anyhow::ensure!(off + dst.len() <= src.len(), "dtoh: {} bytes at {off} from {}", dst.len(), src.len()); + self.wait()?; + let r = unsafe { (self.hip.memcpy)(dst.as_mut_ptr().cast(), (src.addr() + off as u64) as *const c_void, dst.len(), + ffi::MEMCPY_D2H) }; + self.hip.check(r, "hipMemcpyAsync(dtoh)") + } + + fn dtod(&self, src: &Buf, src_off: usize, dst: &Buf, dst_off: usize, bytes: usize) -> anyhow::Result<()> { + anyhow::ensure!(src_off + bytes <= src.len() && dst_off + bytes <= dst.len(), "dtod: {bytes} bytes out of range"); + let r = unsafe { (self.hip.memcpy_async)((dst.addr() + dst_off as u64) as *mut c_void, + (src.addr() + src_off as u64) as *const c_void, bytes, ffi::MEMCPY_D2D, self.stream) }; + self.hip.check(r, "hipMemcpyAsync(dtod)") + } + + fn memset(&self, dst: &Buf) -> anyhow::Result<()> { + self.hip.check(unsafe { (self.hip.memset)(dst.addr() as *mut c_void, 0, dst.len()) }, "hipMemset") + } + + fn mem_info(&self) -> anyhow::Result<(usize, usize)> { + let (mut free, mut total) = (0usize, 0usize); + self.hip.check(unsafe { (self.hip.mem_get_info)(&mut free, &mut total) }, "hipMemGetInfo")?; + Ok((free, total)) + } + + fn sync(&self) -> anyhow::Result<()> { self.wait() } + + /// Recorded with `hipStreamBeginCapture`: the same launches, replayed by the driver with no host work. + /// Off by default: the forwards allocate inside their step (the q8 cache grows, the rope table is made), and HIP + /// refuses an allocation on a capturing stream ("operation not permitted when stream is capturing"), where CUDA's + /// stream-ordered allocator allows it. `STRATA_HIP_GRAPH=1` turns capture on once the step allocates nothing. + fn graph(&self, key: u64, f: &mut dyn FnMut() -> anyhow::Result<()>) -> anyhow::Result<()> { + if std::env::var_os("STRATA_NO_GRAPH").is_some() || std::env::var_os("STRATA_HIP_GRAPH").is_none() { return f() } + if let Some(g) = self.graphs.lock().unwrap().get(&key) { + let r = unsafe { (self.hip.graph_launch)(g.exec, self.stream) }; + return self.hip.check(r, "hipGraphLaunch"); + } + let mut capturing = 0; + unsafe { (self.hip.stream_is_capturing)(self.stream, &mut capturing) }; + if capturing != 0 { return f() } // never nest captures + self.hip.check(unsafe { (self.hip.stream_begin_capture)(self.stream, ffi::CAPTURE_MODE_THREAD_LOCAL) }, "hipStreamBeginCapture")?; + let r = f(); + let mut graph: ffi::Graph = std::ptr::null_mut(); + let end = unsafe { (self.hip.stream_end_capture)(self.stream, &mut graph) }; + r?; + self.hip.check(end, "hipStreamEndCapture")?; + anyhow::ensure!(!graph.is_null(), "empty HIP graph"); + let mut exec: ffi::GraphExec = std::ptr::null_mut(); + self.hip.check(unsafe { (self.hip.graph_instantiate)(&mut exec, graph, 0) }, "hipGraphInstantiate")?; + self.hip.check(unsafe { (self.hip.graph_launch)(exec, self.stream) }, "hipGraphLaunch")?; + self.graphs.lock().unwrap().insert(key, Graph { exec, graph, hip: self.hip.clone() }); + Ok(()) + } + + /// Pinned host memory mapped into the device address space (the CPU expert worker's mailbox). + fn host_mailbox(&self, words: usize) -> anyhow::Result<(Buf, *mut u32)> { + let n = words.max(1); + let mut host: *mut c_void = std::ptr::null_mut(); + self.hip.check(unsafe { (self.hip.host_malloc)(&mut host, 4 * n, ffi::HOST_MALLOC_PORTABLE | ffi::HOST_MALLOC_MAPPED) }, "hipHostMalloc")?; + let mut dev: *mut c_void = std::ptr::null_mut(); + self.hip.check(unsafe { (self.hip.host_device_ptr)(&mut dev, host, 0) }, "hipHostGetDevicePointer")?; + unsafe { std::ptr::write_bytes(host as *mut u8, 0, 4 * n) }; + struct Pinned { hip: Arc, p: *mut c_void } + unsafe impl Send for Pinned {} + unsafe impl Sync for Pinned {} + impl Drop for Pinned { + fn drop(&mut self) { unsafe { (self.hip.host_free)(self.p) }; } + } + let owner = Pinned { hip: self.hip.clone(), p: host }; + Ok((Buf::new(dev as u64, 4 * n, owner), host.cast())) + } + + fn kv_words(&self, n: usize) -> usize { if self.kv_q8 { n * 17 / 32 } else { n } } + + // ---- kernels ------------------------------------------------------------------------------------------------- + + fn gemm(&self, ty: GgmlType, rows: usize, cols: usize, tiles: u64, n_tiles: usize, x: u64, x_stride: usize, n_x: usize, + xrow: u64, y: u64, y_stride: usize, act: i32) -> anyhow::Result<()> { + self.gemm_raw(ty, rows, cols, tiles, n_tiles, 0, 0, x, x_stride, n_x, xrow, y, y_stride, act) + } + + fn gemm_dense(&self, w: &GpuTensor, n: usize, x: u64, x_stride: usize, y: u64, y_stride: usize, act: i32) -> anyhow::Result<()> { + self.gemm_raw(w.ty, w.rows, w.cols, 0, n.div_ceil(GEMM_BM), w.ptr, n, x, x_stride, n, 0, y, y_stride, act) + } + + fn int8_gemm(&self, _ty: GgmlType) -> bool { false } + + fn gemv(&self, w: &GpuTensor, x: u64, y: u64) -> anyhow::Result<()> { + let (ncols, kn) = Self::gemv_cols("gemv", w.ty, w.cols)?; + let (c, rpw) = Self::gemv_cfg(w.ty, w.rows, w.cols, 1); + launch!(self, &kn, c, w.ptr, x, y, w.rows as i32, ncols, rpw, 0u64, 0i64, 0i64, 0i32); + Ok(()) + } + + fn gemvn(&self, w: &GpuTensor, x: u64, x_stride: usize, y: u64, y_stride: usize, nt: usize) -> anyhow::Result<()> { + self.gemvq(w, x, x_stride, 0, y, y_stride, nt) + } + + fn gemvq(&self, w: &GpuTensor, x: u64, x_stride: usize, xq: u64, y: u64, y_stride: usize, nt: usize) -> anyhow::Result<()> { + self.gemvq_pair(w, x, x_stride, xq, y, y_stride, nt, (0, 0, 0), 1) + } + + fn gemvq2(&self, a: &GpuTensor, b: &GpuTensor, x: u64, x_stride: usize, xq: u64, ya: u64, yb: u64, nt: usize) -> anyhow::Result<()> { + if a.ty != b.ty || a.cols != b.cols { + self.gemvq(a, x, x_stride, xq, ya, a.rows, nt)?; + return self.gemvq(b, x, x_stride, xq, yb, b.rows, nt); + } + let ((a, ya), (b, yb)) = if a.rows >= b.rows { ((a, ya), (b, yb)) } else { ((b, yb), (a, ya)) }; + self.gemvq_pair(a, x, x_stride, xq, ya, a.rows, nt, (b.ptr as i64 - a.ptr as i64, yb as i64 - ya as i64, b.rows as i32), 2) + } + + fn moe_gemv(&self, ty: GgmlType, rows: usize, cols: usize, w: u64, stride: usize, ids: u64, k: usize, x: u64, x_stride: usize, + xg: usize, y: u64, pair: Option<(i64, i64)>, xq: u64) -> anyhow::Result<()> { + let (ncols, kn) = Self::gemv_cols("moe_gemv", ty, cols)?; + let (mut c, mut rpw) = Self::gemv_cfg(ty, rows, cols, k); + if rpw == 1 && !Self::float_ty(ty) { + rpw = 2; + c.grid_dim.0 = rows.div_ceil(2 * (Self::gemv_block(k) as usize / 32)) as u32; + } + let (w2, y2) = pair.unwrap_or((0, 0)); + c.grid_dim.2 = if pair.is_some() { 2 } else { 1 }; + if xq != 0 { c.shared_mem_bytes = 0; } + launch!(self, &kn, c, w, ids, stride as i64, x, x_stride as i32, xg as i32, y, rows as i32, ncols, rpw, w2, y2, xq); + Ok(()) + } + + fn dequant(&self, w: &GpuTensor, rows: usize, out: u64) -> anyhow::Result<()> { + launch!(self, &kname("dequant", w.ty), cfg((rows as u32, 1), 256, 0), w.ptr, out, Self::gemv_cols("dequant", w.ty, w.cols)?.0); + Ok(()) + } + + fn quant_xq(&self, x: u64, x_stride: usize, n: usize, nt: usize, out: u64) -> anyhow::Result<()> { + launch!(self, "quant_xq", cfg((nt as u32, 1), 256, 0), x, x_stride as i32, n as i32, out); + Ok(()) + } + + fn rms_norm(&self, x: u64, x_stride: usize, w: u64, out: u64, out_stride: usize, n: usize, rows: usize, eps: f32) -> anyhow::Result<()> { + self.rms_norm_q(x, x_stride, w, out, out_stride, n, rows, eps, 0, 0) + } + + fn rms_norm_q(&self, x: u64, x_stride: usize, w: u64, out: u64, out_stride: usize, n: usize, rows: usize, eps: f32, xq: u64, res: u64) -> anyhow::Result<()> { + launch!(self, "rms_norm", cfg((rows as u32, 1), 512, 0), x, x_stride as i32, w, out, out_stride as i32, n as i32, eps, xq, res, 1i32); + Ok(()) + } + + fn rms_norm_streams(&self, x: u64, w: u64, out: u64, n: usize, hc: usize, nt: usize, eps: f32) -> anyhow::Result<()> { + launch!(self, "rms_norm", cfg(((nt * hc) as u32, 1), 512, 0), x, n as i32, w, out, n as i32, n as i32, eps, 0u64, 0u64, hc as i32); + Ok(()) + } + + fn argmax_rows(&self, x: u64, n: usize, rows: usize, out: u64) -> anyhow::Result<()> { + let part = self.ptr(&self.am); + anyhow::ensure!(rows * AMAX_PARTS <= self.am.len(), "argmax_rows: {rows} rows"); + launch!(self, "argmax_part", cfg((AMAX_PARTS as u32, rows as u32), 256, 0), x, n as i32, part); + launch!(self, "argmax_rows", cfg((rows as u32, 1), AMAX_PARTS as u32, 0), part, n as i32, out); + Ok(()) + } + + fn l2_norm(&self, x: u64, n: usize, per: usize, stride: usize, rows: usize, eps: f32) -> anyhow::Result<()> { + launch!(self, "l2_norm", cfg((rows as u32, 1), 128, 0), x, n as i32, per as i32, stride as i32, eps); + Ok(()) + } + + fn rope_neox(&self, x: u64, stride: usize, heads: usize, per: usize, n_rot: usize, step: u64, base: f32) -> anyhow::Result<()> { + launch!(self, "rope_neox", cfg(((heads / per) as u32, 1), (n_rot / 2) as u32, 0), x, stride as i32, per as i32, n_rot as i32, step, base); + Ok(()) + } + + fn rms_norm_rope(&self, x: u64, x_stride: usize, w: u64, out: u64, n: usize, rows: usize, eps: f32, per: usize, n_rot: usize, step: u64, base: f32) -> anyhow::Result<()> { + self.rms_norm_rope_kv(x, x_stride, w, out, n, rows, eps, per, n_rot, step, base, 0, 0, 0) + } + + fn rms_norm_rope_kv(&self, x: u64, x_stride: usize, w: u64, out: u64, n: usize, rows: usize, eps: f32, per: usize, n_rot: usize, + step: u64, base: f32, v: u64, kc: u64, vc: u64) -> anyhow::Result<()> { + anyhow::ensure!(n_rot <= n.min(512) && n % 32 == 0, "rms_norm_rope: head of {n}, n_rot {n_rot}"); + let fr = self.rope_fr(base, n_rot)?; + launch!(self, "rms_norm_rope", cfg((rows as u32, 1), 256, 0), x, x_stride as i32, w, out, n as i32, eps, per as i32, n_rot as i32, + step, base, v, kc, vc, 0i32, 0u64, 0i32, 0u64, 0u64, 0i32, fr, 0u64); + Ok(()) + } + + fn rms_norm_rope_qk(&self, q: u64, q_stride: usize, qw: u64, qo: u64, qrows: usize, qper: usize, k: u64, kw: u64, ko: u64, + krows: usize, kper: usize, n: usize, eps: f32, n_rot: usize, step: u64, base: f32, v: u64, kc: u64, vc: u64) -> anyhow::Result<()> { + anyhow::ensure!(n_rot <= n.min(512) && n % 32 == 0, "rms_norm_rope: head of {n}, n_rot {n_rot}"); + let fr = self.rope_fr(base, n_rot)?; + launch!(self, "rms_norm_rope", cfg(((qrows + krows) as u32, 1), 256, 0), k, n as i32, kw, ko, n as i32, eps, kper as i32, n_rot as i32, + step, base, v, kc, vc, qrows as i32, q, q_stride as i32, qw, qo, qper as i32, fr, 0u64); + Ok(()) + } + + fn kv_rows(&self) -> bool { true } + + fn rms_norm_rope_qk_rows(&self, q: u64, q_stride: usize, qw: u64, qo: u64, nh: usize, k: u64, kw: u64, ko: u64, nkv: usize, + hd: usize, eps: f32, n_rot: usize, step: u64, base: f32, v: u64, kvt: u64, nt: usize) -> anyhow::Result<()> { + anyhow::ensure!(n_rot <= hd.min(512) && hd % 32 == 0, "rms_norm_rope: head of {hd}, n_rot {n_rot}"); + let fr = self.rope_fr(base, n_rot)?; + launch!(self, "rms_norm_rope", cfg(((nt * (nh + nkv)) as u32, 1), 256, 0), k, hd as i32, kw, ko, hd as i32, eps, nkv as i32, n_rot as i32, + step, base, v, 0u64, 0u64, (nt * nh) as i32, q, q_stride as i32, qw, qo, nh as i32, fr, kvt); + Ok(()) + } + + fn attn_rows(&self, q: u64, qg: u64, out: u64, part: u64, step: u64, nh: usize, nkv: usize, hd: usize, scale: f32, nt: usize, + sink: u64, win: usize, kvt: u64, splits: usize) -> anyhow::Result<()> { + self.attn(q, 0, 0, qg, out, part, step, nh, nkv, hd, scale, 0, nt, 0, 0, 0, sink, win, kvt, splits) + } + + fn add(&self, x: u64, y: u64, n: usize) -> anyhow::Result<()> { + launch!(self, "add", Self::grid(n), x, y, n as i32); + Ok(()) + } + + fn swiglu(&self, g: u64, u: u64, n: usize) -> anyhow::Result<()> { + launch!(self, "swiglu", Self::grid(n), g, u, n as i32); + Ok(()) + } + + fn swiglu_q(&self, g: u64, u: u64, n: usize, rows: usize, xq: u64) -> anyhow::Result { + launch!(self, "swiglu_q", cfg((n.div_ceil(256) as u32, rows as u32), 32, 0), g, u, n as i32, xq); + Ok(xq) + } + + fn ssm_gates(&self, beta: u64, g: u64, dt_bias: u64, a: u64, n: usize, nv: usize) -> anyhow::Result<()> { + launch!(self, "ssm_gates", Self::grid(n), beta, g, dt_bias, a, n as i32, nv as i32); + Ok(()) + } + + fn conv_silu(&self, qkv: u64, state: u64, w: u64, y: u64, ch: usize, kw: usize, nn: usize, eps: f32) -> anyhow::Result<()> { + launch!(self, "conv_silu", cfg((ch.div_ceil(128) as u32, 1), 128, 0), qkv, state, w, y, ch as i32, kw as i32, nn as i32, eps); + Ok(()) + } + + fn deltanet(&self, y: u64, s: u64, beta: u64, g: u64, dt_bias: u64, a: u64, o: u64, nk: usize, nv: usize, interleave: bool, + dk: usize, dv: usize, scale: f32, t: usize, ych: usize, snap: u64, nsnap: usize) -> anyhow::Result<()> { + let rows = 512 / dk.max(1); + anyhow::ensure!(matches!(dk, 32 | 64 | 128 | 256) && dv % rows == 0, "deltanet: head dims {dk}/{dv} unsupported"); + launch!(self, "deltanet_seq", cfg((nv as u32, dv.div_ceil(8 * rows) as u32), 256, 0), + y, s, beta, g, o, nk as i32, nv as i32, interleave as i32, dk as i32, dv as i32, scale, t as i32, ych as i32, + snap, nsnap as i32, dt_bias, a); + Ok(()) + } + + fn conv_seq(&self, qkv: u64, state: u64, w: u64, y: u64, ch: usize, kw: usize, t: usize, snap: u64, nsnap: usize) -> anyhow::Result<()> { + launch!(self, "conv_seq", Self::grid(t * ch), qkv, state, w, y, ch as i32, kw as i32, t as i32); + launch!(self, "conv_state", Self::grid(ch), qkv, state, ch as i32, kw as i32, t as i32, snap, nsnap as i32); + Ok(()) + } + + fn attn_prefill_m(&self, q: u64, kc: u64, vc: u64, qg: u64, out: u64, step: u64, t: usize, nh: usize, nkv: usize, hd: usize, + scale: f32, qm: u64, mw: usize, sink: u64, win: usize) -> anyhow::Result<()> { + if !matches!(hd, 64 | 128 | 256) { bail!("attention prefill: head_dim {hd} unsupported (64, 128 or 256)"); } + // A tile of FA_BK keys needs 72 KiB at head_dim 256, more than a 64 KiB block may use on RDNA; 16 keys a + // tile (the depth the CUDA build uses on Turing's 64 KB blocks) fits, at the cost of more passes. + let bk = [FA_BK, 16, 8].into_iter().find(|&bk| attn_prefill_smem_bk(hd, bk) <= self.max_smem) + .with_context(|| format!("attn_prefill_{hd}: no tile depth fits {} B of shared memory", self.max_smem))?; + let smem = attn_prefill_smem_bk(hd, bk) as u32; + launch!(self, &format!("attn_prefill_{hd}"), cfg((t.div_ceil(64) as u32, nh as u32), 128, smem), + q, kc, vc, qg, out, step, t as i32, nh as i32, nkv as i32, scale, qm, mw as i32, sink, win as i32); + Ok(()) + } + + fn qsa_pool(&self, ik: u64, ring: u64, pool: u64, w: u64, step: u64, t: usize, n_rot: usize, base: f32, eps: f32) -> anyhow::Result<()> { + launch!(self, "qsa_pool", cfg(((t / 4 + 1) as u32, 1), 128, 0), ik, ring, pool, w, step, t as i32, n_rot as i32, base, eps); + Ok(()) + } + + fn qsa_select(&self, q: u64, pool: u64, score: u64, sel: u64, mask: u64, step: u64, r0: usize, rows: usize, nbs: usize, top: usize, sst: usize, mw: usize) -> anyhow::Result<()> { + launch!(self, "qsa_score", cfg((64, rows.div_ceil(8) as u32), 256, 0), q, pool, score, step, r0 as i32, rows as i32, nbs as i32, top as i32); + launch!(self, "qsa_select", cfg((rows as u32, 1), 1024, 0), score, sel, mask, step, r0 as i32, nbs as i32, top as i32, sst as i32, mw as i32); + Ok(()) + } + + fn moe_combine_seq(&self, x: u64, ye: u64, wts: u64, inv: u64, k: usize, sh: u64, sg: u64, n: usize, t: usize) -> anyhow::Result<()> { + launch!(self, "moe_combine_seq", Self::grid(n * t), x, ye, wts, inv, k as i32, sh, sg, n as i32, t as i32); + Ok(()) + } + + fn norm_gate(&self, o: u64, w: u64, z: u64, n: usize, heads: usize, eps: f32) -> anyhow::Result<()> { + self.norm_gate_q(o, w, z, n, heads, eps, 0).map(|_| ()) + } + + fn norm_gate_q(&self, o: u64, w: u64, z: u64, n: usize, heads: usize, eps: f32, xq: u64) -> anyhow::Result { + let xq = if crate::cuda::llama_numerics() || n % 32 != 0 { 0 } else { xq }; + launch!(self, "norm_gate", cfg((heads as u32, 1), 128, 0), o, w, z, n as i32, eps, xq, 0i32); + Ok(xq) + } + + fn norm_gate_sig(&self, o: u64, w: u64, z: u64, n: usize, heads: usize, eps: f32, xq: u64) -> anyhow::Result { + let xq = if crate::cuda::llama_numerics() || n % 32 != 0 { 0 } else { xq }; + launch!(self, "norm_gate", cfg((heads as u32, 1), 128, 0), o, w, z, n as i32, eps, xq, 1i32); + Ok(xq) + } + + fn hc_silu(&self, x: u64, sc: f32, n: usize) -> anyhow::Result<()> { + launch!(self, "hc_silu", Self::grid(n), x, sc, n as i32); + Ok(()) + } + + fn hc_mix(&self, xn: u64, g: u64, out: u64, n: usize, hc: usize, nt: usize) -> anyhow::Result<()> { + launch!(self, "hc_mix", cfg((n.div_ceil(256) as u32, nt as u32), 256, 0), xn, g, out, n as i32, hc as i32); + Ok(()) + } + + fn hc_write(&self, r: u64, out: u64, inj: u64, n: usize, hc: usize, nt: usize, clear: bool) -> anyhow::Result<()> { + launch!(self, "hc_write", cfg((n.div_ceil(256) as u32, nt as u32), 256, 0), r, out, inj, n as i32, hc as i32, clear as i32); + Ok(()) + } + + fn ple_gate(&self, key: u64, query: u64, value: u64, gated: u64, n: usize, hc: usize, nt: usize) -> anyhow::Result<()> { + launch!(self, "ple_gate", cfg((hc as u32, nt as u32), 256, 0), key, query, value, gated, n as i32); + Ok(()) + } + + fn ple_conv(&self, r: u64, gated: u64, norm: u64, kw: u64, ring: u64, step: u64, d: usize, nt: usize) -> anyhow::Result<()> { + launch!(self, "ple_conv", Self::grid(d), r, gated, norm, kw, ring, step, d as i32, nt as i32); + Ok(()) + } + + fn kv_store(&self, k: u64, v: u64, kc: u64, vc: u64, n: usize, t: usize, step: u64, hd: usize) -> anyhow::Result<()> { + anyhow::ensure!(!self.kv_q8 || (hd % 32 == 0 && n % hd == 0), "q8 KV cache: head_dim {hd} is not a multiple of 32"); + launch!(self, "kv_store", Self::grid(n * t), k, v, kc, vc, n as i32, (n * t) as i32, step, hd as i32); + Ok(()) + } + + fn attn_decode_gq(&self, q: u64, kc: u64, vc: u64, qg: u64, out: u64, part: u64, step: u64, nh: usize, nkv: usize, hd: usize, + scale: f32, gq_min: i32, nt: usize, sink: u64, win: usize) -> anyhow::Result<()> { + self.attn(q, kc, vc, qg, out, part, step, nh, nkv, hd, scale, gq_min, nt, 0, 0, 0, sink, win, 0, ATT_SPLITS_1) + } + + fn attn_decode_q(&self, q: u64, kc: u64, vc: u64, qg: u64, out: u64, part: u64, step: u64, nh: usize, nkv: usize, hd: usize, + scale: f32, gq_min: i32, nt: usize, xq: u64, sel: u64, sst: usize, sink: u64, win: usize) -> anyhow::Result { + let xq = if crate::cuda::llama_numerics() { 0 } else { xq }; + self.attn(q, kc, vc, qg, out, part, step, nh, nkv, hd, scale, gq_min, nt, xq, sel, sst, sink, win, 0, ATT_SPLITS_1)?; + Ok(xq) + } + + fn router_topk(&self, p: u64, n: usize, k: usize, extra_scale: f32, ids: u64, wts: u64, t: usize, sigmoid: bool) -> anyhow::Result<()> { + anyhow::ensure!(n <= 512 && k <= 32, "router_topk: {n} experts, top {k}"); + launch!(self, "router_topk", cfg((t as u32, 1), 32, 0), p, n as i32, k as i32, extra_scale, ids, wts, sigmoid as i32); + Ok(()) + } + + fn moe_route(&self, p: u64, n: usize, k: usize, extra_scale: f32, table: u64, ids: u64, wts: u64, slots: u64, wh: u64, h: u64, + mb: u64, nh: usize, h_off: usize, step: u64, t: usize, pid: u64, sigmoid: bool) -> anyhow::Result<()> { + anyhow::ensure!(n <= 512 && k <= 32, "moe_route: {n} experts, top {k}"); + launch!(self, "moe_route", cfg((1, 1), 256, 0), p, n as i32, k as i32, extra_scale, table, ids, wts, slots, wh, h, mb, + nh as i32, h_off as i32, step, t as i32, pid, sigmoid as i32); + Ok(()) + } + + fn moe_mailbox_optional(&self) -> bool { true } + fn moe_prefetch_supported(&self) -> bool { false } + + fn moe_combine(&self, x: u64, ye: u64, w: u64, k: usize, sh: u64, sg: u64, mb: u64, y_off: usize, step: u64, slots: u64, n: usize, t: usize) -> anyhow::Result<()> { + let mut c = Self::grid(n); + c.grid_dim.1 = t as u32; + launch!(self, "moe_combine", c, x, ye, w, k as i32, sh, sg, mb, y_off as i32, step, slots, n as i32); + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The whole plumbing on the device: allocate, upload, launch a real kernel, read it back. `add` is the + /// simplest kernel in the file, so a failure here is the backend, not the math. + #[test] + fn add_kernel_round_trips() { + let g = match Gpu::new(0) { + Ok(g) => g, + Err(e) => { + eprintln!("skipping: HIP unavailable: {e:#}"); + return; + } + }; + let n = 1024; + let x: Vec = (0..n).map(|i| i as f32).collect(); + let y: Vec = (0..n).map(|i| 0.5 * i as f32).collect(); + let want: Vec = (0..n).map(|i| 1.5 * i as f32).collect(); + let g: &dyn Backend = &g; + let bx = g.alloc(4 * n).unwrap(); + let by = g.alloc(4 * n).unwrap(); + g.put(&x, &bx, 0).unwrap(); + g.put(&y, &by, 0).unwrap(); + // `Backend::add` is x += y, so the result lands in x. + g.add(bx.addr(), by.addr(), n).unwrap(); + g.sync().unwrap(); + let got: Vec = g.get(&bx, 0, n).unwrap(); + assert!(got.iter().zip(&want).all(|(a, b)| a == b), "first mismatch at {:?}", got.iter().zip(&want).position(|(a, b)| a != b)); + } + + /// `norm_gate` with the quantize-to-int8 epilogue: the first kernel of the qwen35 attention layer, and the one + /// that faulted first on the card, so it gets its own comparison against the reference math. + #[test] + fn norm_gate_matches_the_reference() { + let g = match Gpu::new(0) { Ok(g) => g, Err(e) => { eprintln!("skipping: HIP unavailable: {e:#}"); return } }; + let (heads, n) = (4usize, 128usize); + let mut st = 12345u32; + let mut rnd = || { st = st.wrapping_mul(1664525).wrapping_add(1013904223); (st >> 8) as f32 / 16777216.0 - 0.5 }; + let o: Vec = (0..heads * n).map(|_| rnd()).collect(); + let w: Vec = (0..n).map(|_| rnd() + 1.0).collect(); + let z: Vec = (0..heads * n).map(|_| rnd()).collect(); + let want: Vec = (0..heads).flat_map(|h| { + let row = &o[h * n..(h + 1) * n]; + let ss: f32 = row.iter().map(|v| v * v).sum(); + let sc = 1.0 / (ss / n as f32 + 1e-6).sqrt(); + let silu = |v: f32| v / (1.0 + (-v).exp()); + (0..n).map(|i| row[i] * sc * w[i] * silu(z[h * n + i])).collect::>() + }).collect(); + let gx = g.alloc(4 * heads * n).unwrap(); + let gw = g.alloc(4 * n).unwrap(); + let gz = g.alloc(4 * heads * n).unwrap(); + let xq_bytes = heads * n + heads * n / 32 * 4; + let gxq = g.alloc(xq_bytes).unwrap(); + let g: &dyn Backend = &g; + g.put(&o, &gx, 0).unwrap(); + g.put(&w, &gw, 0).unwrap(); + g.put(&z, &gz, 0).unwrap(); + g.norm_gate(gx.addr(), gw.addr(), gz.addr(), n, heads, 1e-6).unwrap(); + g.sync().unwrap(); + eprintln!("plain norm_gate ok: {:?}", &g.get::(&gx, 0, 2).unwrap()); + g.put(&o, &gx, 0).unwrap(); + g.norm_gate_q(gx.addr(), gw.addr(), gz.addr(), n, heads, 1e-6, gxq.addr()).unwrap(); + g.sync().unwrap(); + let got: Vec = g.get(&gx, 0, heads * n).unwrap(); + let worst = got.iter().zip(&want).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); + assert!(worst < 2e-5, "max |diff| = {worst}"); + } + + /// The generated source compiles for this device through hiprtc (the CUDA source with `STRATA_HIP` taken). + #[test] + fn hiprtc_compiles_the_kernels() { + let Some(rtc) = ffi::Rtc::get() else { + eprintln!("skipping: no hiprtc"); + return; + }; + let Ok(hip) = ffi::Hip::open() else { + eprintln!("skipping: no HIP runtime"); + return; + }; + let arch = hip.arch(0).unwrap(); + rtc.compile(&source(false), "kernels.cu", &arch, &[]).expect("hiprtc compiles kernels.cu for the device"); + } +} diff --git a/src/lib.rs b/src/lib.rs index 96f17186..24f7f6dd 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -9,6 +9,7 @@ pub mod model; pub mod backend; pub mod cuda; pub mod vulkan; +pub mod hip; pub mod gpu_model; pub mod cpu_moe; pub mod expert_cache; From 4a670a1377e5f2bdd5459aa9fcc32415d4b1e321 Mon Sep 17 00:00:00 2001 From: Hannes Klas Date: Mon, 16 Nov 2026 14:44:41 +0100 Subject: [PATCH 005/515] hip: prefill on the card's matrix cores (gfx11/gfx12 WMMA) gemm_q takes an AMD branch under GEMM_WMMA: D[16x16] += A * B^T through __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12 (the gfx11 form on RDNA3). Both operands are 16 rows of 16 halves, which is how the kernel already stages X (positions) and W (output rows) in shared memory, so the tile loop and the epilogue keep their shape: a warp owns 32x32 outputs (2x2 tiles) in the big-tile kernel and 16x16 in the small-tile one; a lane supplies 8 halves of its own row of each operand (gfx12 splits k across the two half-waves) and holds 8 results, column lane & 15, rows 8*(lane >> 4) + i. Preflight on RX 9070 XT, Qwen3.6-35B-A3B UD-Q4_K_XL, pp 1024: 737 -> 1684 tok/s without MTP and 1569 with it, against 1428 for the Vulkan backend; pp 4096: 2106 tok/s. Greedy output is bit-identical to the CUDA-core prefill on 5 of 6 prompts, and the sixth differs at a near-tie (f16 tensor-core summation order), the same class of difference the CUDA and Vulkan backends have. kernels.cu keeps one source: the whole path is behind #if GEMM_WMMA, which is undefined for the CUDA build. The preprocessed CUDA source is unchanged for GEMM_TC 0/1 x KV_Q8 0/1 x arch 700/750/800/900 (checked by diffing clang -E output before and after). STRATA_HIP_WMMA=0 selects the CUDA-core multiplications, for A/B and as a workaround. --- docs/HIP.md | 38 +++++++++++++++++++++------------ src/cuda/kernels.cu | 52 +++++++++++++++++++++++++++++++++++++++++++-- src/hip/compat.h | 41 +++++++++++++++++++++++++++++++++++ src/hip/mod.rs | 45 ++++++++++++++++++++++++++++++++++++++- 4 files changed, 160 insertions(+), 16 deletions(-) diff --git a/docs/HIP.md b/docs/HIP.md index d237139f..62fc05e6 100644 --- a/docs/HIP.md +++ b/docs/HIP.md @@ -4,9 +4,11 @@ build step: the kernels are compiled at run time by hiprtc and launched through the HIP runtime, both loaded by name (`libamdhip64.so`, `libhiprtc.so`), the way `src/cuda` loads NVRTC. `cargo build --release` is the whole build. -**Status: experimental.** Brought up on Qwen3.6-35B-A3B (RX 9070 XT, gfx1201, ROCm 7.2). Greedy output is identical to -the Vulkan backend on the prompts tried. Not yet ported: matrix cores (prefill runs the f16 CUDA-core path, not WMMA), -graph capture (off by default), and the host-side pipeline details of the CUDA backend (ring staging, side stream). +**Status: experimental.** Brought up on Qwen3.6-35B-A3B (RX 9070 XT, gfx1201, ROCm 7.2.3). Greedy output matches the +other backends: identical to the Vulkan backend on 3 of 4 prompts, and to its own CUDA-core prefill on 5 of 6, with the +difference at a near-tie where the f16 tensor-core summation order picks another token (the same class of difference the +CUDA and Vulkan backends have). Not yet ported: graph capture (off by default) and the host-side pipeline details of the +CUDA backend (pinned ring staging, side stream). ## What runs @@ -14,12 +16,13 @@ Everything the Vulkan backend runs, through the same kernels: | | HIP | Vulkan (same machine, same model) | |---|---|---| -| Greedy tokens, 3 prompts | identical | identical | -| Prefill, pp 1024 | 492 tok/s | 1458 tok/s | -| Decode, tg 48, `--mtp 2` | 159 tok/s | 232 tok/s | +| Prefill, pp 1024, `--mtp 2` | 1569 tok/s | 1428 tok/s | +| Prefill, pp 4096, `--mtp 2` | 2106 tok/s | (not run) | +| Decode, tg 48, `--mtp 2` | 173 tok/s | 231 tok/s | -Qwen3.6-35B-A3B UD-Q4_K_XL, `--ctx 4096 --vram-margin 256`, RX 9070 XT, Ryzen 7 5700X. Decode is within 1.5x of -Vulkan; prefill is 3x behind because the prefill GEMM has no matrix-core path on HIP yet (see below). +Qwen3.6-35B-A3B UD-Q4_K_XL, `--ctx 4096 --vram-margin 256`, RX 9070 XT, Ryzen 7 5700X, one process each. Prefill runs on +the card's matrix cores (below) and is at parity with Vulkan; decode is 1.3x behind, which is the host side (no graph +capture, no side stream) rather than the kernels. ## How it works @@ -30,6 +33,14 @@ Vulkan; prefill is 3x behind because the prefill GEMM has no matrix-core path on instead of `mma.sync`. - The kernels compile as **wave32** (lane = `threadIdx.x & 31`), which is the default wavefront size on RDNA and the assumption the CUDA source already makes about a warp. The backend refuses a device that reports a 64-wide wave. +- **Matrix cores**: the prefill GEMM (`gemm_q` in `kernels.cu`) takes an AMD branch under `GEMM_WMMA`: `D[16x16] += + A * B^T` through `__builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12` (the gfx11 form on RDNA3). Both operands are rows + of 16 halves, which is exactly how the kernel stages X (positions) and W (output rows) in shared memory — no + transpose, and the same tile loop and epilogue shape as the CUDA path. A warp owns 32x32 outputs (2x2 tiles) in the + big-tile kernel and 16x16 in the small-tile one; a lane supplies 8 halves of its own row of each operand (gfx12 + splits the k dimension across the two half-waves) and holds 8 results, column `lane & 15`, rows `8*(lane>>4) + i`. + `STRATA_HIP_WMMA=0` falls back to the CUDA-core multiplications: 737 -> 1684 tok/s prefill at pp 1024 on the RX 9070 + XT, and 5 of 6 prompts bit-identical between the two. - `src/cuda/kernels.cu` keeps one source for both backends: the few places that cannot be shared are behind `#if STRATA_HIP` (f16 conversions, the per-lane fragment loads, `mma884`, the KV f16x2 math, the L2 prefetch hint), so the CUDA build's preprocessed source is unchanged. @@ -50,14 +61,15 @@ Vulkan; prefill is 3x behind because the prefill GEMM has no matrix-core path on - `STRATA_HIP_GRAPH=1` turns on graph capture once the forward allocates nothing inside a step (HIP refuses an allocation on a capturing stream; CUDA's stream-ordered allocator allows it). - `STRATA_NO_GRAPH=1` turns capture off for both GPU backends. +- `STRATA_HIP_WMMA=0` uses the CUDA-core multiplications in the prefill GEMM instead of the matrices cores. ## Next -1. gfx12 WMMA (`__builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12` and its int8 form) for the prefill GEMM: the 3x - prefill gap is exactly the missing matrix-core path. -2. Graph capture: move the per-step allocations (q8 cache growth, rope table) out of the captured region. -3. The CUDA host-side pipeline: a pinned ring for `htod` (expert streaming during prefill) and a side stream for - `beside`. +1. Graph capture: move the per-step allocations (q8 cache growth, rope table) out of the captured region; that and the + side stream are where the remaining decode gap is. +2. The int8 WMMA form (`__builtin_amdgcn_wmma_i32_16x16x16_iu8`) for the integer-weight prefill GEMM, which today takes + the f16 path (`GEMM_TC 0`): less shared-memory traffic per output than the sm_80-style int8 `gemmi_*` kernels. +3. A pinned ring for `htod` so expert streaming during prefill does not sync the stream per tensor. ## Credits diff --git a/src/cuda/kernels.cu b/src/cuda/kernels.cu index 3c90061c..82a03d1f 100644 --- a/src/cuda/kernels.cu +++ b/src/cuda/kernels.cu @@ -1059,6 +1059,10 @@ __device__ __forceinline__ void gemm_q(const GemmTile* tiles, const u8* wd, int #if __CUDA_ARCH__ < 800 && GEMM_TC // Same 32 f32 storage as acc, seen as 4 m8 tiles x 8 D registers: accv[j][i] == &acc[0][0][0][j*8+i]. float (&accv)[4][8] = reinterpret_cast(acc); +#endif +#if GEMM_WMMA + // The same 32 f32 as 4 WMMA tiles of 8 results: accw[t][i] is tile t, result i of this lane. + float (&accw)[4][8] = reinterpret_cast(acc); #endif // W step kb is decoded into registers (as halves) during step kb - 1's mma and stored after it. constexpr int WQ = 64 * SUBS / NT; @@ -1101,7 +1105,30 @@ __device__ __forceinline__ void gemm_q(const GemmTile* tiles, const u8* wd, int if (wm < tl.cnt) #pragma unroll for (int kk = 0; kk < BK; kk += 16) { -#if __CUDA_ARCH__ < 800 && GEMM_TC +#if GEMM_WMMA + // AMD matrix cores: the tile in xs (positions, rows = m) and ws (rows = n) is fed straight in as A and B + // of D[16x16] += A * B^T. A warp owns MT x NT 16x16 tiles: (32 positions, 32 rows) for the big kernel and + // (16 positions, 64 rows) for the small-tile one. Each lane holds 8 results of every tile. + const int l16 = lane & 15, w0 = STRATA_WMMA_K0(lane); + constexpr int MT = SM ? 1 : 2, NTW = SM ? 1 : 2; + strata_hip::strata_hk wa[MT], wb[NTW]; +#pragma unroll + for (int mt = 0; mt < MT; mt++) wa[mt] = strata_hip::strata_ld_wmma(xs + (wm + mt * 16 + l16) * P + kk + w0); +#pragma unroll + for (int nt = 0; nt < NTW; nt++) wb[nt] = strata_hip::strata_ld_wmma(ws + (wn + nt * 16 + l16) * P + kk + w0); +#pragma unroll + for (int mt = 0; mt < MT; mt++) +#pragma unroll + for (int nt = 0; nt < NTW; nt++) { + float* t = accw[mt * NTW + nt]; + strata_hip::strata_f8 c, r; +#pragma unroll + for (int i = 0; i < 8; i++) c[i] = t[i]; + r = strata_hip::strata_wmma(wa[mt], wb[nt], c); +#pragma unroll + for (int i = 0; i < 8; i++) t[i] = r[i]; + } +#elif __CUDA_ARCH__ < 800 && GEMM_TC // Volta: eight m8n8k4 ops replace one m16n8k16 for the same 16-deep k step. The four computations of // each instruction are selected by c = g & 3: SM == false maps them to the four n8 tiles (m8 = j, n8 = // c, 32 f32 per lane in accv[0..3]); SM == true maps them to the four 8x8 quadrants of the 16x16 warp @@ -1141,7 +1168,28 @@ __device__ __forceinline__ void gemm_q(const GemmTile* tiles, const u8* wd, int __syncthreads(); if (kb + 1 < nk) stw(); } -#if __CUDA_ARCH__ < 800 && GEMM_TC +#if GEMM_WMMA + // D layout of the AMD WMMA: lane 16*(lane>>4) keeps column lane & 15 and rows 8*(lane>>4) .. +7 of each tile. + { + const int l16 = lane & 15, wl = lane >> 4; + constexpr int MT = SM ? 1 : 2, NTW = SM ? 1 : 2; +#pragma unroll + for (int mt = 0; mt < MT; mt++) +#pragma unroll + for (int nt = 0; nt < NTW; nt++) { + int n = n0 + wn + nt * 16 + l16; + if (n >= rows) continue; +#pragma unroll + for (int i = 0; i < 8; i++) { + int r = wm + mt * 16 + 8 * wl + i; + if (r >= tl.cnt) continue; + float* yr = y + (size_t)(tl.m0 + r) * y_stride; + float v = accw[mt * NTW + nt][i]; + yr[n] = act == 0 ? v : act == 1 ? silu(yr[n]) * v : yr[n] + v; + } + } + } +#elif __CUDA_ARCH__ < 800 && GEMM_TC // m8n8k4 D layout (PTX ISA 8.5 §9.7.13.4.1): register i = 4*p4 + 2*p2 + e sits at row (t & 1) + 2*p2 + 4*hi // and column (t & 2) + 4*p4 + e of the 8x8 tile. For each fixed c, lanes {4c..4c+3} and {16+4c..19+4c} cover // that tile exactly once; the tile itself is picked by c (n8 = c) and j (m8 = j), or by c alone for SM. diff --git a/src/hip/compat.h b/src/hip/compat.h index 7e37eed8..f0f676ab 100644 --- a/src/hip/compat.h +++ b/src/hip/compat.h @@ -85,6 +85,47 @@ template __device__ __forceinline__ T shfl_sync(unsigned, T v, int __device__ __forceinline__ unsigned ballot_sync(unsigned, int predicate) { return (unsigned)__ballot(predicate); } __device__ __forceinline__ int any_sync(unsigned, int predicate) { return (int)(__ballot(predicate) != 0); } +// ---- matrix cores (gfx11/gfx12 WMMA) ---- +// D[16x16] += A[16x16] * B^T[16x16]: both operands are 16 rows of 16 halves, which is exactly how the prefill GEMM +// stages X (positions) and W (output rows) in shared memory, so no transpose is needed. Each lane supplies the +// k-values of its own row of both operands and holds 8 results: rows 8*(lane>>4) + i, column lane & 15. +// gfx12 splits the k dimension across the two half-waves (each lane gives 8 halves, lanes 16-31 the upper half); +// gfx11 takes all 16 from one lane. +#if defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1103__) || defined(__gfx1150__) || \ + defined(__gfx1151__) || defined(__gfx1152__) +#define STRATA_WMMA 1 +#define STRATA_WMMA_K 16 +#elif defined(__gfx1200__) || defined(__gfx1201__) +#define STRATA_WMMA 1 +#define STRATA_WMMA_K 8 +#else +#define STRATA_WMMA 0 +#define STRATA_WMMA_K 0 +#endif +// First k half the lane supplies: gfx12 lanes 16-31 give k 8..15, every lane on gfx11 gives k 0..15. +#define STRATA_WMMA_K0(lane) (((lane) >> 4) * (16 - STRATA_WMMA_K)) + +#if STRATA_WMMA +typedef _Float16 strata_hk __attribute__((ext_vector_type(STRATA_WMMA_K))); +typedef float strata_f8 __attribute__((ext_vector_type(8))); + +__device__ __forceinline__ strata_f8 strata_wmma(strata_hk a, strata_hk b, strata_f8 c) { +#if defined(__gfx1200__) || defined(__gfx1201__) + return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12(a, b, c); +#else + return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32(a, b, c); +#endif +} + +/// STRATA_WMMA_K halves at `p` (16-byte aligned); lanes 16-31 read their own upper half of the same row. +__device__ __forceinline__ strata_hk strata_ld_wmma(const unsigned short* p) { + union { uint4 u[STRATA_WMMA_K / 8]; strata_hk h; } c; +#pragma unroll + for (int i = 0; i < STRATA_WMMA_K / 8; i++) c.u[i] = *(const uint4*)(p + 8 * i); + return c.h; +} +#endif + } // namespace strata_hip #define __dp4a(a, b, c) (strata_hip::dp4a((a), (b), (c))) diff --git a/src/hip/mod.rs b/src/hip/mod.rs index 80030f72..3a222cb3 100644 --- a/src/hip/mod.rs +++ b/src/hip/mod.rs @@ -107,7 +107,7 @@ fn source(kv_q8: bool) -> String { __device__ const unsigned int iq3s_grid[512] = {{{}}};\n\ __device__ const unsigned char ksigns_iq2xs[128] = {{{}}};\n\ __device__ const signed char kvalues_iq4nl[16] = {{{}}};\n\ - #define LLAMA_Q8 {}\n#define KV_Q8 {}\n#define GEMM_TC 0\n\ + #define LLAMA_Q8 {}\n#define KV_Q8 {}\n#define GEMM_TC 0\n#define GEMM_WMMA (STRATA_WMMA && {})\n\ #define GEMM_BM {}\n#define GEMM_BK {}\n#define GEMM_MIN_BLOCKS 1\n#define GEMV_LOADW {}\n\ #define FA_BQ {}\n#define FA_BK {}\n{}", include_str!("compat.h"), @@ -121,6 +121,9 @@ fn source(kv_q8: bool) -> String { join(KVALUES_IQ4NL.iter().map(|v| v.to_string()).collect()), crate::cuda::llama_numerics() as u8, kv_q8 as u8, + // `STRATA_HIP_WMMA=0` falls back to the CUDA-core multiplications (A/B comparison, and a workaround if a + // card's matrix cores misbehave). + (std::env::var("STRATA_HIP_WMMA").map(|v| v != "0").unwrap_or(true)) as u8, GEMM_BM, crate::cuda::GEMM_BK, tuned(std::env::var("STRATA_GEMV_LOADW").ok().as_deref(), 0, |v| v <= 1), @@ -837,6 +840,46 @@ mod tests { assert!(worst < 2e-5, "max |diff| = {worst}"); } + /// `gemm_dense` against a CPU product, both tile regimes: the 16-position warp tile (`SM`) the small shapes take + /// and the 32-position one, which is what the matrix-core path in `gemm_q` computes. + #[test] + fn gemm_dense_matches_cpu_in_both_tile_regimes() { + let Ok(g) = Gpu::new(0) else { eprintln!("skipping: no HIP device"); return }; + for (rows, n, cols) in [(128usize, 64usize, 64usize), (8192, 128, 64)] { + let mut st = 7u32; + let mut rnd = || { st = st.wrapping_mul(1664525).wrapping_add(1013904223); (st >> 9) as f32 / 8388608.0 - 0.5 }; + let w: Vec = (0..rows * cols).map(|_| rnd()).collect(); + let x: Vec = (0..n * cols).map(|_| rnd()).collect(); + let mut want = vec![0f32; n * rows]; + for m in 0..n { + for r in 0..rows { + let mut a = 0f32; + for k in 0..cols { a += x[m * cols + k] * w[r * cols + k]; } + want[m * rows + r] = a; + } + } + let gw = g.alloc(4 * rows * cols).unwrap(); + let gx = g.alloc(4 * n * cols).unwrap(); + let gy = g.alloc(4 * n * rows).unwrap(); + let g: &dyn Backend = &g; + g.put(&w, &gw, 0).unwrap(); + g.put(&x, &gx, 0).unwrap(); + let t = GpuTensor::new(GgmlType::F32, rows, cols, gw); + g.gemm_dense(&t, n, gx.addr(), cols, gy.addr(), rows, 0).unwrap(); + g.sync().unwrap(); + let got: Vec = g.get(&gy, 0, n * rows).unwrap(); + let mut worst = 0f32; + let mut at = 0; + for i in 0..n * rows { + let d = (got[i] - want[i]).abs(); + if d > worst { worst = d; at = i; } + } + // f32 products summed over 64 terms: a few ulps either way, and f16 inputs quantize harder, so compare by + // relative error against the magnitude of the row's terms. + assert!(worst < 1e-2 * cols as f32, "rows {rows}: max |diff| = {worst} at {at} (got {}, want {})", got[at], want[at]); + } + } + /// The generated source compiles for this device through hiprtc (the CUDA source with `STRATA_HIP` taken). #[test] fn hiprtc_compiles_the_kernels() { From 92b28e2d886412613286587067e79b33133714c6 Mon Sep 17 00:00:00 2001 From: Hannes Klas Date: Mon, 16 Nov 2026 14:55:09 +0100 Subject: [PATCH 006/515] hip: graph capture on by default, and parity checks across the local models The step allocates nothing once the rope table exists, so the forward is captured (hipStreamBeginCapture) and replayed: 174 -> 183 tok/s decode on Qwen3.6-35B-A3B. A rope table a capture lacks is deferred the way the CUDA backend defers it (the kernel computes its own frequencies for that pass; the table is made after the capture and the graph recaptured), and htod refuses to run inside a capture instead of failing deep in the driver. STRATA_HIP_GRAPH=0 turns capture off. Checked with --fixed-experts (deterministic placement) against the Vulkan backend: bit-identical greedy output on Qwen3.6-35B-A3B, Ornith-1.5-35B-A3B, Qwen3.5-9B (dense) and Qwen3.8-27B (dense), and graph-on vs graph-off bit-identical on three prompts. Dense prefill is 1.4x Vulkan's (705 vs 497 tok/s on the 27B), dense decode 10% behind (memory-bandwidth bound); 35B decode is at parity with fixed placement (73.8 vs 72.3 tok/s). --- docs/HIP.md | 35 +++++++++++++++++++---------------- src/hip/mod.rs | 36 +++++++++++++++++++++++++++++------- 2 files changed, 48 insertions(+), 23 deletions(-) diff --git a/docs/HIP.md b/docs/HIP.md index 62fc05e6..aac957ce 100644 --- a/docs/HIP.md +++ b/docs/HIP.md @@ -4,11 +4,13 @@ build step: the kernels are compiled at run time by hiprtc and launched through the HIP runtime, both loaded by name (`libamdhip64.so`, `libhiprtc.so`), the way `src/cuda` loads NVRTC. `cargo build --release` is the whole build. -**Status: experimental.** Brought up on Qwen3.6-35B-A3B (RX 9070 XT, gfx1201, ROCm 7.2.3). Greedy output matches the -other backends: identical to the Vulkan backend on 3 of 4 prompts, and to its own CUDA-core prefill on 5 of 6, with the -difference at a near-tie where the f16 tensor-core summation order picks another token (the same class of difference the -CUDA and Vulkan backends have). Not yet ported: graph capture (off by default) and the host-side pipeline details of the -CUDA backend (pinned ring staging, side stream). +**Status: experimental.** Brought up on an RX 9070 XT (gfx1201, ROCm 7.2.3). With `--fixed-experts` (deterministic +placement) the greedy output is **bit-identical to the Vulkan backend** on the four local models tried (Qwen3.6-35B-A3B, +Ornith-1.5-35B-A3B, Qwen3.5-9B dense, Qwen3.8-27B dense) and to its own CUDA-core prefill on 5 of 6 prompts — the odd +one out differs at a near-tie, where the f16 tensor-core summation order picks another token (the same class of +difference the CUDA and Vulkan backends have; with adaptive placement, greedy tokens can also change between runs, as +they do on the other backends). Not yet ported: the host-side pipeline details of the CUDA backend (pinned ring staging +for `htod`, side stream for `beside`). ## What runs @@ -16,13 +18,16 @@ Everything the Vulkan backend runs, through the same kernels: | | HIP | Vulkan (same machine, same model) | |---|---|---| -| Prefill, pp 1024, `--mtp 2` | 1569 tok/s | 1428 tok/s | +| Prefill, pp 1024, `--mtp 2` | 1530 tok/s | 1602 tok/s | | Prefill, pp 4096, `--mtp 2` | 2106 tok/s | (not run) | -| Decode, tg 48, `--mtp 2` | 173 tok/s | 231 tok/s | +| Decode, tg 48, `--mtp 2` | 183 tok/s | 236 tok/s | +| Decode, `--fixed-experts`, same prompt | 73.8 tok/s | 72.3 tok/s | +| Qwen3.8-27B dense, prefill / decode | 705 / 50.3 tok/s | 497 / 55.5 tok/s | -Qwen3.6-35B-A3B UD-Q4_K_XL, `--ctx 4096 --vram-margin 256`, RX 9070 XT, Ryzen 7 5700X, one process each. Prefill runs on -the card's matrix cores (below) and is at parity with Vulkan; decode is 1.3x behind, which is the host side (no graph -capture, no side stream) rather than the kernels. +Qwen3.6-35B-A3B UD-Q4_K_XL (first rows) and Qwen3.8-27B UD-IQ3_S, `--ctx 4096 --vram-margin 256`, one process each. +Prefill runs on the card's matrix cores (below); on a dense model it is 1.4x ahead of Vulkan. Decode with fixed +placement is at parity (the benches above differ because each backend finds its own expert placement, which changes the +MTP draft acceptance); the dense model's decode is 10% behind, memory-bandwidth bound. ## How it works @@ -58,18 +63,16 @@ capture, no side stream) rather than the kernels. - `STRATA_HIP_SYNC=1` waits after every launch, so a hardware exception names the kernel that raised it. - `STRATA_HIP_TRACE=1` names every launch before it goes out (grid, block, shared memory). -- `STRATA_HIP_GRAPH=1` turns on graph capture once the forward allocates nothing inside a step (HIP refuses an - allocation on a capturing stream; CUDA's stream-ordered allocator allows it). +- `STRATA_HIP_GRAPH=0` runs the forward every time instead of capturing it (capture is on by default, +5% decode). - `STRATA_NO_GRAPH=1` turns capture off for both GPU backends. - `STRATA_HIP_WMMA=0` uses the CUDA-core multiplications in the prefill GEMM instead of the matrices cores. ## Next -1. Graph capture: move the per-step allocations (q8 cache growth, rope table) out of the captured region; that and the - side stream are where the remaining decode gap is. -2. The int8 WMMA form (`__builtin_amdgcn_wmma_i32_16x16x16_iu8`) for the integer-weight prefill GEMM, which today takes +1. The int8 WMMA form (`__builtin_amdgcn_wmma_i32_16x16x16_iu8`) for the integer-weight prefill GEMM, which today takes the f16 path (`GEMM_TC 0`): less shared-memory traffic per output than the sm_80-style int8 `gemmi_*` kernels. -3. A pinned ring for `htod` so expert streaming during prefill does not sync the stream per tensor. +2. A pinned ring for `htod` and a side stream for `beside`, so expert uploads overlap with compute in prefill. +3. The int8 WMMA form ## Credits diff --git a/src/hip/mod.rs b/src/hip/mod.rs index 3a222cb3..dbe9bb01 100644 --- a/src/hip/mod.rs +++ b/src/hip/mod.rs @@ -21,6 +21,10 @@ use std::sync::{Arc, LazyLock, Mutex}; /// `STRATA_HIP_SYNC`: one sync per launch (see `Gpu::launch`). static SYNC_EACH: LazyLock = LazyLock::new(|| std::env::var_os("STRATA_HIP_SYNC").is_some()); +/// `STRATA_NO_GRAPH` / `STRATA_HIP_GRAPH=0`: run the forward every time instead of capturing it. +static NO_GRAPH: LazyLock = LazyLock::new(|| { + std::env::var_os("STRATA_NO_GRAPH").is_some() || std::env::var("STRATA_HIP_GRAPH").map(|v| v == "0").unwrap_or(false) +}); /// `STRATA_HIP_TRACE`: name every launch before it goes out, so a fault that kills the process names the kernel. static TRACE: LazyLock = LazyLock::new(|| std::env::var_os("STRATA_HIP_TRACE").is_some()); @@ -271,10 +275,23 @@ impl Gpu { (cfg((rows.div_ceil(wpb * rpw) as u32, k as u32), (32 * wpb) as u32, Self::xq_smem(ty, cols)), rpw as i32) } + /// Whether the stream is capturing a graph: no allocation and no synchronous copy may be issued inside one. + fn capturing(&self) -> bool { + let mut status = 0; + unsafe { (self.hip.stream_is_capturing)(self.stream, &mut status) }; + status != 0 + } + /// The rope frequencies base^(-2i / n_rot) as `rms_norm_rope` computes them in f64, made once by `rope_freq`. + /// While a graph is captured a missing table gives 0 (the kernel computes the frequencies itself) and is made + /// after the capture, which `graph` then repeats. fn rope_fr(&self, base: f32, n_rot: usize) -> anyhow::Result { let mut fr = self.fr.lock().unwrap(); if let Some(b) = fr.0.get(&(base.to_bits(), n_rot)) { return Ok(b.addr()) } + if self.capturing() { + fr.1.push((base, n_rot)); + return Ok(0); + } let buf = alloc_raw(&self.hip, 8 * (n_rot / 2).max(1))?; let p = buf.addr(); let (bs, nr) = (base, n_rot as i32); @@ -406,6 +423,7 @@ impl Backend for Gpu { /// drained first so the copy cannot pass kernels already queued that write `dst`. fn htod(&self, src: &[u8], dst: &Buf, off: usize) -> anyhow::Result<()> { anyhow::ensure!(off + src.len() <= dst.len(), "htod: {} bytes at {off} into {}", src.len(), dst.len()); + anyhow::ensure!(!self.capturing(), "htod inside a captured graph: the caller must copy before the capture"); self.wait()?; let r = unsafe { (self.hip.memcpy)((dst.addr() + off as u64) as *mut c_void, src.as_ptr().cast(), src.len(), ffi::MEMCPY_H2D) }; self.hip.check(r, "hipMemcpy(htod)") @@ -439,18 +457,16 @@ impl Backend for Gpu { fn sync(&self) -> anyhow::Result<()> { self.wait() } /// Recorded with `hipStreamBeginCapture`: the same launches, replayed by the driver with no host work. - /// Off by default: the forwards allocate inside their step (the q8 cache grows, the rope table is made), and HIP - /// refuses an allocation on a capturing stream ("operation not permitted when stream is capturing"), where CUDA's - /// stream-ordered allocator allows it. `STRATA_HIP_GRAPH=1` turns capture on once the step allocates nothing. + /// HIP refuses an allocation on a capturing stream ("operation not permitted when stream is capturing"), where + /// CUDA's stream-ordered allocator allows it, so anything a step allocates has to be made before the capture (the + /// rope table defers itself, see `rope_fr`). `STRATA_HIP_GRAPH=0` turns capture off. fn graph(&self, key: u64, f: &mut dyn FnMut() -> anyhow::Result<()>) -> anyhow::Result<()> { - if std::env::var_os("STRATA_NO_GRAPH").is_some() || std::env::var_os("STRATA_HIP_GRAPH").is_none() { return f() } + if *NO_GRAPH { return f() } if let Some(g) = self.graphs.lock().unwrap().get(&key) { let r = unsafe { (self.hip.graph_launch)(g.exec, self.stream) }; return self.hip.check(r, "hipGraphLaunch"); } - let mut capturing = 0; - unsafe { (self.hip.stream_is_capturing)(self.stream, &mut capturing) }; - if capturing != 0 { return f() } // never nest captures + if self.capturing() { return f() } // never nest captures self.hip.check(unsafe { (self.hip.stream_begin_capture)(self.stream, ffi::CAPTURE_MODE_THREAD_LOCAL) }, "hipStreamBeginCapture")?; let r = f(); let mut graph: ffi::Graph = std::ptr::null_mut(); @@ -461,6 +477,12 @@ impl Backend for Gpu { let mut exec: ffi::GraphExec = std::ptr::null_mut(); self.hip.check(unsafe { (self.hip.graph_instantiate)(&mut exec, graph, 0) }, "hipGraphInstantiate")?; self.hip.check(unsafe { (self.hip.graph_launch)(exec, self.stream) }, "hipGraphLaunch")?; + // A rope table the capture lacked: make it, and capture again next time (this graph computes it per call). + let want = std::mem::take(&mut self.fr.lock().unwrap().1); + if !want.is_empty() { + for (base, n_rot) in want { self.rope_fr(base, n_rot)?; } + return Ok(()); + } self.graphs.lock().unwrap().insert(key, Graph { exec, graph, hip: self.hip.clone() }); Ok(()) } From 08c6297bb6813aa4807f46f5aa6456623c695345 Mon Sep 17 00:00:00 2001 From: Hannes Klas Date: Mon, 16 Nov 2026 16:03:48 +0100 Subject: [PATCH 007/515] hip: pinned staging ring, stream-ordered copies, graph cap, calibration htod goes through a 64 MB pinned ring for copies over 256 KB: the DMA reads one region while the host fills the next, and a region is reused only after the event of the copy that read it completed. Smaller copies are queued asynchronously on the stream instead of a synchronous memcpy after a full stream sync, and memset/memset(alloc) are hipMemsetAsync on the stream -- the null-stream hipMemset could land after a copy queued for the same buffer, which is what made the first version's upload look lost. Graph recording is capped at 32 like the CUDA backend (step_rows keys one graph per combination of sequence slots, each holding device memory). calibrate --backend hip now measures chunk, MTP drafts and the short-prompt threshold and writes strata--hip.json, which later runs read: on Qwen3.6-35B-A3B it picks chunk 4096 and --mtp 3 (prefill 2717 tok/s measured in calibration). With both backends calibrated, pp 1024 / tg 48: HIP 1577-2072 prefill and 188-222 decode, Vulkan 1344 and 195. --- docs/HIP.md | 24 ++++++----- src/hip/ffi.rs | 2 + src/hip/mod.rs | 107 ++++++++++++++++++++++++++++++++++++++++--------- 3 files changed, 105 insertions(+), 28 deletions(-) diff --git a/docs/HIP.md b/docs/HIP.md index aac957ce..d50b6cf1 100644 --- a/docs/HIP.md +++ b/docs/HIP.md @@ -18,16 +18,16 @@ Everything the Vulkan backend runs, through the same kernels: | | HIP | Vulkan (same machine, same model) | |---|---|---| -| Prefill, pp 1024, `--mtp 2` | 1530 tok/s | 1602 tok/s | -| Prefill, pp 4096, `--mtp 2` | 2106 tok/s | (not run) | -| Decode, tg 48, `--mtp 2` | 183 tok/s | 236 tok/s | -| Decode, `--fixed-experts`, same prompt | 73.8 tok/s | 72.3 tok/s | +| Prefill, pp 1024, calibrated | 1577-2072 tok/s | 1344 tok/s | +| Prefill, pp 4096 | 2106 tok/s | (not run) | +| Decode, tg 48, calibrated | 188-222 tok/s | 195 tok/s | | Qwen3.8-27B dense, prefill / decode | 705 / 50.3 tok/s | 497 / 55.5 tok/s | -Qwen3.6-35B-A3B UD-Q4_K_XL (first rows) and Qwen3.8-27B UD-IQ3_S, `--ctx 4096 --vram-margin 256`, one process each. -Prefill runs on the card's matrix cores (below); on a dense model it is 1.4x ahead of Vulkan. Decode with fixed -placement is at parity (the benches above differ because each backend finds its own expert placement, which changes the -MTP draft acceptance); the dense model's decode is 10% behind, memory-bandwidth bound. +Qwen3.6-35B-A3B UD-Q4_K_XL (first rows) and Qwen3.8-27B UD-IQ3_S, `--ctx 4096 --vram-margin 256`, one process each, +`calibrate` run for each backend (chunk 4096; HIP picks `--mtp 3`, Vulkan `--mtp 1`). Prefill runs on the card's matrix +cores (below) and is ahead of Vulkan; decode is within a few percent in either direction — the spread over repeated runs +is larger than the difference, because each backend finds its own expert placement and that moves the MTP draft +acceptance. A dense model's prefill is 1.4x ahead and its decode 10% behind (memory-bandwidth bound). ## How it works @@ -51,6 +51,11 @@ MTP draft acceptance); the dense model's decode is 10% behind, memory-bandwidth so the CUDA build's preprocessed source is unchanged. - The code object is cached in `$XDG_CACHE_HOME/rusting_strata/.amdgcn`, keyed by the source, the `gfx` target and the hiprtc version. +- `calibrate --backend hip` measures chunk, MTP drafts and the short-prompt threshold on this machine and writes + `strata--hip.json`; later runs read it, as they do for the other backends. +- Large `htod`s go through a 64 MB pinned ring (the DMA reads it while the host fills the next region), so expert + streaming does not stop the CPU side; small copies are queued asynchronously on the same stream, and `memset` is + stream-ordered (the null-stream `hipMemset` could land after a copy queued for the same buffer). ## Requirements @@ -71,8 +76,7 @@ MTP draft acceptance); the dense model's decode is 10% behind, memory-bandwidth 1. The int8 WMMA form (`__builtin_amdgcn_wmma_i32_16x16x16_iu8`) for the integer-weight prefill GEMM, which today takes the f16 path (`GEMM_TC 0`): less shared-memory traffic per output than the sm_80-style int8 `gemmi_*` kernels. -2. A pinned ring for `htod` and a side stream for `beside`, so expert uploads overlap with compute in prefill. -3. The int8 WMMA form +2. A side stream for `beside`, so expert uploads overlap with compute in prefill. ## Credits diff --git a/src/hip/ffi.rs b/src/hip/ffi.rs index ed6ea1cf..a8a7590e 100644 --- a/src/hip/ffi.rs +++ b/src/hip/ffi.rs @@ -64,6 +64,7 @@ pub struct Hip { pub malloc: unsafe extern "C" fn(*mut *mut c_void, usize) -> c_int, pub free: unsafe extern "C" fn(*mut c_void) -> c_int, pub memset: unsafe extern "C" fn(*mut c_void, c_int, usize) -> c_int, + pub memset_async: unsafe extern "C" fn(*mut c_void, c_int, usize, Stream) -> c_int, pub memcpy: unsafe extern "C" fn(*mut c_void, *const c_void, usize, c_int) -> c_int, pub memcpy_async: unsafe extern "C" fn(*mut c_void, *const c_void, usize, c_int, Stream) -> c_int, pub stream_create: unsafe extern "C" fn(*mut Stream, u32) -> c_int, @@ -129,6 +130,7 @@ impl Hip { malloc: g!("hipMalloc"), free: g!("hipFree"), memset: g!("hipMemset"), + memset_async: g!("hipMemsetAsync"), memcpy: g!("hipMemcpy"), memcpy_async: g!("hipMemcpyAsync"), stream_create: g!("hipStreamCreateWithFlags"), diff --git a/src/hip/mod.rs b/src/hip/mod.rs index dbe9bb01..7db7838f 100644 --- a/src/hip/mod.rs +++ b/src/hip/mod.rs @@ -15,7 +15,7 @@ use crate::cuda::{AMAX_PARTS, FA_BK, attn_prefill_smem_bk, dyn_shmem_need, kname use crate::quant::GgmlType; use anyhow::{Context, bail}; use std::any::Any; -use std::collections::HashMap; +use std::collections::{HashMap, VecDeque}; use std::ffi::c_void; use std::sync::{Arc, LazyLock, Mutex}; @@ -54,6 +54,9 @@ pub struct Gpu { done: ffi::Event, /// Rope frequency tables, `base` and `n_rot` to the device buffer that holds them. fr: Mutex<(HashMap<(u32, usize), Buf>, Vec<(f32, usize)>)>, + /// Pinned staging for large `htod`, used as a ring: the copy returns before its DMA, so the host fills the next + /// region while the card reads the previous one (expert streaming in prefill). + staging: Mutex, } // The HIP handles are raw pointers but the runtime is thread-safe for the calls the backend makes, and `Backend` @@ -201,10 +204,16 @@ impl Gpu { } let am_buf = alloc_raw(&hip, 64 * AMAX_PARTS)?; let q8_buf = alloc_raw(&hip, 1)?; + // Pinned ring for large host-to-device copies. + let mut host: *mut c_void = std::ptr::null_mut(); + hip.check(unsafe { (hip.host_malloc)(&mut host, RING, ffi::HOST_MALLOC_PORTABLE | ffi::HOST_MALLOC_MAPPED) }, "hipHostMalloc(ring)")?; + let mut dev: *mut c_void = std::ptr::null_mut(); + hip.check(unsafe { (hip.host_device_ptr)(&mut dev, host, 0) }, "hipHostGetDevicePointer(ring)")?; + let staging = Staging { pin: Buf::new(dev as u64, RING, PinnedHost { hip: hip.clone(), p: host }), host: host.cast(), head: 0, busy: VecDeque::new() }; let mut done: ffi::Event = std::ptr::null_mut(); hip.check(unsafe { (hip.event_create)(&mut done, ffi::EVENT_DISABLE_TIMING) }, "hipEventCreate")?; Ok(Gpu { hip, device, stream, module, fns, arch, kv_q8, max_smem, am: am_buf, q8: Mutex::new((q8_buf, None)), - graphs: Mutex::new(HashMap::new()), done, fr: Mutex::new((HashMap::new(), Vec::new())) }) + graphs: Mutex::new(HashMap::new()), done, fr: Mutex::new((HashMap::new(), Vec::new())), staging: Mutex::new(staging) }) } fn h(&self) -> &ffi::Hip { &self.hip } @@ -378,6 +387,49 @@ impl Gpu { fn grid(n: usize) -> LaunchConfig { cfg((n.div_ceil(256) as u32, 1), 256, 0) } } +/// Pinned host allocation freed with the runtime that made it. +struct PinnedHost { hip: Arc, p: *mut c_void } + +unsafe impl Send for PinnedHost {} +unsafe impl Sync for PinnedHost {} + +impl Drop for PinnedHost { + fn drop(&mut self) { unsafe { (self.hip.host_free)(self.p) }; } +} + +/// Pinned host memory used as a ring for `htod`: a region is free again once the copy that read it has completed. +struct Staging { + pin: Buf, + host: *mut u8, + head: usize, + busy: VecDeque<(usize, usize, Event)>, +} + +/// A `hipEvent_t` that destroys itself; `query` reports completion. +struct Event { hip: Arc, ev: ffi::Event } + +impl Event { + fn new(hip: &Arc) -> anyhow::Result { + let mut ev: ffi::Event = std::ptr::null_mut(); + hip.check(unsafe { (hip.event_create)(&mut ev, ffi::EVENT_DISABLE_TIMING) }, "hipEventCreate")?; + Ok(Event { hip: hip.clone(), ev }) + } + fn record(&self, stream: ffi::Stream) -> anyhow::Result<()> { + self.hip.check(unsafe { (self.hip.event_record)(self.ev, stream) }, "hipEventRecord") + } + fn done(&self) -> bool { unsafe { (self.hip.event_query)(self.ev) == ffi::HIP_SUCCESS } } +} + +impl Drop for Event { + fn drop(&mut self) { unsafe { (self.hip.event_destroy)(self.ev) }; } +} + +/// Recorded graphs kept before a forward runs uncaptured (CUDA's cap, same reason). +const GRAPHS_MAX: usize = 32; + +const RING: usize = 64 << 20; +const RING_MIN: usize = 256 << 10; + fn alloc_raw(hip: &Arc, bytes: usize) -> anyhow::Result { let mut p: *mut c_void = std::ptr::null_mut(); hip.check(unsafe { (hip.malloc)(&mut p, bytes.max(1)) }, "hipMalloc")?; @@ -414,19 +466,39 @@ impl Backend for Gpu { fn alloc(&self, bytes: usize) -> anyhow::Result { let b = alloc_raw(&self.hip, bytes)?; - self.hip.check(unsafe { (self.hip.memset)(b.addr() as *mut c_void, 0, b.len()) }, "hipMemset")?; + self.memset(&b)?; Ok(b) } - /// Synchronous copy: HIP does not promise that an async copy from pageable memory has staged the host buffer when - /// the call returns, and a caller that reuses `src` (every caller does) cannot wait for that. The stream is - /// drained first so the copy cannot pass kernels already queued that write `dst`. + /// Queue a host-to-device copy on the stream and return once `src` may be reused: from pageable memory the + /// runtime stages the buffer inside the call, and large copies go through the pinned ring so the DMA does not + /// stop the host (expert streaming during prefill). fn htod(&self, src: &[u8], dst: &Buf, off: usize) -> anyhow::Result<()> { anyhow::ensure!(off + src.len() <= dst.len(), "htod: {} bytes at {off} into {}", src.len(), dst.len()); - anyhow::ensure!(!self.capturing(), "htod inside a captured graph: the caller must copy before the capture"); - self.wait()?; - let r = unsafe { (self.hip.memcpy)((dst.addr() + off as u64) as *mut c_void, src.as_ptr().cast(), src.len(), ffi::MEMCPY_H2D) }; - self.hip.check(r, "hipMemcpy(htod)") + if src.len() < RING_MIN { + let r = unsafe { (self.hip.memcpy_async)((dst.addr() + off as u64) as *mut c_void, src.as_ptr().cast(), src.len(), + ffi::MEMCPY_H2D, self.stream) }; + return self.hip.check(r, "hipMemcpyAsync(htod)"); + } + let mut g = self.staging.lock().unwrap(); + for (i, c) in src.chunks(RING).enumerate() { + if g.head + c.len() > RING { g.head = 0; } + let (a, b) = (g.head, g.head + c.len()); + // Regions still being read by an earlier copy have to complete before the host overwrites them. + while g.busy.iter().any(|&(s, e, _)| s < b && a < e) { + let (_, _, ev) = g.busy.pop_front().unwrap(); + self.hip.check(unsafe { (self.hip.event_sync)(ev.ev) }, "hipEventSynchronize")?; + } + unsafe { std::ptr::copy_nonoverlapping(c.as_ptr(), g.host.add(a), c.len()) }; + let r = unsafe { (self.hip.memcpy_async)((dst.addr() + (off + i * RING) as u64) as *mut c_void, + g.host.add(a) as *const c_void, c.len(), ffi::MEMCPY_H2D, self.stream) }; + self.hip.check(r, "hipMemcpyAsync(htod ring)")?; + let ev = Event::new(&self.hip)?; + ev.record(self.stream)?; + g.busy.push_back((a, b, ev)); + g.head = b; + } + Ok(()) } fn dtoh(&self, src: &Buf, off: usize, dst: &mut [u8]) -> anyhow::Result<()> { @@ -444,8 +516,10 @@ impl Backend for Gpu { self.hip.check(r, "hipMemcpyAsync(dtod)") } + /// On the stream, so it is ordered against the copies and launches around it (the plain `hipMemset` goes to the + /// null stream and can land after a copy that was queued for the same buffer). fn memset(&self, dst: &Buf) -> anyhow::Result<()> { - self.hip.check(unsafe { (self.hip.memset)(dst.addr() as *mut c_void, 0, dst.len()) }, "hipMemset") + self.hip.check(unsafe { (self.hip.memset_async)(dst.addr() as *mut c_void, 0, dst.len(), self.stream) }, "hipMemsetAsync") } fn mem_info(&self) -> anyhow::Result<(usize, usize)> { @@ -466,6 +540,9 @@ impl Backend for Gpu { let r = unsafe { (self.hip.graph_launch)(g.exec, self.stream) }; return self.hip.check(r, "hipGraphLaunch"); } + // Each graph holds device memory and `step_rows` keys one per combination of sequence slots: past the cap a + // forward runs uncaptured (the CUDA backend caps for the same reason). + if self.graphs.lock().unwrap().len() >= GRAPHS_MAX { return f() } if self.capturing() { return f() } // never nest captures self.hip.check(unsafe { (self.hip.stream_begin_capture)(self.stream, ffi::CAPTURE_MODE_THREAD_LOCAL) }, "hipStreamBeginCapture")?; let r = f(); @@ -495,13 +572,7 @@ impl Backend for Gpu { let mut dev: *mut c_void = std::ptr::null_mut(); self.hip.check(unsafe { (self.hip.host_device_ptr)(&mut dev, host, 0) }, "hipHostGetDevicePointer")?; unsafe { std::ptr::write_bytes(host as *mut u8, 0, 4 * n) }; - struct Pinned { hip: Arc, p: *mut c_void } - unsafe impl Send for Pinned {} - unsafe impl Sync for Pinned {} - impl Drop for Pinned { - fn drop(&mut self) { unsafe { (self.hip.host_free)(self.p) }; } - } - let owner = Pinned { hip: self.hip.clone(), p: host }; + let owner = PinnedHost { hip: self.hip.clone(), p: host }; Ok((Buf::new(dev as u64, 4 * n, owner), host.cast())) } From f3f29c8773bb34e3b1a9383b9c46e5dbc802f1a1 Mon Sep 17 00:00:00 2001 From: Hannes Klas Date: Mon, 16 Nov 2026 17:04:56 +0100 Subject: [PATCH 008/515] hip: why the prefill GEMM keeps the f16 matrix cores (int8 measured, not assumed) The CUDA backend runs integer weight types as int8 mma.sync; porting that assumed NVIDIA's premises hold on RDNA4, and they do not. Two probes, both model-free and committed under tools/hip, settle it: - wmma_rate: v_wmma_i32_16x16x16_iu8 is only 2x v_wmma_f32_16x16x16_f16 on gfx1201 (137 vs 57 TMAC/s). - wmma_rescale: in the kernel's inner-loop shape (2x2 tiles, four 16-deep k-steps from shared memory), int8 without its epilogue takes 0.35x the time of f16 -- but the per-16-weight scale and min the K-quants carry cost a multiplication per result, and AMD's layout gives a lane 8 results in 8 different rows, so the fold is 8 scalar operations each. With a vector-friendly layout it is 6.6x slower than f16, with the source's layout 13-16x. So GEMM_TC stays 0 on HIP: the prefill GEMM dequantizes to f16 in shared memory and runs on the f16 matrix cores, which is what puts HIP ahead of Vulkan on prefill. docs/HIP.md records the numbers so the next person does not repeat the port. --- docs/HIP.md | 16 ++++ tools/hip/README.md | 16 ++++ tools/hip/wmma_rate.cpp | 42 ++++++++++ tools/hip/wmma_rescale.cpp | 166 +++++++++++++++++++++++++++++++++++++ 4 files changed, 240 insertions(+) create mode 100644 tools/hip/README.md create mode 100644 tools/hip/wmma_rate.cpp create mode 100644 tools/hip/wmma_rescale.cpp diff --git a/docs/HIP.md b/docs/HIP.md index d50b6cf1..d4f4841c 100644 --- a/docs/HIP.md +++ b/docs/HIP.md @@ -72,6 +72,22 @@ acceptance. A dense model's prefill is 1.4x ahead and its decode 10% behind (mem - `STRATA_NO_GRAPH=1` turns capture off for both GPU backends. - `STRATA_HIP_WMMA=0` uses the CUDA-core multiplications in the prefill GEMM instead of the matrices cores. +## Why the prefill GEMM does not use int8 matrix cores + +The CUDA backend runs integer weight types as int8 `mma.sync` because NVIDIA's int8 tensor cores are 2-4x its f16 ones +and its layout puts each lane's 4 results over 2 rows and 2 columns, so the per-16-weight scale and min the K-quants +carry cost 2 multiplications a result. On RDNA4 both premises fail: + +- `v_wmma_i32_16x16x16_iu8` is only **2x** `v_wmma_f32_16x16x16_f16` (137 vs 57 TMAC/s on gfx1201, + `tools/hip/wmma_rate.cpp`). +- AMD's WMMA layout gives a lane 8 results in 8 *different rows*, so the scale of each result is different and the + rescale costs ~8 scalar operations per result — per 16-key group, not once per GEMM. + +Measured in the kernel's own inner-loop shape (`tools/hip/wmma_rescale.cpp`): int8 without its epilogue runs in 0.35x +the time of f16, with a vector-friendly rescale 6.6x *slower*, with the layout the source uses 13-16x slower. The +integer path cannot pay for itself here, so `GEMM_TC` stays 0 on HIP and the prefill GEMM dequantizes to f16 in shared +memory and runs on the f16 matrix cores, which is what puts it ahead of the Vulkan backend. + ## Next 1. The int8 WMMA form (`__builtin_amdgcn_wmma_i32_16x16x16_iu8`) for the integer-weight prefill GEMM, which today takes diff --git a/tools/hip/README.md b/tools/hip/README.md new file mode 100644 index 00000000..bf5b4c7e --- /dev/null +++ b/tools/hip/README.md @@ -0,0 +1,16 @@ +# HIP micro-benchmarks + +Device-side probes behind the decisions in `docs/HIP.md`. Build and run with the ROCm compiler; they need no model and +no RustingStrata binary: + +```sh +hipcc --offload-arch=gfx1201 -O3 wmma_rate.cpp -o wmma_rate && ./wmma_rate +hipcc --offload-arch=gfx1201 -O3 wmma_rescale.cpp -o wmma_rescale && ./wmma_rescale +``` + +- `wmma_rate.cpp`: the matrix-core instruction rate of the two operand types, operands in registers, so the numbers + are the instruction rate and not memory bandwidth. On RX 9070 XT (gfx1201): f16 57 TMAC/s, int8 137 TMAC/s. +- `wmma_rescale.cpp`: the inner-loop shape of the prefill GEMM (`gemm_q`: 2x2 tiles of 16x16, four 16-deep k-steps per + BK = 64, fragments from shared memory), as f16 and as int8 with the epilogue the integer weight formats need. The + int8 instruction is twice as fast on its own (0.35x the time) but the per-16-weight rescale takes it to 6.6x the f16 + time even written SoA with 8 rows contiguous per lane, which is why the HIP backend keeps the f16 matrix-core path. diff --git a/tools/hip/wmma_rate.cpp b/tools/hip/wmma_rate.cpp new file mode 100644 index 00000000..9cd2561e --- /dev/null +++ b/tools/hip/wmma_rate.cpp @@ -0,0 +1,42 @@ +// Isolated matrix-core rate: f16 WMMA vs int8 WMMA, same 16x16x16 shape, operands in registers so the number is the +// instruction rate, not memory bandwidth. +#include +#include +using h8 = _Float16 __attribute__((ext_vector_type(8))); +using f8 = float __attribute__((ext_vector_type(8))); +using i8v = int __attribute__((ext_vector_type(8))); +using b8 = int __attribute__((ext_vector_type(2))); // 8 int8 values + +__global__ void f16_loop(float* out, int iters) { + h8 a, b; f8 c; + for (int i = 0; i < 8; i++) { a[i] = (_Float16)i * 0.001f; b[i] = (_Float16)i * 0.002f; c[i] = 0.f; } + for (int t = 0; t < iters; t++) { c = __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12(a, b, c); a[0] += 1e-7f; } + float s = 0; for (int i = 0; i < 8; i++) s += c[i]; + if (threadIdx.x == 0) out[blockIdx.x] = s; +} +__global__ void i8_loop(float* out, int iters) { + b8 a = {0x01020304, 0x05060708}; + b8 b = {0x11121314, 0x15161718}; + i8v c; for (int i = 0; i < 8; i++) c[i] = 0; + for (int t = 0; t < iters; t++) { c = __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32_gfx12(true, a, true, b, c, false); a[0] ^= 1; } + int s = 0; for (int i = 0; i < 8; i++) s += c[i]; + if (threadIdx.x == 0) out[blockIdx.x] = (float)s; +} +template static float run(K k, int blocks, int iters) { + float* out; hipMalloc(&out, blocks * 4); + hipEvent_t a, b; hipEventCreate(&a); hipEventCreate(&b); + k<<>>(out, 16); // warm up + hipDeviceSynchronize(); + hipEventRecord(a); k<<>>(out, iters); hipEventRecord(b); hipEventSynchronize(b); + float ms = 0; hipEventElapsedTime(&ms, a, b); + hipFree(out); + double macs = (double)blocks * 2.0 * 4096.0 * iters; // 2 warps a block, 16x16x16 + return (float)(macs / (ms * 1e-3) / 1e12); +} +int main() { + int iters = 20000; + for (int blocks : {256, 1024}) { + printf("blocks %4d: f16 %.3f TMAC/s | i8 %.3f TMAC/s\n", blocks, run(f16_loop, blocks, iters), run(i8_loop, blocks, iters)); + } + return 0; +} diff --git a/tools/hip/wmma_rescale.cpp b/tools/hip/wmma_rescale.cpp new file mode 100644 index 00000000..6b85583a --- /dev/null +++ b/tools/hip/wmma_rescale.cpp @@ -0,0 +1,166 @@ +// Inner-loop shapes of the prefill GEMM: f16 WMMA vs int8 WMMA with the per-16 rescale fold that int8 needs. +// Both read their fragments from the same shared-memory tiles and run 16 WMMA per k-step (2x2 tiles of 16x16, 4 +// k-groups), which is one GEMM_TC step of the 128-thread warp tile. +#include +#include +using h8 = _Float16 __attribute__((ext_vector_type(8))); +using f8 = float __attribute__((ext_vector_type(8))); +using b8 = int __attribute__((ext_vector_type(2))); +using i8v = int __attribute__((ext_vector_type(8))); + +#define P 72 +__global__ void f16_loop(float* out, int iters) { + __shared__ __align__(16) _Float16 xs[128 * P], ws[64 * P]; + int tid = threadIdx.x; + for (int i = tid; i < 128 * P; i += blockDim.x) xs[i] = (_Float16)(i & 7) * 0.01f; + for (int i = tid; i < 64 * P; i += blockDim.x) ws[i] = (_Float16)(i & 7) * 0.01f; + __syncthreads(); + int warp = tid >> 5, lane = tid & 31, l16 = lane & 15, w0 = (lane >> 4) * 8; + int wm = (warp >> 1) * 32, wn = (warp & 1) * 32; + f8 acc[4]; for (int i = 0; i < 4; i++) for (int j = 0; j < 8; j++) acc[i][j] = 0.f; + for (int t = 0; t < iters; t++) { + #pragma unroll + for (int kk = 0; kk < 64; kk += 16) { + h8 a[2], b[2]; + #pragma unroll + for (int mt = 0; mt < 2; mt++) *(uint4*)&a[mt] = *(const uint4*)(xs + (wm + mt * 16 + l16) * P + kk + w0); + #pragma unroll + for (int nt = 0; nt < 2; nt++) *(uint4*)&b[nt] = *(const uint4*)(ws + (wn + nt * 16 + l16) * P + kk + w0); + #pragma unroll + for (int mt = 0; mt < 2; mt++) for (int nt = 0; nt < 2; nt++) + acc[mt * 2 + nt] = __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12(a[mt], b[nt], acc[mt * 2 + nt]); + } + } + float s = 0; for (int i = 0; i < 4; i++) for (int j = 0; j < 8; j++) s += acc[i][j]; + if (tid == 0) out[blockIdx.x] = s; +} +__global__ void i8_loop(float* out, int iters) { + __shared__ __align__(16) signed char xq[128 * P], wq[64 * P]; + __shared__ float xd[128][2], xs2[128][4]; // X scale per 32 keys, X sums per 16 keys + __shared__ float2 wdm[4][64]; // W scale and min per 16 weights + int tid = threadIdx.x; + for (int i = tid; i < 128 * P; i += blockDim.x) xq[i] = (signed char)(i & 31); + for (int i = tid; i < 64 * P; i += blockDim.x) wq[i] = (signed char)(i & 31); + for (int i = tid; i < 128; i += blockDim.x) { xd[i][0] = 0.01f; xd[i][1] = 0.02f; for (int j = 0; j < 4; j++) xs2[i][j] = 0.5f; } + for (int i = tid; i < 64; i += blockDim.x) for (int g = 0; g < 4; g++) wdm[g][i] = make_float2(0.01f, 0.3f); + __syncthreads(); + int warp = tid >> 5, lane = tid & 31, l16 = lane & 15, hi = lane >> 4, w0 = hi * 8; + int wm = (warp >> 1) * 32, wn = (warp & 1) * 32; + f8 acc[4]; for (int i = 0; i < 4; i++) for (int j = 0; j < 8; j++) acc[i][j] = 0.f; + for (int t = 0; t < iters; t++) { + #pragma unroll + for (int g = 0; g < 4; g++) { // 16-key groups = one weight scale + b8 a[2], b[2]; + #pragma unroll + for (int mt = 0; mt < 2; mt++) *(uint2*)&a[mt] = *(const uint2*)(xq + (wm + mt * 16 + l16) * P + g * 16 + w0); + #pragma unroll + for (int nt = 0; nt < 2; nt++) *(uint2*)&b[nt] = *(const uint2*)(wq + (wn + nt * 16 + l16) * P + g * 16 + w0); + #pragma unroll + for (int mt = 0; mt < 2; mt++) + #pragma unroll + for (int nt = 0; nt < 2; nt++) { + i8v c = {0,0,0,0,0,0,0,0}; + i8v r = __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32_gfx12(true, a[mt], true, b[nt], c, false); + float2 wq2 = wdm[g][wn + nt * 16 + l16]; + int base = wm + mt * 16 + 8 * hi; + f8 a4 = acc[mt * 2 + nt]; + #pragma unroll + for (int i = 0; i < 8; i++) { + float dx = xd[base + i][g >> 1]; + float sx = xs2[base + i][g]; + a4[i] += (float)r[i] * dx * wq2.x - sx * wq2.y; + acc[mt * 2 + nt] = a4; + } + } + } + } + float s = 0; for (int i = 0; i < 4; i++) for (int j = 0; j < 8; j++) s += acc[i][j]; + if (tid == 0) out[blockIdx.x] = s; +} + +__global__ void i8_nofold(float* out, int iters) { + __shared__ __align__(16) signed char xq[128 * P], wq[64 * P]; + int tid = threadIdx.x; + for (int i = tid; i < 128 * P; i += blockDim.x) xq[i] = (signed char)(i & 31); + for (int i = tid; i < 64 * P; i += blockDim.x) wq[i] = (signed char)(i & 31); + __syncthreads(); + int warp = tid >> 5, lane = tid & 31, l16 = lane & 15, hi = lane >> 4, w0 = hi * 8; + int wm = (warp >> 1) * 32, wn = (warp & 1) * 32; + i8v acc[4]; for (int i = 0; i < 4; i++) for (int j = 0; j < 8; j++) acc[i][j] = 0; + for (int t = 0; t < iters; t++) { + #pragma unroll + for (int g = 0; g < 4; g++) { + b8 a[2], b[2]; + #pragma unroll + for (int mt = 0; mt < 2; mt++) *(uint2*)&a[mt] = *(const uint2*)(xq + (wm + mt * 16 + l16) * P + g * 16 + w0); + #pragma unroll + for (int nt = 0; nt < 2; nt++) *(uint2*)&b[nt] = *(const uint2*)(wq + (wn + nt * 16 + l16) * P + g * 16 + w0); + #pragma unroll + for (int mt = 0; mt < 2; mt++) for (int nt = 0; nt < 2; nt++) + acc[mt * 2 + nt] = __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32_gfx12(true, a[mt], true, b[nt], acc[mt * 2 + nt], false); + } + } + int s = 0; for (int i = 0; i < 4; i++) for (int j = 0; j < 8; j++) s += acc[i][j]; + if (tid == 0) out[blockIdx.x] = (float)s; +} +// SoA fold: 8 rows of the lane are consecutive, so a scale is one 8-wide vector of separate arrays. +__global__ void i8_soa(float* out, int iters) { + __shared__ __align__(16) signed char xq[128 * P], wq[64 * P]; + __shared__ float dx0[128], sx0[128]; // X scale (one per 32 keys) and X sum (one per 16 keys) + __shared__ float2 wdm[4][64]; + int tid = threadIdx.x; + for (int i = tid; i < 128 * P; i += blockDim.x) xq[i] = (signed char)(i & 31); + for (int i = tid; i < 64 * P; i += blockDim.x) wq[i] = (signed char)(i & 31); + for (int i = tid; i < 128; i += blockDim.x) { dx0[i] = 0.01f; sx0[i] = 0.5f; } + for (int i = tid; i < 64; i += blockDim.x) for (int g = 0; g < 4; g++) wdm[g][i] = make_float2(0.01f, 0.3f); + __syncthreads(); + int warp = tid >> 5, lane = tid & 31, l16 = lane & 15, hi = lane >> 4, w0 = hi * 8; + int wm = (warp >> 1) * 32, wn = (warp & 1) * 32; + f8 acc[4]; for (int i = 0; i < 4; i++) for (int j = 0; j < 8; j++) acc[i][j] = 0.f; + for (int t = 0; t < iters; t++) { + #pragma unroll + for (int g = 0; g < 4; g++) { + b8 a[2], b[2]; + #pragma unroll + for (int mt = 0; mt < 2; mt++) *(uint2*)&a[mt] = *(const uint2*)(xq + (wm + mt * 16 + l16) * P + g * 16 + w0); + #pragma unroll + for (int nt = 0; nt < 2; nt++) *(uint2*)&b[nt] = *(const uint2*)(wq + (wn + nt * 16 + l16) * P + g * 16 + w0); + #pragma unroll + for (int mt = 0; mt < 2; mt++) + #pragma unroll + for (int nt = 0; nt < 2; nt++) { + i8v c = {0,0,0,0,0,0,0,0}; + i8v r = __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32_gfx12(true, a[mt], true, b[nt], c, false); + float2 wq2 = wdm[g][wn + nt * 16 + l16]; + int base = wm + mt * 16 + 8 * hi; + const float* dx = dx0 + base; + const float* sx = sx0 + base; + f8 a4 = acc[mt * 2 + nt]; + #pragma unroll + for (int i = 0; i < 8; i++) a4[i] += (float)r[i] * dx[i] * wq2.x - sx[i] * wq2.y; + acc[mt * 2 + nt] = a4; + } + } + } + float s = 0; for (int i = 0; i < 4; i++) for (int j = 0; j < 8; j++) s += acc[i][j]; + if (tid == 0) out[blockIdx.x] = s; +} + +template static float run(K k, int blocks, int iters) { + float* out; hipMalloc(&out, blocks * 4); + hipEvent_t a, b; hipEventCreate(&a); hipEventCreate(&b); + k<<>>(out, 16); hipDeviceSynchronize(); + hipEventRecord(a); k<<>>(out, iters); hipEventRecord(b); hipEventSynchronize(b); + float ms = 0; hipEventElapsedTime(&ms, a, b); hipFree(out); + return (float)ms; +} +int main() { + int iters = 200000; + for (int blocks : {256, 1024}) { + float f = run(f16_loop, blocks, iters), i = run(i8_loop, blocks, iters); + float n = run(i8_nofold, blocks, iters), so = run(i8_soa, blocks, iters); + printf("blocks %4d: f16 %.2f | i8 nofold %.2f (%.2fx) | i8 SoA fold %.2f (%.2fx) | i8 scalar fold %.2f (%.2fx)\n", + blocks, f, n, n / f, so, so / f, i, i / f); + } + return 0; +} From 5f8d1681c1ecb8754c144b11351f8ae9961a3562 Mon Sep 17 00:00:00 2001 From: Hannes Klas Date: Mon, 16 Nov 2026 17:06:17 +0100 Subject: [PATCH 009/515] hip: serve verified on the ROCm backend GET /v1/models, a non-streaming chat completion, a streaming one (SSE deltas) and a second turn that reuses the prompt cache (prompt_tokens_details.cached_tokens = 16 of 51) all work on HIP with Qwen3.5-9B. --- docs/HIP.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/HIP.md b/docs/HIP.md index d4f4841c..8b97987a 100644 --- a/docs/HIP.md +++ b/docs/HIP.md @@ -29,6 +29,9 @@ cores (below) and is ahead of Vulkan; decode is within a few percent in either d is larger than the difference, because each backend finds its own expert placement and that moves the MTP draft acceptance. A dense model's prefill is 1.4x ahead and its decode 10% behind (memory-bandwidth bound). +`serve` works too, checked on Qwen3.5-9B: `GET /v1/models`, non-streaming and streaming (`stream: true`) chat +completions, and the prompt cache across turns (`prompt_tokens_details.cached_tokens` on a follow-up request). + ## How it works - `src/hip/compat.h` is prepended to `kernels.cu`: it supplies the CUDA intrinsics the source uses (`__shfl_*_sync`, From 6feb823fd0e3b8bb135fe7481df7a604473cb9a0 Mon Sep 17 00:00:00 2001 From: Hannes Klas Date: Mon, 16 Nov 2026 18:16:48 +0100 Subject: [PATCH 010/515] hip: long-prompt numbers, and where the depth-dependent cost goes Benchmarks at 32k and 128k on the 35B model (pp and gen at both depths) plus a dense comparison, recorded in docs/HIP.md. With placement equalised (--fixed-experts: same residents, no swaps) decode is at parity but prefill loses 10% at 8k and 56% at 32k; at 128k HIP is 173 tok/s against Vulkan's 762. Fitting the per-token cost against depth isolates it: HIP 572 -> 1389 us/token from 8k to 32k, Vulkan 516 -> 614, so HIP's depth-dependent cost is 33 ns per position against 4 -- 8.4x -- and the same fit predicts the 128k numbers within the spread. Only attention grows with depth, and the prefill attention is the one kernel family still on the CUDA cores (the mma16816 emulation): the matrix-core port covered gemm_q only. Dense Qwen3.8-27B shows the same shape (HIP ahead at 8k, behind at 32k). Next: port attn_prefill_t to the gfx11/gfx12 WMMA the GEMM now uses. --- docs/HIP.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/docs/HIP.md b/docs/HIP.md index 8b97987a..9b979903 100644 --- a/docs/HIP.md +++ b/docs/HIP.md @@ -32,6 +32,28 @@ acceptance. A dense model's prefill is 1.4x ahead and its decode 10% behind (mem `serve` works too, checked on Qwen3.5-9B: `GET /v1/models`, non-streaming and streaming (`stream: true`) chat completions, and the prompt cache across turns (`prompt_tokens_details.cached_tokens` on a follow-up request). +## Long prompts + +Prefill degrades with prompt depth on both backends (attention is the only depth-dependent term), but faster on HIP, +because the prefill attention still runs on the CUDA cores: only the prefill GEMM has an AMD matrix-core path so far. + +Qwen3.6-35B-A3B UD-Q4_K_XL, `--mtp 0 --reps 1 --vram-margin 256`, KV `f16`: + +| | HIP | Vulkan | +|---|---|---| +| pp 32k / gen at 32k | 670 / 80.8 tok/s | 1584 / 108.8 tok/s | +| pp 128k / gen at 128k | 173 / 59.2 tok/s | 762 / 83.4 tok/s | +| pp 8k, `--fixed-experts` | 1748 tok/s | 1938 tok/s | +| pp 32k, `--fixed-experts` | 720 tok/s | 1629 tok/s | +| dense Qwen3.8-27B, pp 8k / 32k | 601 / 328 tok/s | 475 / 404 tok/s | + +With placement equalised (`--fixed-experts`: same residents, zero swaps) decode is at parity (63.8 vs 66.0 tok/s) and +prefill loses 10% at 8k and 56% at 32k. Fitting the per-token cost against depth (HIP 572 -> 1389 us from 8k to 32k, +Vulkan 516 -> 614) gives a depth slope of 33 vs 4 ns per position: HIP's attention costs 8.4x more per position, and +that same fit predicts the 128k numbers (215 vs 995 tok/s) within the measurement's spread. Porting `attn_prefill_t` +to the matrix cores the way `gemm_q` was ported is the next step; until then, `--chunk 0`-style token-by-token prefill +is not the answer, but a shorter `--ctx` and `--kv q8` both buy expert slots back. + ## How it works - `src/hip/compat.h` is prepended to `kernels.cu`: it supplies the CUDA intrinsics the source uses (`__shfl_*_sync`, From 5aa14362cb7a4985225e71e733288c1d553b35a4 Mon Sep 17 00:00:00 2001 From: Hannes Klas Date: Mon, 16 Nov 2026 20:04:23 +0100 Subject: [PATCH 011/515] hip: the prefill attention's V fragment read every other key ldsm4t's HIP branch loaded the high half of each transposed register two rows down instead of one, so the P*V product on the CUDA cores paired key 2k with key 2k+2: every even key's V row was counted twice and every odd one's never, while the softmax row sums still counted all of them. A long prompt's attention output was therefore wrong on every head, silently -- HIP and Vulkan never disagreed on the token parity checks because those prompts are shorter than the short-prompt threshold (32 tokens) and decoding runs `step`/`attn_rows`, which never reaches attn_prefill_t. On CUDA the same line is a byte offset (`a + 2 * PQ`), which is one row for a u16 pointer; the HIP port dropped the pointer arithmetic's unit. Found with a new device test: `hip::tests::attn_prefill_matches_cpu` runs attn_prefill_m against a CPU reference (q, k, v random, causal, four heads over two KV heads) at head_dim 128 and 256 and compares every element. Before the fix it reports a max |diff| of 2.2e3 on an output whose values are ~0.05; after it, 1.2e-4 (f16 rounding of q, k and the softmax weights). The same test pins the causal mask, the partial last query tile and both tile depths. head_dim 256 needed its shared-memory size fixed in the same commit: the kernel takes a 16-key tile there (FA_BK_FOR, as the CUDA build does on Turing's 64 KB blocks) while attn_prefill_m picked the depth by what fit, which was 16 too but by a different rule; the launcher now mirrors the kernel's choice instead of guessing, so a smaller allocation than the kernel addresses cannot come back. --- src/cuda/kernels.cu | 6 ++-- src/hip/mod.rs | 79 ++++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 78 insertions(+), 7 deletions(-) diff --git a/src/cuda/kernels.cu b/src/cuda/kernels.cu index 82a03d1f..aefc9b1b 100644 --- a/src/cuda/kernels.cu +++ b/src/cuda/kernels.cu @@ -956,7 +956,7 @@ __device__ __forceinline__ void ldsm4t(u32* r, const u16* p) { int m_row = (RM ? (m & 1) : (m >> 1)) * 8, m_col = (RM ? (m >> 1) : (m & 1)) * 8; #if STRATA_HIP const u16* a = p + (m_row + row) * PQ + m_col + col; - r[m] = (u32)a[0] | ((u32)a[2 * PQ] << 16); + r[m] = (u32)a[0] | ((u32)a[PQ] << 16); #else unsigned a = (unsigned)__cvta_generic_to_shared(p + (m_row + row) * PQ + m_col + col); unsigned short lo, hi; @@ -2483,8 +2483,8 @@ extern "C" __global__ void moe_combine_seq(float* x, const float* ye, const floa #endif #define FA_BK_DEFAULT FA_BK // Turing's 64 KB shared memory cannot hold the HD = 256 tile at 32 keys either: 16 fit (the kernel keeps the same -// 64 queries a block and four warps). -#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 750 && __CUDA_ARCH__ < 800 +// 64 queries a block and four warps). The HIP build has the same 64 KB a workgroup, so it takes the same 16-key tile. +#if (defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 750 && __CUDA_ARCH__ < 800) || STRATA_HIP #define FA_BK_FOR(HD) ((HD) == 256 ? 16 : FA_BK_DEFAULT) #else #define FA_BK_FOR(HD) FA_BK_DEFAULT diff --git a/src/hip/mod.rs b/src/hip/mod.rs index 7db7838f..e722d824 100644 --- a/src/hip/mod.rs +++ b/src/hip/mod.rs @@ -754,11 +754,13 @@ impl Backend for Gpu { fn attn_prefill_m(&self, q: u64, kc: u64, vc: u64, qg: u64, out: u64, step: u64, t: usize, nh: usize, nkv: usize, hd: usize, scale: f32, qm: u64, mw: usize, sink: u64, win: usize) -> anyhow::Result<()> { if !matches!(hd, 64 | 128 | 256) { bail!("attention prefill: head_dim {hd} unsupported (64, 128 or 256)"); } - // A tile of FA_BK keys needs 72 KiB at head_dim 256, more than a 64 KiB block may use on RDNA; 16 keys a - // tile (the depth the CUDA build uses on Turing's 64 KB blocks) fits, at the cost of more passes. - let bk = [FA_BK, 16, 8].into_iter().find(|&bk| attn_prefill_smem_bk(hd, bk) <= self.max_smem) - .with_context(|| format!("attn_prefill_{hd}: no tile depth fits {} B of shared memory", self.max_smem))?; + // A tile of FA_BK keys needs 72 KiB at head_dim 256, more than a 64 KiB workgroup may use on RDNA; 16 keys a + // tile (the depth the CUDA build uses on Turing's 64 KB blocks) fits, at the cost of more passes. This has to + // be the depth the kernel picks for itself (`FA_BK_FOR(HD)`), not a smaller one: the kernel would then address + // shared memory past what is allocated. + let bk = if hd == 256 { 16 } else { FA_BK }; let smem = attn_prefill_smem_bk(hd, bk) as u32; + anyhow::ensure!(smem as usize <= self.max_smem, "attn_prefill_{hd}: {smem} B of shared memory, {} allowed", self.max_smem); launch!(self, &format!("attn_prefill_{hd}"), cfg((t.div_ceil(64) as u32, nh as u32), 128, smem), q, kc, vc, qg, out, step, t as i32, nh as i32, nkv as i32, scale, qm, mw as i32, sink, win as i32); Ok(()) @@ -973,6 +975,75 @@ mod tests { } } + /// `attn_prefill_t` end to end (score product, causal softmax, P·V, the epilogue) against a CPU reference, at + /// head_dim 128 (32-key tiles) and 256 (the HIP build's 16-key tiles) with a partial last query tile. This is the + /// check the matrix-core score path needs on its own: a wrong lane/lane-staging mapping shows up as a large + /// per-element difference on a specific query or head, not as the near-tie token flips a parity run sees. + #[test] + fn attn_prefill_matches_cpu() { + use half::f16; + let Ok(gpu) = Gpu::new(0) else { eprintln!("skipping: no HIP device"); return }; + let g: &dyn Backend = &gpu; + let (t, nh, nkv) = (40usize, 4usize, 2usize); + let scale = 0.088388347; + for hd in [128usize, 256] { + let mut st = 99u32; + let mut rnd = || { st = st.wrapping_mul(1664525).wrapping_add(1013904223); (st >> 9) as f32 / 8388608.0 - 0.5 }; + let q: Vec = (0..t * nh * hd).map(|_| rnd()).collect(); + let kh: Vec = (0..t * nkv * hd).map(|_| f16::from_f32(rnd()).to_bits()).collect(); + let vh: Vec = (0..t * nkv * hd).map(|_| f16::from_f32(rnd()).to_bits()).collect(); + let half = |h: u16| f16::from_bits(h).to_f32(); + // Reference: the kernel scales Q before rounding it to f16, sums in f32, rounds the weights to f16 to + // feed P·V, and divides by the row sum at the end (`out = o * inv` with `inv = sc / den`). + let mut want = vec![0f32; t * nh * hd]; + for h in 0..nh { + let kvh = h / (nh / nkv); + for ti in 0..t { + let mut sc = vec![0f32; ti + 1]; + for (j, s) in sc.iter_mut().enumerate() { + let mut a = 0f32; + for d in 0..hd { + a += half(f16::from_f32(q[ti * nh * hd + h * hd + d] * scale).to_bits()) + * half(kh[(j * nkv + kvh) * hd + d]); + } + *s = a; + } + let mx = sc.iter().cloned().fold(f32::NEG_INFINITY, f32::max); + let e: Vec = sc.iter().map(|s| (s - mx).exp()).collect(); + let den: f32 = e.iter().sum(); + for d in 0..hd { + let mut a = 0f32; + for (j, w) in e.iter().enumerate() { + a += half(f16::from_f32(w / den).to_bits()) * half(vh[(j * nkv + kvh) * hd + d]); + } + want[ti * nh * hd + h * hd + d] = a; + } + } + } + let gq = g.alloc(4 * q.len()).unwrap(); + let gk = g.alloc(2 * kh.len()).unwrap(); + let gv = g.alloc(2 * vh.len()).unwrap(); + let go = g.alloc(4 * q.len()).unwrap(); + let gs = g.alloc(4).unwrap(); + g.put(&q, &gq, 0).unwrap(); + g.put(&kh, &gk, 0).unwrap(); + g.put(&vh, &gv, 0).unwrap(); + g.put(&[0i32], &gs, 0).unwrap(); + g.attn_prefill_m(gq.addr(), gk.addr(), gv.addr(), 0, go.addr(), gs.addr(), t, nh, nkv, hd, scale, 0, 0, 0, 0).unwrap(); + g.sync().unwrap(); + let got: Vec = g.get(&go, 0, q.len()).unwrap(); + let mut worst = 0f32; + let (mut at, mut gv_) = (0, 0f32); + for i in 0..q.len() { + let d = (got[i] - want[i]).abs(); + if d > worst { worst = d; at = i; gv_ = got[i]; } + } + eprintln!("hd {hd}: max |diff| = {worst:e} at {at} (row {}, head {}, d {}): got {gv_} want {}", + at / (nh * hd), (at / hd) % nh, at % hd, want[at]); + assert!(worst < 5e-3, "hd {hd}: max |diff| = {worst} at {at}"); + } + } + /// The generated source compiles for this device through hiprtc (the CUDA source with `STRATA_HIP` taken). #[test] fn hiprtc_compiles_the_kernels() { From 3d5cdf7be335b8ec734e7b789a6a8c210cec89e5 Mon Sep 17 00:00:00 2001 From: Hannes Klas Date: Mon, 16 Nov 2026 20:07:08 +0100 Subject: [PATCH 012/515] hip: prefill attention scores on the matrix cores attn_prefill_t's Q*K^T product was the last depth-dependent kernel family on the CUDA cores: it cost 8-11 ns per position of prompt depth against Vulkan's 5.6, and prefill fell behind Vulkan as prompts grew (pp 32k 794 tok/s against 1661). It now takes the same GEMM_WMMA instruction the prefill GEMM uses, one 16-query x 16-key tile per instruction against the 16-half qs/ks rows. The one thing the instruction does not give for free is where its results land: 8 per lane, column `lane & 15` and rows `8*(lane>>4) + i`, while the softmax, the causal/QSA mask and the P*V step all read the m16n8k16 layout (row g / g + 8, keys 2t / 2t + 1). So a warp writes its 16 x FA_BKL tile of f32 scores to a private staging tile and reads back the four values each lane owns in the layout below, `s[ng][2h + e] == S[warp*16 + g + 8h][ng*8 + 2t + e]`; one __syncwarp() publishes it, since a warp only reads what it wrote itself. The staging tile (FA_BQ x (FA_BKL + 8) floats) is added to the block's dynamic shared memory in hip::Gpu::attn_prefill_m only, so attn_prefill_smem_bk stays shared with CUDA and Vulkan. head_dim 256 takes 16 keys a step under STRATA_HIP (FA_BK_FOR, as the CUDA build already does on Turing's 64 KB blocks): 32 keys with the staging tile need 78 KiB and a workgroup may use 64. At 128k depth the same build does 660 tok/s against Vulkan's 731 (it was 173 against 762), decode 48.3 against 44.2. Measured on Qwen3.6-35B-A3B UD-Q4_K_XL, --mtp 0 --fixed-experts (same placement, same build, two runs each, one process each): pp 8192 1308 / 1303 -> 2556 / 2558 tok/s (Vulkan 2152 / 2148) pp 32768 794 / 776 -> 1677 / 1502 tok/s (Vulkan 1661) decode is unchanged (73-75 at 8k, 64-67 at 32k), and the depth slope of the per-token cost drops from 20-21 to 8-11 ns per position. HIP is now ahead of Vulkan at 8k and level at 32k; the P*V product below is the other half. Verified three ways. `hip::tests::attn_prefill_matches_cpu` (added with the ldsm4t fix) covers this path at both tile depths, 1.2e-4 / 1.7e-4 against a CPU reference. STRATA_HIP_WMMA=0 against this build gives bit-identical greedy output on a 79-token prompt and on the pp 8k/32k runs, so the summation order change is below the token decision. And greedy output is bit-identical to Vulkan on five long prose prompts (64-79 tokens, so through this kernel) on the 35B and two on the dense 9B with --fixed-experts --mtp 0, where the pre-fix build disagreed on 2 of 2 long prompts tried. The CUDA build's preprocessed source is unchanged (clang -E over GEMM_TC{0,1} x KV_Q8{0,1} x arch{700,750,800,900}: identical modulo blank lines and line markers). docs/HIP.md: the long-prompt section now reports the A/B, the slopes and pp 128k (660 tok/s against Vulkan's 731, up from 173 against 762), "Status" states what the parity check covers (bit-identical with --mtp 0; with the calibrated drafts on, the two backends verify different batch shapes and 1 of 7 probes flips at a near-tie), and "Next" is down to the P*V port and the side stream. --- docs/HIP.md | 83 +++++++++++++++++++++++++++++---------------- src/cuda/kernels.cu | 40 ++++++++++++++++++++-- src/hip/mod.rs | 11 +++--- 3 files changed, 98 insertions(+), 36 deletions(-) diff --git a/docs/HIP.md b/docs/HIP.md index 9b979903..bf22def1 100644 --- a/docs/HIP.md +++ b/docs/HIP.md @@ -4,13 +4,14 @@ build step: the kernels are compiled at run time by hiprtc and launched through the HIP runtime, both loaded by name (`libamdhip64.so`, `libhiprtc.so`), the way `src/cuda` loads NVRTC. `cargo build --release` is the whole build. -**Status: experimental.** Brought up on an RX 9070 XT (gfx1201, ROCm 7.2.3). With `--fixed-experts` (deterministic -placement) the greedy output is **bit-identical to the Vulkan backend** on the four local models tried (Qwen3.6-35B-A3B, -Ornith-1.5-35B-A3B, Qwen3.5-9B dense, Qwen3.8-27B dense) and to its own CUDA-core prefill on 5 of 6 prompts — the odd -one out differs at a near-tie, where the f16 tensor-core summation order picks another token (the same class of -difference the CUDA and Vulkan backends have; with adaptive placement, greedy tokens can also change between runs, as -they do on the other backends). Not yet ported: the host-side pipeline details of the CUDA backend (pinned ring staging -for `htod`, side stream for `beside`). +**Status: experimental.** Brought up on an RX 9070 XT (gfx1201, ROCm 7.2.3). With `--fixed-experts --mtp 0` +(deterministic placement, no speculative verify) the greedy output is **bit-identical to the Vulkan backend** on the +four local models tried (Qwen3.6-35B-A3B, Ornith-1.5-35B-A3B, Qwen3.5-9B dense, Qwen3.8-27B dense): five long prose +prompts (64-79 tokens, i.e. through the batched prefill and its attention) and two short ones on the 35B, two long ones +on the 9B. With the calibrated MTP drafts on (3 on this machine, 1 on Vulkan) the two backends verify different batch +shapes, so a near-tie can pick another token — 1 of those 7 probes does — and `--mtp 0` on both sides makes it agree. +HIP's prefill attention is pinned to a CPU f32 reference to 2e-4 by `hip::tests::attn_prefill_matches_cpu`. Not yet +ported: the host-side pipeline details of the CUDA backend (pinned ring staging for `htod`, side stream for `beside`). ## What runs @@ -34,25 +35,33 @@ completions, and the prompt cache across turns (`prompt_tokens_details.cached_to ## Long prompts -Prefill degrades with prompt depth on both backends (attention is the only depth-dependent term), but faster on HIP, -because the prefill attention still runs on the CUDA cores: only the prefill GEMM has an AMD matrix-core path so far. - -Qwen3.6-35B-A3B UD-Q4_K_XL, `--mtp 0 --reps 1 --vram-margin 256`, KV `f16`: - -| | HIP | Vulkan | -|---|---|---| -| pp 32k / gen at 32k | 670 / 80.8 tok/s | 1584 / 108.8 tok/s | -| pp 128k / gen at 128k | 173 / 59.2 tok/s | 762 / 83.4 tok/s | -| pp 8k, `--fixed-experts` | 1748 tok/s | 1938 tok/s | -| pp 32k, `--fixed-experts` | 720 tok/s | 1629 tok/s | -| dense Qwen3.8-27B, pp 8k / 32k | 601 / 328 tok/s | 475 / 404 tok/s | - -With placement equalised (`--fixed-experts`: same residents, zero swaps) decode is at parity (63.8 vs 66.0 tok/s) and -prefill loses 10% at 8k and 56% at 32k. Fitting the per-token cost against depth (HIP 572 -> 1389 us from 8k to 32k, -Vulkan 516 -> 614) gives a depth slope of 33 vs 4 ns per position: HIP's attention costs 8.4x more per position, and -that same fit predicts the 128k numbers (215 vs 995 tok/s) within the measurement's spread. Porting `attn_prefill_t` -to the matrix cores the way `gemm_q` was ported is the next step; until then, `--chunk 0`-style token-by-token prefill -is not the answer, but a shorter `--ctx` and `--kv q8` both buy expert slots back. +Prefill degrades with prompt depth on both backends (attention is the only depth-dependent term). The Q·Kᵀ score +product of the prefill attention runs on the card's matrix cores (below); the P·V product still runs on the CUDA cores, +which is where the remaining depth cost sits. + +Qwen3.6-35B-A3B UD-Q4_K_XL, `--mtp 0 --reps 1 --vram-margin 256`, KV `f16`, `--fixed-experts` (two runs where a +range is given, one process each): + +| pp | HIP | Vulkan | HIP, CUDA-core scores (`STRATA_HIP_WMMA=0`) | +|---|---|---|---| +| 8192 | 2556-2558 tok/s | 2148-2152 tok/s | 1303-1308 tok/s | +| 32768 | 1502-1677 tok/s | 1661 tok/s | 776-794 tok/s | +| 131072 | 660 tok/s | 731 tok/s | (not run) | +| decode at 8k / 32k / 128k | 73-75 / 64-67 / 48 tok/s | 71-72 / 68 / 44 tok/s | 74 / 64-65 / - | + +Fitting the per-token cost against depth gives a slope of 8-11 ns per position over 8k -> 32k (9.2 over 8k -> 128k) +for HIP and 5.6 over 8k -> 32k (7.3 over 8k -> 128k) for Vulkan, against 20-21 ns per position for HIP with the +CUDA-core scores — the matrix-core score product is worth **2x on prefill at depth** (pp 32k 794 -> 1677 tok/s, +pp 8k 1308 -> 2558 tok/s, same placement in the same build). At 128k HIP now does 660 tok/s against Vulkan's 731 +(prefill was 173 against 762) and is ahead on decode (48.3 against 44.2); at 32k the two are level, and at 8k HIP is +ahead. The earlier numbers in this file (pp 32k 720 tok/s, pp 128k 173, gen 80.8, slope 33 ns) were taken with the +CUDA-core scores and are the ones to compare against. `--chunk 0`-style token-by-token prefill is still not the +answer, but a shorter `--ctx` and `--kv q8` both buy expert slots back. + +Two caveats on the numbers: `--fixed-experts` only means "same residents, no re-placement during the run", so the +spread between two runs of the same build (1502 vs 1677 at 32k) is expert placement and host page-cache state, not the +kernel; and a prompt's depth cost is the fit over the two depths, not either point. A 128k prompt costs more VRAM in +the KV cache than a 16 GB card has left over for experts, so the run above streams most of them from host memory. ## How it works @@ -71,6 +80,20 @@ is not the answer, but a shorter `--ctx` and `--kv q8` both buy expert slots bac splits the k dimension across the two half-waves) and holds 8 results, column `lane & 15`, rows `8*(lane>>4) + i`. `STRATA_HIP_WMMA=0` falls back to the CUDA-core multiplications: 737 -> 1684 tok/s prefill at pp 1024 on the RX 9070 XT, and 5 of 6 prompts bit-identical between the two. +- **Matrix-core prefill attention** (`attn_prefill_t`): the same WMMA computes the Q·Kᵀ score tile, one 16-query x + 16-key instruction against the 16-half `qs`/`ks` rows. Its 8 results a lane land in AMD's layout (rows + `8*(lane>>4) + i`, column `lane & 15`) rather than the m16n8k16 layout the softmax, the causal mask and the P·V + step are written for, so the tile is staged through a warp-private f32 tile (`FA_BQ` x (`FA_BKL` + 8) floats, 4-6 + KiB on top of `qs`/`ks`/`vs`) and read back as `s[ng][2h + e] == S[warp*16 + g + 8h][ng*8 + 2t + e]`. That tile is + why head_dim 256 prefill takes 16 keys a step (`FA_BK_FOR`, as on Turing's 64 KB blocks): 32 keys would need 78 KiB + of a block's 64. The CUDA-core scores (`STRATA_HIP_WMMA=0`) and the matrix-core ones give the same greedy output on + the model, and the CPU-reference test covers both. +- The transposed V fragment (`ldsm4t`, the P·V operand) is the one CUDA-core multiplicand left in the attention: on HIP + it reads the two halves of a register as *adjacent* keys, which is what the `ldmatrix.trans` fragments mean. An + emulation that read them two rows apart (every even key counted twice, every odd one never) shipped with the first + HIP commit: it moved no token on the short prompts the parity checks used, and on the batched prefill it made every + long prompt disagree with Vulkan. `hip::tests::attn_prefill_matches_cpu` pins it now, and five long prompts agree + token for token with Vulkan afterwards. - `src/cuda/kernels.cu` keeps one source for both backends: the few places that cannot be shared are behind `#if STRATA_HIP` (f16 conversions, the per-lane fragment loads, `mma884`, the KV f16x2 math, the L2 prefetch hint), so the CUDA build's preprocessed source is unchanged. @@ -95,7 +118,8 @@ is not the answer, but a shorter `--ctx` and `--kv q8` both buy expert slots bac - `STRATA_HIP_TRACE=1` names every launch before it goes out (grid, block, shared memory). - `STRATA_HIP_GRAPH=0` runs the forward every time instead of capturing it (capture is on by default, +5% decode). - `STRATA_NO_GRAPH=1` turns capture off for both GPU backends. -- `STRATA_HIP_WMMA=0` uses the CUDA-core multiplications in the prefill GEMM instead of the matrices cores. +- `STRATA_HIP_WMMA=0` uses the CUDA-core multiplications in the prefill GEMM and the prefill attention instead of the + matrix cores. ## Why the prefill GEMM does not use int8 matrix cores @@ -115,8 +139,9 @@ memory and runs on the f16 matrix cores, which is what puts it ahead of the Vulk ## Next -1. The int8 WMMA form (`__builtin_amdgcn_wmma_i32_16x16x16_iu8`) for the integer-weight prefill GEMM, which today takes - the f16 path (`GEMM_TC 0`): less shared-memory traffic per output than the sm_80-style int8 `gemmi_*` kernels. +1. The P·V product of the prefill attention on the matrix cores (the score product is ported, see above): `A = P` from + the staging tile, `B = Vᵀ`, which needs transposed V fragments and an accumulator layout that does not match the + softmax's per-row `m`/`l` bookkeeping — stage it like the scores. Worth about the other half of the depth slope. 2. A side stream for `beside`, so expert uploads overlap with compute in prefill. ## Credits diff --git a/src/cuda/kernels.cu b/src/cuda/kernels.cu index aefc9b1b..9fa380d9 100644 --- a/src/cuda/kernels.cu +++ b/src/cuda/kernels.cu @@ -2483,7 +2483,8 @@ extern "C" __global__ void moe_combine_seq(float* x, const float* ye, const floa #endif #define FA_BK_DEFAULT FA_BK // Turing's 64 KB shared memory cannot hold the HD = 256 tile at 32 keys either: 16 fit (the kernel keeps the same -// 64 queries a block and four warps). The HIP build has the same 64 KB a workgroup, so it takes the same 16-key tile. +// 64 queries a block and four warps). The HIP build has the same 64 KB a workgroup, and its score staging tile comes +// on top of the qs/ks/vs/ps sizes, so it takes the same 16-key tile. #if (defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 750 && __CUDA_ARCH__ < 800) || STRATA_HIP #define FA_BK_FOR(HD) ((HD) == 256 ? 16 : FA_BK_DEFAULT) #else @@ -2510,6 +2511,14 @@ __device__ __forceinline__ void attn_prefill_t(const float* q, const u16* kc, co // Volta only: warp-private P tile for the PV A fragments (see the staging in the PV step below). Appended after // `vs` so the qs/ks/vs offsets above do not move; FA_BQ * (FA_BKL + 8) halves = 5120 B. u16* ps = vs + FA_BKL * PQ; +#endif +#if GEMM_WMMA + // HIP: the P staging tile in halves (the PV A fragments, as on Volta) and, after it, the f32 tile the matrix-core + // scores are staged through before they are read in the m16n8k16 layout the softmax below is written for. Both + // sit after `vs` so the qs/ks/vs offsets do not move; `hip::Gpu::attn_prefill_m` adds the f32 tile to the block's + // dynamic shared memory (FA_BQ * (FA_BKL + 8) floats, 4-8 KiB). + u16* ps = vs + FA_BKL * PQ; + float* st = (float*)(ps + FA_BQ * (FA_BKL + 8)); #endif // The last query tiles see the most keys: start them first so the short ones fill the tail. int pos0 = step[0], q0 = (gridDim.x - 1 - blockIdx.x) * FA_BQ, h = blockIdx.y, kvh = h / (nh / nkv), kvd = nkv * HD; @@ -2594,7 +2603,34 @@ __device__ __forceinline__ void attn_prefill_t(const float* q, const u16* kc, co bool skip = qm && !__any_sync(0xffffffff, (vis[0] | vis[1]) != 0); #endif float s[FA_BKL / 8][4] = {}; -#if __CUDA_ARCH__ < 800 && GEMM_TC +#if GEMM_WMMA + // Q K^T on the matrix cores: one 16-query x 16-key tile per instruction against the 16-half qs/ks rows, then + // staged and read back so the softmax keeps its m16n8k16 lane layout (row g / g + 8, keys 2t / 2t + 1). The + // warp writes and reads only its own 16 rows of the tile, so a warp barrier publishes it. + if (!skip) { + const int l16 = lane & 15, w0 = STRATA_WMMA_K0(lane), PW = FA_BKL + 8; + float* sw = st + warp * 16 * PW; + const u16* qrow = qs + (warp * 16 + l16) * PQ + w0; +#pragma unroll + for (int kg = 0; kg < FA_BKL / 16; kg++) { + strata_hip::strata_f8 acc; +#pragma unroll + for (int i = 0; i < 8; i++) acc[i] = 0.0f; + const u16* krow = ks + (kg * 16 + l16) * PQ + w0; +#pragma unroll + for (int kk = 0; kk < HD; kk += 16) + acc = strata_hip::strata_wmma(strata_hip::strata_ld_wmma(qrow + kk), strata_hip::strata_ld_wmma(krow + kk), acc); +#pragma unroll + for (int i = 0; i < 8; i++) sw[(8 * (lane >> 4) + i) * PW + kg * 16 + l16] = acc[i]; + } + __syncwarp(); +#pragma unroll + for (int ng = 0; ng < FA_BKL / 8; ng++) +#pragma unroll + for (int i = 0; i < 4; i++) + s[ng][i] = sw[(g + 8 * (i >> 1)) * PW + ng * 8 + 2 * t4 + (i & 1)]; + } +#elif __CUDA_ARCH__ < 800 && GEMM_TC // Same 16 f32 storage as s, seen as m8n8k4 D registers: s2[ng][j][4*p4 + 2*p2 + e] is S[8*j + (t & 1) + // 2*p2 + 4*hi][8*(4*ng + c) + (t & 2) + 4*p4 + e] of the 16 x FA_BKL score tile. Every lane holds the four // computations its c selects, so the warp must stay in uniform control flow (`skip` is warp-uniform). diff --git a/src/hip/mod.rs b/src/hip/mod.rs index e722d824..741e8acd 100644 --- a/src/hip/mod.rs +++ b/src/hip/mod.rs @@ -754,12 +754,13 @@ impl Backend for Gpu { fn attn_prefill_m(&self, q: u64, kc: u64, vc: u64, qg: u64, out: u64, step: u64, t: usize, nh: usize, nkv: usize, hd: usize, scale: f32, qm: u64, mw: usize, sink: u64, win: usize) -> anyhow::Result<()> { if !matches!(hd, 64 | 128 | 256) { bail!("attention prefill: head_dim {hd} unsupported (64, 128 or 256)"); } - // A tile of FA_BK keys needs 72 KiB at head_dim 256, more than a 64 KiB workgroup may use on RDNA; 16 keys a - // tile (the depth the CUDA build uses on Turing's 64 KB blocks) fits, at the cost of more passes. This has to - // be the depth the kernel picks for itself (`FA_BK_FOR(HD)`), not a smaller one: the kernel would then address - // shared memory past what is allocated. + // The tile depth has to be the one the kernel picks for itself (`FA_BK_FOR(HD)`, which takes 16 keys rather than + // 32 at head_dim 256): 32 keys plus the score staging tile need 78 KiB, more than a 64 KiB workgroup may use, + // while 16 keys need 58 KiB. A smaller depth here would under-allocate what the kernel addresses. let bk = if hd == 256 { 16 } else { FA_BK }; - let smem = attn_prefill_smem_bk(hd, bk) as u32; + // The HIP kernel stages its matrix-core scores through an extra FA_BQ x (bk + 8) f32 tile (see attn_prefill_t); + // the qs/ks/vs/ps sizes the shared helper computes are the same as CUDA's. + let smem = (attn_prefill_smem_bk(hd, bk) + 4 * crate::cuda::FA_BQ * (bk + 8)) as u32; anyhow::ensure!(smem as usize <= self.max_smem, "attn_prefill_{hd}: {smem} B of shared memory, {} allowed", self.max_smem); launch!(self, &format!("attn_prefill_{hd}"), cfg((t.div_ceil(64) as u32, nh as u32), 128, smem), q, kc, vc, qg, out, step, t as i32, nh as i32, nkv as i32, scale, qm, mw as i32, sink, win as i32); From 223a737621c2d84a63db377e530e8c8591858642 Mon Sep 17 00:00:00 2001 From: Hannes Klas Date: Mon, 16 Nov 2026 21:16:37 +0100 Subject: [PATCH 013/515] hip: prefill attention P*V on the matrix cores, and the depth cost is gone Both products of attn_prefill_t now run on the card's matrix cores. Q*K^T took the score tile two commits ago; this takes P*V, which had become the bigger half: with the scores ported, removing the P*V step entirely was worth pp 32k 1677 -> 2674 tok/s, i.e. 37-44% of the prefill time at that depth. A = P comes from the half staging tile the Volta path already had (ps, unused on HIP until now): the softmax's registers already hold adjacent key pairs of one row, so the tile is one 32-bit store a pair. B = V^T needs its operand's 16 rows to be head dimensions with the 16 k-values being keys, which no row of the V tile is, so strata_ld_wmma_t reads it down a column (one half a key apart) instead of through a 16-byte vector load. The results land in AMD's layout again (rows 8*(lane>>4)+i, column lane & 15), so each 16x16 tile is staged in f32 -- in the same warp-private `st` tile the scores use, which is free by then -- and read back into the two m16n8k16 dim tiles the rescale and the epilogue are written for. Reusing `st` is why the shared-memory request does not change. Measured on Qwen3.6-35B-A3B UD-Q4_K_XL, --mtp 0 --fixed-experts, same placement, same build: pp 8192 2556 / 2558 -> 2647 / 2666 tok/s (Vulkan 2148 / 2152) pp 32768 1677 / 1502 -> 2029 / 2026 tok/s (Vulkan 1661) pp 131072 660 -> 872 tok/s (Vulkan 731) The depth slope of the per-token cost is now 4.7 ns per position over 8k -> 32k against Vulkan's 5.6 (6.3 against 7.3 over 8k -> 128k), down from 20-21 with the attention on the CUDA cores: 3.4x on prefill at depth, and HIP is ahead of Vulkan at every depth tried. Decode is unmoved (68-73 / 64 / 48). The run-to-run spread also collapsed from 10% to under 1% at 32k, which says the P*V instruction count was what the CPU-side expert copies used to hide behind. hip::tests::attn_prefill_matches_cpu grew to head_dim 128 with 130 queries (three query tiles, five key tiles) and head_dim 256 with 70, and both are 1.5e-4 against the CPU reference (f16 rounding of q, k and the softmax weights), so the layout staging is pinned on both products; STRATA_HIP_WMMA=0 covers the CUDA-core path with the same test. Greedy parity with Vulkan (--fixed-experts --mtp 0) holds on 4 of 5 long prose prompts and 2 of 2 on the dense 9B; the fifth prompt flips at a near-tie after ten tokens, where all 5 agreed with P*V left on the CUDA cores -- the hardware sums a 16-deep dot product in another order than the emulation does. docs/HIP.md carries that, the new numbers and the refreshed short-prompt table (pp 4096 2993 against Vulkan's 2325; dense 27B pp 1024 784 against 508). --- docs/HIP.md | 118 ++++++++++++++++++++++++-------------------- src/cuda/kernels.cu | 42 +++++++++++++++- src/hip/compat.h | 10 ++++ src/hip/mod.rs | 15 +++--- 4 files changed, 124 insertions(+), 61 deletions(-) diff --git a/docs/HIP.md b/docs/HIP.md index bf22def1..66b7ee65 100644 --- a/docs/HIP.md +++ b/docs/HIP.md @@ -6,12 +6,16 @@ build step: the kernels are compiled at run time by hiprtc and launched through **Status: experimental.** Brought up on an RX 9070 XT (gfx1201, ROCm 7.2.3). With `--fixed-experts --mtp 0` (deterministic placement, no speculative verify) the greedy output is **bit-identical to the Vulkan backend** on the -four local models tried (Qwen3.6-35B-A3B, Ornith-1.5-35B-A3B, Qwen3.5-9B dense, Qwen3.8-27B dense): five long prose -prompts (64-79 tokens, i.e. through the batched prefill and its attention) and two short ones on the 35B, two long ones -on the 9B. With the calibrated MTP drafts on (3 on this machine, 1 on Vulkan) the two backends verify different batch -shapes, so a near-tie can pick another token — 1 of those 7 probes does — and `--mtp 0` on both sides makes it agree. -HIP's prefill attention is pinned to a CPU f32 reference to 2e-4 by `hip::tests::attn_prefill_matches_cpu`. Not yet -ported: the host-side pipeline details of the CUDA backend (pinned ring staging for `htod`, side stream for `beside`). +four local models tried (Qwen3.6-35B-A3B, Ornith-1.5-35B-A3B, Qwen3.5-9B dense, Qwen3.8-27B dense) for the decode +path, and on the batched prefill path 4 of 5 long prose prompts (64-79 tokens) agree token for token on the 35B +(head_dim 128), 2 of 2 on the dense 9B and 1 of 2 on the dense 27B: the fifth 35B prompt flips at a near-tie after +ten tokens, because the matrix cores sum a 16-deep dot product in a different order than Vulkan does (all 5 agree +with the P·V product left on the CUDA cores), and the 27B flips on its first token with either attention path — at +head_dim 256 it takes 16-key tiles where Vulkan goes deeper, so its softmax and P·V sum over more steps. With the +calibrated MTP drafts on (3 on this machine, 1 on Vulkan) the two backends verify different batch shapes, so 1 of +those 7 probes flips too. HIP's prefill attention is pinned to a CPU f32 reference to 2e-4 by +`hip::tests::attn_prefill_matches_cpu`. Not yet ported: the host-side pipeline details of the CUDA backend (pinned +ring staging for `htod`, side stream for `beside`). ## What runs @@ -19,48 +23,51 @@ Everything the Vulkan backend runs, through the same kernels: | | HIP | Vulkan (same machine, same model) | |---|---|---| -| Prefill, pp 1024, calibrated | 1577-2072 tok/s | 1344 tok/s | -| Prefill, pp 4096 | 2106 tok/s | (not run) | -| Decode, tg 48, calibrated | 188-222 tok/s | 195 tok/s | -| Qwen3.8-27B dense, prefill / decode | 705 / 50.3 tok/s | 497 / 55.5 tok/s | +| Prefill, pp 1024 / 4096, calibrated | 1104 / 2993 tok/s | 1097 / 2325 tok/s | +| Decode, tg 48, calibrated | 209 / 219 tok/s | 199 / 163 tok/s | +| Qwen3.8-27B dense, pp 1024, prefill / decode | 784 / 39.1 tok/s | 508 / 35.3 tok/s | Qwen3.6-35B-A3B UD-Q4_K_XL (first rows) and Qwen3.8-27B UD-IQ3_S, `--ctx 4096 --vram-margin 256`, one process each, -`calibrate` run for each backend (chunk 4096; HIP picks `--mtp 3`, Vulkan `--mtp 1`). Prefill runs on the card's matrix -cores (below) and is ahead of Vulkan; decode is within a few percent in either direction — the spread over repeated runs -is larger than the difference, because each backend finds its own expert placement and that moves the MTP draft -acceptance. A dense model's prefill is 1.4x ahead and its decode 10% behind (memory-bandwidth bound). +`calibrate` run for each backend (chunk 4096; HIP picks `--mtp 3`, Vulkan `--mtp 1`). Each cell is pp / the decode that +follows it, so the second value is throughput at that depth. The pp 1024 row runs first in the process, before expert +placement has settled, so it understates both backends (1577-2072 tok/s was measured for HIP there when it was not the +first row); pp 4096 is the honest short-prompt number and is 1.29x Vulkan's. Decode is within a few percent in either +direction — the spread over repeated runs is larger than the difference, because each backend finds its own expert +placement and that moves the MTP draft acceptance. A dense model's prefill is 1.5x ahead and its decode 11% ahead. `serve` works too, checked on Qwen3.5-9B: `GET /v1/models`, non-streaming and streaming (`stream: true`) chat completions, and the prompt cache across turns (`prompt_tokens_details.cached_tokens` on a follow-up request). ## Long prompts -Prefill degrades with prompt depth on both backends (attention is the only depth-dependent term). The Q·Kᵀ score -product of the prefill attention runs on the card's matrix cores (below); the P·V product still runs on the CUDA cores, -which is where the remaining depth cost sits. +Prefill degrades with prompt depth on both backends (attention is the only depth-dependent term), and the prefill +attention now runs both of its products on the card's matrix cores (below). Its per-position cost is now below +Vulkan's, which is where the depth-dependent deficit used to be. Qwen3.6-35B-A3B UD-Q4_K_XL, `--mtp 0 --reps 1 --vram-margin 256`, KV `f16`, `--fixed-experts` (two runs where a range is given, one process each): -| pp | HIP | Vulkan | HIP, CUDA-core scores (`STRATA_HIP_WMMA=0`) | +| pp | HIP | Vulkan | HIP, everything on the CUDA cores (`STRATA_HIP_WMMA=0`) | |---|---|---|---| -| 8192 | 2556-2558 tok/s | 2148-2152 tok/s | 1303-1308 tok/s | -| 32768 | 1502-1677 tok/s | 1661 tok/s | 776-794 tok/s | -| 131072 | 660 tok/s | 731 tok/s | (not run) | -| decode at 8k / 32k / 128k | 73-75 / 64-67 / 48 tok/s | 71-72 / 68 / 44 tok/s | 74 / 64-65 / - | - -Fitting the per-token cost against depth gives a slope of 8-11 ns per position over 8k -> 32k (9.2 over 8k -> 128k) -for HIP and 5.6 over 8k -> 32k (7.3 over 8k -> 128k) for Vulkan, against 20-21 ns per position for HIP with the -CUDA-core scores — the matrix-core score product is worth **2x on prefill at depth** (pp 32k 794 -> 1677 tok/s, -pp 8k 1308 -> 2558 tok/s, same placement in the same build). At 128k HIP now does 660 tok/s against Vulkan's 731 -(prefill was 173 against 762) and is ahead on decode (48.3 against 44.2); at 32k the two are level, and at 8k HIP is -ahead. The earlier numbers in this file (pp 32k 720 tok/s, pp 128k 173, gen 80.8, slope 33 ns) were taken with the -CUDA-core scores and are the ones to compare against. `--chunk 0`-style token-by-token prefill is still not the -answer, but a shorter `--ctx` and `--kv q8` both buy expert slots back. +| 8192 | 2647-2666 tok/s | 2148-2152 tok/s | 1303-1308 tok/s | +| 32768 | 2026-2029 tok/s | 1661 tok/s | 776-794 tok/s | +| 131072 | 872 tok/s | 731 tok/s | (not run) | +| decode at 8k / 32k / 128k | 68-73 / 64 / 48 tok/s | 71-72 / 68 / 44 tok/s | 74 / 64-65 / - | + +Fitting the per-token cost against depth gives a slope of 4.7 ns per position over 8k -> 32k (6.3 over 8k -> 128k) +for HIP against 5.6 (7.3) for Vulkan and 20-21 for HIP with the attention on the CUDA cores: **3.4x on prefill at +depth** (pp 32k 794 -> 2029 tok/s, pp 8k 1308 -> 2647, same placement in the same build), the score product worth 2x +of it (pp 32k 794 -> 1677) and the P·V product the rest (1677 -> 2029). HIP is now ahead of Vulkan at every depth +tried — 1.23x at 8k, 1.22x at 32k, 1.19x at 128k — and at parity or ahead on decode; the earlier numbers in this file +(pp 32k 720 tok/s, pp 128k 173, gen 80.8, slope 33 ns) were taken on the CUDA cores and are the ones to compare +against. `--chunk 0`-style token-by-token prefill is still not the answer, but a shorter `--ctx` and `--kv q8` both +buy expert slots back. Two caveats on the numbers: `--fixed-experts` only means "same residents, no re-placement during the run", so the -spread between two runs of the same build (1502 vs 1677 at 32k) is expert placement and host page-cache state, not the -kernel; and a prompt's depth cost is the fit over the two depths, not either point. A 128k prompt costs more VRAM in +spread between two runs of the same build was up to 10% before the P·V port (1502 vs 1677 at 32k) — expert placement +and host page-cache state, not the kernel — and has been under 1% since (2029 vs 2026), which is itself a sign of how +much of the prefill used to wait on the CPU-side copies; and a prompt's depth cost is the fit over the two depths, +not either point. A 128k prompt costs more VRAM in the KV cache than a 16 GB card has left over for experts, so the run above streams most of them from host memory. ## How it works @@ -80,20 +87,24 @@ the KV cache than a 16 GB card has left over for experts, so the run above strea splits the k dimension across the two half-waves) and holds 8 results, column `lane & 15`, rows `8*(lane>>4) + i`. `STRATA_HIP_WMMA=0` falls back to the CUDA-core multiplications: 737 -> 1684 tok/s prefill at pp 1024 on the RX 9070 XT, and 5 of 6 prompts bit-identical between the two. -- **Matrix-core prefill attention** (`attn_prefill_t`): the same WMMA computes the Q·Kᵀ score tile, one 16-query x - 16-key instruction against the 16-half `qs`/`ks` rows. Its 8 results a lane land in AMD's layout (rows - `8*(lane>>4) + i`, column `lane & 15`) rather than the m16n8k16 layout the softmax, the causal mask and the P·V - step are written for, so the tile is staged through a warp-private f32 tile (`FA_BQ` x (`FA_BKL` + 8) floats, 4-6 - KiB on top of `qs`/`ks`/`vs`) and read back as `s[ng][2h + e] == S[warp*16 + g + 8h][ng*8 + 2t + e]`. That tile is - why head_dim 256 prefill takes 16 keys a step (`FA_BK_FOR`, as on Turing's 64 KB blocks): 32 keys would need 78 KiB - of a block's 64. The CUDA-core scores (`STRATA_HIP_WMMA=0`) and the matrix-core ones give the same greedy output on - the model, and the CPU-reference test covers both. -- The transposed V fragment (`ldsm4t`, the P·V operand) is the one CUDA-core multiplicand left in the attention: on HIP - it reads the two halves of a register as *adjacent* keys, which is what the `ldmatrix.trans` fragments mean. An - emulation that read them two rows apart (every even key counted twice, every odd one never) shipped with the first - HIP commit: it moved no token on the short prompts the parity checks used, and on the batched prefill it made every - long prompt disagree with Vulkan. `hip::tests::attn_prefill_matches_cpu` pins it now, and five long prompts agree - token for token with Vulkan afterwards. +- **Matrix-core prefill attention** (`attn_prefill_t`): the same WMMA computes both products. Q·Kᵀ is one 16-query + x 16-key instruction against the 16-half `qs`/`ks` rows; P·V takes A = P from a half staging tile (the `ps` tile the + Volta path already had, unused on HIP until now, written from the softmax registers as half pairs) and B = Vᵀ read + down a column of the `vs` tile (`strata_ld_wmma_t`, one half a key apart, since that operand's rows are head + dimensions). + Both results land in AMD's layout — 8 a lane, rows `8*(lane>>4) + i`, column `lane & 15` — rather than the m16n8k16 + layout the softmax, the causal mask and the epilogue are written for, so each 16x16 result tile is staged in f32 + and read back as `s[ng][2h + e] == S[warp*16 + g + 8h][ng*8 + 2t + e]` (scores) or `o[d][2r + e]` (P·V). One warp + staging tile serves both stages (`FA_BQ` x (`FA_BKL` + 8) floats, 4-6 KiB added to the block's dynamic shared + memory), and it is why head_dim 256 prefill takes 16 keys a step (`FA_BK_FOR`, as on Turing's 64 KB blocks): 32 + keys would need 78 KiB of a block's 64. `STRATA_HIP_WMMA=0` runs the same numerics on the CUDA cores; the + CPU-reference test covers both. +- The CUDA-core P·V path (`ldsm4t` + `mma16816`) is still there for `STRATA_HIP_WMMA=0` and for CUDA, and it is + worth knowing how it is shaped: on HIP it reads the two halves of a transposed register as *adjacent* keys, which is + what the `ldmatrix.trans` fragments mean. An emulation that read them two rows apart (every even key counted twice, + every odd one never) shipped with the first HIP commit: it moved no token on the short prompts the parity checks + used, and on the batched prefill it made every long prompt disagree with Vulkan. `hip::tests:: + attn_prefill_matches_cpu` pins it now. - `src/cuda/kernels.cu` keeps one source for both backends: the few places that cannot be shared are behind `#if STRATA_HIP` (f16 conversions, the per-lane fragment loads, `mma884`, the KV f16x2 math, the L2 prefetch hint), so the CUDA build's preprocessed source is unchanged. @@ -118,8 +129,8 @@ the KV cache than a 16 GB card has left over for experts, so the run above strea - `STRATA_HIP_TRACE=1` names every launch before it goes out (grid, block, shared memory). - `STRATA_HIP_GRAPH=0` runs the forward every time instead of capturing it (capture is on by default, +5% decode). - `STRATA_NO_GRAPH=1` turns capture off for both GPU backends. -- `STRATA_HIP_WMMA=0` uses the CUDA-core multiplications in the prefill GEMM and the prefill attention instead of the - matrix cores. +- `STRATA_HIP_WMMA=0` uses the CUDA-core multiplications in the prefill GEMM and in both products of the prefill + attention instead of the matrix cores. ## Why the prefill GEMM does not use int8 matrix cores @@ -139,10 +150,11 @@ memory and runs on the f16 matrix cores, which is what puts it ahead of the Vulk ## Next -1. The P·V product of the prefill attention on the matrix cores (the score product is ported, see above): `A = P` from - the staging tile, `B = Vᵀ`, which needs transposed V fragments and an accumulator layout that does not match the - softmax's per-row `m`/`l` bookkeeping — stage it like the scores. Worth about the other half of the depth slope. -2. A side stream for `beside`, so expert uploads overlap with compute in prefill. +1. A side stream for `beside`, so expert uploads overlap with compute in prefill (the 8k prefill still moves a lot of + expert data per chunk, and the run-to-run spread collapsing from 10% to 1% with the faster attention says the + copies now wait on the CPU less than they used to). +2. The decode path: no matrix cores on either backend there (it is memory-bound), but the prefill attention's `FA_BKL` + of 16 at head_dim 256 is a shared-memory compromise — a 32-key tile would need 78 KiB. Not worth chasing. ## Credits diff --git a/src/cuda/kernels.cu b/src/cuda/kernels.cu index 9fa380d9..d0ea2875 100644 --- a/src/cuda/kernels.cu +++ b/src/cuda/kernels.cu @@ -2759,7 +2759,47 @@ __device__ __forceinline__ void attn_prefill_t(const float* q, const u16* kc, co cp_async_wait<1>(); // sm_80+: this V tile, the next K tile may still be in flight; sm_70: already copied here __syncthreads(); #endif -#if __CUDA_ARCH__ < 800 && GEMM_TC +#if GEMM_WMMA + // P * V on the matrix cores, the way the scores are: A = P (this warp's 16 query rows x the tile's keys, in + // halves), B = V^T (16 head dimensions x the same keys, one half a tile row apart). The lane's 8 results land + // in AMD's layout again (query rows 8*(lane>>4) + i, dim column lane & 15), so each 16 x 16 result tile is + // staged in f32 and read back as the two m16n8k16 dim tiles the rescale above, the epilogue below and the + // score stage all use (`st` is free again by now: it held the scores of this tile). + if (!skip) { + const int l16 = lane & 15, w0 = STRATA_WMMA_K0(lane), PW = FA_BKL + 8; +#pragma unroll + for (int ng = 0; ng < FA_BKL / 8; ng++) { + // P in halves, one 32-bit store a half pair (keys 2t / 2t+1 are adjacent in this lane's registers) + *(u32*)(ps + (warp * 16 + g) * PW + ng * 8 + 2 * t4) = h2pack(s[ng][0], s[ng][1]); + *(u32*)(ps + (warp * 16 + g + 8) * PW + ng * 8 + 2 * t4) = h2pack(s[ng][2], s[ng][3]); + } + __syncwarp(); + float* sw = st + warp * 256; +#pragma unroll + for (int dt = 0; dt < HD / 16; dt++) { + strata_hip::strata_f8 acc; +#pragma unroll + for (int i = 0; i < 8; i++) acc[i] = 0.0f; +#pragma unroll + for (int kg = 0; kg < FA_BKL / 16; kg++) { + const u16* pa = ps + (warp * 16 + l16) * PW + kg * 16 + w0; + const u16* pb = vs + (kg * 16 + w0) * PQ + dt * 16 + l16; + acc = strata_hip::strata_wmma(strata_hip::strata_ld_wmma(pa), strata_hip::strata_ld_wmma_t(pb, PQ), acc); + } +#pragma unroll + for (int i = 0; i < 8; i++) sw[(8 * (lane >> 4) + i) * 16 + l16] = acc[i]; + __syncwarp(); +#pragma unroll + for (int r = 0; r < 2; r++) +#pragma unroll + for (int e = 0; e < 2; e++) { + o[2 * dt][2 * r + e] += sw[(g + 8 * r) * 16 + 2 * t4 + e]; + o[2 * dt + 1][2 * r + e] += sw[(g + 8 * r) * 16 + 8 + 2 * t4 + e]; + } + __syncwarp(); + } + } +#elif __CUDA_ARCH__ < 800 && GEMM_TC // P -> the warp-private staging tile: the m8n8k4 A fragment of the PV product wants row t + 4*hi and four // contiguous keys per lane, which the QK^T D layout does not give for free. One 32-bit store per half pair; // the __syncwarp() publishes the tile to the mma step below (the next tile's stores follow the loop's diff --git a/src/hip/compat.h b/src/hip/compat.h index f0f676ab..6202692a 100644 --- a/src/hip/compat.h +++ b/src/hip/compat.h @@ -124,6 +124,16 @@ __device__ __forceinline__ strata_hk strata_ld_wmma(const unsigned short* p) { for (int i = 0; i < STRATA_WMMA_K / 8; i++) c.u[i] = *(const uint4*)(p + 8 * i); return c.h; } + +/// The same STRATA_WMMA_K halves one tile row apart from each other: the B operand when the operand's rows are the +/// transposed side (the prefill attention's V, whose rows are head dimensions and whose k are keys). One load a have +/// instead of a 16-byte vector load. +__device__ __forceinline__ strata_hk strata_ld_wmma_t(const unsigned short* p, int stride) { + strata_hk r; +#pragma unroll + for (int i = 0; i < STRATA_WMMA_K; i++) r[i] = *(const _Float16*)(p + i * stride); + return r; +} #endif } // namespace strata_hip diff --git a/src/hip/mod.rs b/src/hip/mod.rs index 741e8acd..84d0726e 100644 --- a/src/hip/mod.rs +++ b/src/hip/mod.rs @@ -977,17 +977,18 @@ mod tests { } /// `attn_prefill_t` end to end (score product, causal softmax, P·V, the epilogue) against a CPU reference, at - /// head_dim 128 (32-key tiles) and 256 (the HIP build's 16-key tiles) with a partial last query tile. This is the - /// check the matrix-core score path needs on its own: a wrong lane/lane-staging mapping shows up as a large - /// per-element difference on a specific query or head, not as the near-tie token flips a parity run sees. + /// head_dim 128 with three query tiles and five key tiles and at head_dim 256 (the HIP build's 16-key tiles). + /// A wrong lane/lane-staging mapping, a lost half of a fragment or a missing key shows up as a large per-element + /// difference on a specific query or head — which is how the transposed-V bug below was found — rather than as + /// the near-tie token flip a parity run sees. #[test] fn attn_prefill_matches_cpu() { use half::f16; let Ok(gpu) = Gpu::new(0) else { eprintln!("skipping: no HIP device"); return }; let g: &dyn Backend = &gpu; - let (t, nh, nkv) = (40usize, 4usize, 2usize); - let scale = 0.088388347; - for hd in [128usize, 256] { + let (nh, nkv) = (4usize, 2usize); + for (hd, t) in [(128usize, 130usize), (256, 70)] { + let scale = 1.0 / (hd as f32).sqrt(); let mut st = 99u32; let mut rnd = || { st = st.wrapping_mul(1664525).wrapping_add(1013904223); (st >> 9) as f32 / 8388608.0 - 0.5 }; let q: Vec = (0..t * nh * hd).map(|_| rnd()).collect(); @@ -1039,7 +1040,7 @@ mod tests { let d = (got[i] - want[i]).abs(); if d > worst { worst = d; at = i; gv_ = got[i]; } } - eprintln!("hd {hd}: max |diff| = {worst:e} at {at} (row {}, head {}, d {}): got {gv_} want {}", + eprintln!("hd {hd} T {t}: max |diff| = {worst:e} at {at} (row {}, head {}, d {}): got {gv_} want {}", at / (nh * hd), (at / hd) % nh, at % hd, want[at]); assert!(worst < 5e-3, "hd {hd}: max |diff| = {worst} at {at}"); } From 7d7a0eb4a4c2bfcef27660b1d7a52c51c5688330 Mon Sep 17 00:00:00 2001 From: Hannes Klas Date: Tue, 17 Nov 2026 06:52:40 +0100 Subject: [PATCH 014/515] hip: deltanet_seq measured, and left alone The gated delta-rule scan behind Qwen3.6/3.8's linear-attention layers is 12% of a long-prompt prefill (the second largest kernel after the prefill GEMM), and the obvious guess -- "it is a sequential scan with redundant loads, so give it more parallelism or fewer loads" -- is wrong in every direction. Measured with a new probe, tools/hip/deltanet.cpp, which times the scan alone at the 35B's shape (dk 128, nk 16, nv 32, dv 128, T 4096, 128 blocks) at 3.11 ms a layer, ~1750 cycles a token. A model-level prefill A/B cannot resolve this: two runs of the same build differ by more than any of the variants gain. base (16 floats a lane, `tok * stride` in the loop) 3.11 ms 1.00x 32 floats a lane (half the blocks, one wave on 60 CUs) 3.84 ms 0.81x loop address math hoisted into pointer increments 3.26 ms 0.93x dot-product accumulators split in two 3.22 ms 0.96x every token re-reading token 0's q/k/v (L1-resident) 3.13 ms 0.99x no per-token expf(g) for the decay 2.76 ms 1.12x no warp reductions (wrong results) 2.33 ms 1.33x So the kernel is latency, not bandwidth (the reads are free, with all of the redundancy), and the only parts with headroom are the two dependent warp-reduction rounds and the per-token exp -- both properties of the sequential recurrence, removable only by the chunked WY/UT-transform form (a small triangular inverse plus matmuls over a chunk). That form wants f32 for the state, so it would not use the tensor cores, and 12% of prefill is the whole prize: ~4%. Not done, deliberately, and now with the numbers to back that up instead of a hand-wave. docs/HIP.md gains a "What is left, measured" section: the kernel-time profile of a prefill and of a decode step (~90% of decode is the CPU expert worker's latency, not GPU), and this table. tools/hip/README.md lists the probe. --- docs/HIP.md | 31 +++++- tools/hip/README.md | 6 + tools/hip/deltanet.cpp | 246 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 278 insertions(+), 5 deletions(-) create mode 100644 tools/hip/deltanet.cpp diff --git a/docs/HIP.md b/docs/HIP.md index 66b7ee65..10d41d74 100644 --- a/docs/HIP.md +++ b/docs/HIP.md @@ -148,13 +148,34 @@ the time of f16, with a vector-friendly rescale 6.6x *slower*, with the layout t integer path cannot pay for itself here, so `GEMM_TC` stays 0 on HIP and the prefill GEMM dequantizes to f16 in shared memory and runs on the f16 matrix cores, which is what puts it ahead of the Vulkan backend. +## What is left, measured + +Profiled on the same 35B prefill (`rocprofv3 --kernel-trace`, pp 4096): 54% of the kernel time is the quantized +prefill GEMM (already on the matrix cores), 12% the gated delta-rule scan `deltanet_seq`, 10% the prefill attention +(ported), and nothing else above 3%. Of a decode step's wall time, ~90% is not GPU at all — `moe_combine` spends most +of its time waiting on the CPU expert worker, which is an expert-tier question, not a kernel one. + +`deltanet_seq` is the one kernel left worth a look, and it has now been measured properly rather than guessed at +(`tools/hip/deltanet.cpp`, which times the scan alone at the 35B's shape): + +- its per-token latency (~1750 cycles) is **not** memory: a variant that re-reads token 0's q/k/v every step, so the + reads stay in L1, runs just as fast (1.00x), even though the scan as written re-reads them from 128 blocks. +- no rearrangement of the scan wins: 32 floats a lane instead of 16 (half the blocks, one wave on 60 CUs) is 0.81x, + hoisting the loop's `tok * stride` address math into pointer increments is 0.93x, splitting the dot-product + accumulators is 0.96x, combinations worse. +- the parts with headroom are the two dependent warp-reduction rounds (1.33x if both are removed, wrong results) and + the per-token `expf(g)` for the decay (1.12x). Both are properties of the *sequential* recurrence: they only go + away with the chunked WY/UT-transform form (a small triangular inverse plus a few matmuls over a chunk), which + wants f32 for the state and therefore does not get tensor cores. + +Since the whole kernel is 12% of prefill, that rewrite's ceiling is ~4% of prefill. Left alone deliberately. + ## Next -1. A side stream for `beside`, so expert uploads overlap with compute in prefill (the 8k prefill still moves a lot of - expert data per chunk, and the run-to-run spread collapsing from 10% to 1% with the faster attention says the - copies now wait on the CPU less than they used to). -2. The decode path: no matrix cores on either backend there (it is memory-bound), but the prefill attention's `FA_BKL` - of 16 at head_dim 256 is a shared-memory compromise — a 32-key tile would need 78 KiB. Not worth chasing. +1. A side stream for `beside`, so expert uploads overlap with compute in prefill (the run-to-run spread collapsing + from 10% to 1% with the faster attention says the copies now wait on the CPU less than they used to). +2. Decode on an MoE model: the expert residency policy, not a kernel. That is where the multi-x is (see the reference + numbers from Strata in the handoff). ## Credits diff --git a/tools/hip/README.md b/tools/hip/README.md index bf5b4c7e..4ddd5b3a 100644 --- a/tools/hip/README.md +++ b/tools/hip/README.md @@ -8,6 +8,12 @@ hipcc --offload-arch=gfx1201 -O3 wmma_rate.cpp -o wmma_rate && ./wmma_rate hipcc --offload-arch=gfx1201 -O3 wmma_rescale.cpp -o wmma_rescale && ./wmma_rescale ``` +- `deltanet.cpp`: the gated delta-rule scan (`deltanet_seq`) alone, at the 35B model's shape, with the variants that + were tried against it: fewer, fatter lanes, two accumulators a dot sum, the loop's address math hoisted into + pointer increments, and two ablations (the per-token `expf`, the two warp reductions). All of them are neutral or + slower; the reads are free (a variant that re-reads token 0 every step is as fast), and the reductions plus the + exp are the only parts with headroom — which is the chunked WY form's job, not a rearrangement of the scan. The + file's header carries the numbers. - `wmma_rate.cpp`: the matrix-core instruction rate of the two operand types, operands in registers, so the numbers are the instruction rate and not memory bandwidth. On RX 9070 XT (gfx1201): f16 57 TMAC/s, int8 137 TMAC/s. - `wmma_rescale.cpp`: the inner-loop shape of the prefill GEMM (`gemm_q`: 2x2 tiles of 16x16, four 16-deep k-steps per diff --git a/tools/hip/deltanet.cpp b/tools/hip/deltanet.cpp new file mode 100644 index 00000000..febc8bdd --- /dev/null +++ b/tools/hip/deltanet.cpp @@ -0,0 +1,246 @@ +// deltanet_seq (the gated delta-rule scan that Qwen3.6/3.8's linear-attention layers run in prefill) in isolation. +// Answering "can this kernel be made faster without changing the algorithm", with numbers instead of guesses: a +// model-level prefill A/B cannot resolve a 5% change (two runs of the same build differ by more), so the variants are +// timed here. Fixed shape of the 35B model: dk 128, nk 16, nv 32, dv 128, T 4096, i.e. 128 blocks of 256 threads. +// +// hipcc --offload-arch=gfx1201 -O3 deltanet.cpp -o deltanet && ./deltanet +// +// Measured on RX 9070 XT (3.11 ms for one layer's scan over 4096 tokens, ~1750 cycles a token; the ratios move by +// +-4% between runs, so treat anything under 5% as noise): +// +// base 3.11 ms 1.00x deltanet_seq as committed +// dn16 (running pointers) 3.26 ms 0.93x the loop's `tok * stride` products hoisted into pointer increments +// dn16s (+ 2 accumulators) 3.22 ms 0.96x one chain of 16 dependent adds split in two +// dn32 (32 floats a lane) 3.84 ms 0.81x half the blocks (one wave on 60 CUs), twice the work a lane +// dn32s 3.73 ms 0.83x +// no expf(g) per token 2.76 ms 1.12x the per-token decay, which only half the calls need as an exp +// no warp reductions 2.33 ms 1.33x both dependent shuffle rounds removed (wrong results, timing only) +// same q/k/v every step 3.13 ms 0.99x per-token reads held in L1: the strided, 128-block-redundant reads +// cost nothing, so this kernel is latency, not bandwidth +// +// So: no rearrangement of the scan wins (several lose), the reads are free, and the 33% inside reach is the two +// dependent shuffle rounds plus the per-token exp -- both of which only disappear if the per-token recurrence +// becomes a chunked one (the WY/UT-transform form: a triangular inverse and matmuls over a chunk, and with f16 +// tensor cores it would lose state precision). 12% of a 4096-token prefill is in this kernel, so the whole +// theoretical prize is ~4% prefill for that rewrite. Left alone deliberately. +#include +#include +#include +#include +#include +typedef unsigned short u16; +__device__ __forceinline__ float sigmoid(float x) { return 1.0f / (1.0f + expf(-x)); } +__device__ __forceinline__ float softplus(float x) { return x > 20.0f ? x : log1pf(expf(x)); } +// kernels.cu's HIP shim routes the mask-less form here; the HIP builtin itself wants a 64-bit mask. +template __device__ __forceinline__ T shflx(T v, int off) { return __shfl_xor(v, off, 32); } +__global__ void dn_base(const float* y, float* S, const float* beta, const float* g, float* o, + int nk, int nv, int ilv, int dk, int dv, float scale, int T, int ych, float* snap, int nsnap, + const float* dtb, const float* ga) { + int L = dk >> 4, R = 32 / L, lane = threadIdx.x & 31, s = lane % L, vh = blockIdx.x, kh = ilv ? vh / (nv / nk) : vh % nk; + int j0 = (blockIdx.y * 8 + (threadIdx.x >> 5)) * R, j = j0 + lane / L; + if (j0 >= dv) return; // whole warp past the end (R divides dv) + float4* row = (float4*)(S + ((size_t)vh * dv + j) * dk); + float r[16]; +#pragma unroll + for (int i = 0; i < 4; i++) { float4 v = row[s + L * i]; r[4 * i] = v.x; r[4 * i + 1] = v.y; r[4 * i + 2] = v.z; r[4 * i + 3] = v.w; } + // Token inputs do not depend on the state: token tok + 1's are loaded while token tok computes. + float nk_[16], nq[16], ng, nb, nvv; + auto ld = [&](int tok) { + const float* yt = y + (size_t)tok * ych; + const float4* q4 = (const float4*)(yt + kh * dk); + const float4* k4 = (const float4*)(yt + nk * dk + kh * dk); +#pragma unroll + for (int i = 0; i < 4; i++) { + float4 v = k4[s + L * i]; nk_[4 * i] = v.x; nk_[4 * i + 1] = v.y; nk_[4 * i + 2] = v.z; nk_[4 * i + 3] = v.w; + v = q4[s + L * i]; nq[4 * i] = v.x; nq[4 * i + 1] = v.y; nq[4 * i + 2] = v.z; nq[4 * i + 3] = v.w; + } + ng = g[tok * nv + vh]; nb = beta[tok * nv + vh]; nvv = yt[2 * nk * dk + vh * dv + j]; + if (dtb) { ng = softplus(ng + dtb[vh]) * ga[vh]; nb = sigmoid(nb); } + }; + ld(0); + for (int tok = 0; tok < T; tok++) { + float kk[16], qv[16], decay = expf(ng), bt = nb, vt = nvv, sk = 0.0f, oq = 0.0f; +#pragma unroll + for (int e = 0; e < 16; e++) { kk[e] = nk_[e]; qv[e] = nq[e]; } + if (tok + 1 < T) ld(tok + 1); +#pragma unroll + for (int e = 0; e < 16; e++) { r[e] *= decay; sk += r[e] * kk[e]; } + for (int off = L >> 1; off; off >>= 1) sk += shflx(sk, off); + float d = bt * (vt - sk); +#pragma unroll + for (int e = 0; e < 16; e++) { r[e] += d * kk[e]; oq += r[e] * qv[e]; } + for (int off = L >> 1; off; off >>= 1) oq += shflx(oq, off); + if (s == 0) o[(size_t)tok * nv * dv + vh * dv + j] = oq * scale; + if (tok < min(nsnap, T - 1)) { + float4* sr = (float4*)(snap + (size_t)tok * nv * dv * dk + ((size_t)vh * dv + j) * dk); +#pragma unroll + for (int i = 0; i < 4; i++) sr[s + L * i] = make_float4(r[4 * i], r[4 * i + 1], r[4 * i + 2], r[4 * i + 3]); + } + } +#pragma unroll + for (int i = 0; i < 4; i++) row[s + L * i] = make_float4(r[4 * i], r[4 * i + 1], r[4 * i + 2], r[4 * i + 3]); +} + +template +__device__ __forceinline__ void dn_opt(const float* y, float* S, const float* beta, const float* g, float* o, + int nk, int nv, int ilv, int dk, int dv, float scale, int T, int ych, float* snap, int nsnap, + const float* dtb, const float* ga) { + int L = dk / DNP, R = 32 / L, lane = threadIdx.x & 31, s = lane % L, vh = blockIdx.x, kh = ilv ? vh / (nv / nk) : vh % nk; + int j0 = (blockIdx.y * (int)(blockDim.x >> 5) + (threadIdx.x >> 5)) * R, j = j0 + lane / L; + if (j0 >= dv) return; // whole warp past the end (R divides dv) + float4* row = (float4*)(S + ((size_t)vh * dv + j) * dk); + float r[DNP]; +#pragma unroll + for (int i = 0; i < DNP / 4; i++) { float4 v = row[s + L * i]; r[4 * i] = v.x; r[4 * i + 1] = v.y; r[4 * i + 2] = v.z; r[4 * i + 3] = v.w; } + // Running pointers, one step per token: the loop body used to recompute `tok * stride` (and the 64-bit + // multiplies and divides that drag in) for every operand, which was most of its instruction count. + const float4* kp = (const float4*)(y + (size_t)kh * dk); // chunk s + L*i of this lane's row + const float4* qp = (const float4*)(y + (size_t)(nk + kh) * dk); + const float* vp = y + (size_t)2 * nk * dk + (size_t)vh * dv + j; // token's v[j] + const float* gp = g + vh, *bp = beta + vh; // this head's decay gate and beta + float* op = o + (size_t)vh * dv + j; // token's output element + float* sp = snap + (size_t)((size_t)vh * dv + j) * dk; // snapshot of this lane's chunks + const int kstep = ych / 4, snapstep = nv * dv * dk; + const int ns = min(nsnap, T - 1); + // Token inputs do not depend on the state: token tok + 1's are loaded while token tok computes. + float nk_[DNP], nq[DNP], ng, nb, nvv; + auto ld = [&]() { +#pragma unroll + for (int i = 0; i < DNP / 4; i++) { + float4 v = kp[s + L * i]; nk_[4 * i] = v.x; nk_[4 * i + 1] = v.y; nk_[4 * i + 2] = v.z; nk_[4 * i + 3] = v.w; + v = qp[s + L * i]; nq[4 * i] = v.x; nq[4 * i + 1] = v.y; nq[4 * i + 2] = v.z; nq[4 * i + 3] = v.w; + } + ng = *gp; nb = *bp; nvv = *vp; + if constexpr (false) { ng = softplus(ng + dtb[vh]) * ga[vh]; nb = sigmoid(nb); } + kp += kstep; qp += kstep; gp += nv; bp += nv; vp += ych; + }; + ld(); + for (int tok = 0; tok < T; tok++) { + float kk[DNP], qv[DNP], decay = PROBE == 1 ? 0.99f : expf(ng), bt = nb, vt = nvv, sk = 0.0f, oq = 0.0f; +#pragma unroll + for (int e = 0; e < DNP; e++) { kk[e] = nk_[e]; qv[e] = nq[e]; } + if (tok + 1 < T) ld(); + float sk1 = 0.0f, oq1 = 0.0f; + if constexpr (SPLIT) { +#pragma unroll + for (int e = 0; e < DNP; e += 2) { r[e] *= decay; r[e + 1] *= decay; sk += r[e] * kk[e]; sk1 += r[e + 1] * kk[e + 1]; } + sk += sk1; + } else { +#pragma unroll + for (int e = 0; e < DNP; e++) { r[e] *= decay; sk += r[e] * kk[e]; } + } + if (PROBE != 2) for (int off = L >> 1; off; off >>= 1) sk += shflx(sk, off); + float d = bt * (vt - sk); + if constexpr (SPLIT) { +#pragma unroll + for (int e = 0; e < DNP; e += 2) { r[e] += d * kk[e]; r[e + 1] += d * kk[e + 1]; oq += r[e] * qv[e]; oq1 += r[e + 1] * qv[e + 1]; } + oq += oq1; + } else { +#pragma unroll + for (int e = 0; e < DNP; e++) { r[e] += d * kk[e]; oq += r[e] * qv[e]; } + } + if (PROBE != 2) for (int off = L >> 1; off; off >>= 1) oq += shflx(oq, off); + if (s == 0) *op = oq * scale; + if (tok < ns) { + float4* sr = (float4*)sp; +#pragma unroll + for (int i = 0; i < DNP / 4; i++) sr[s + L * i] = make_float4(r[4 * i], r[4 * i + 1], r[4 * i + 2], r[4 * i + 3]); + } + op += nv * dv; sp += snapstep; + } +#pragma unroll + for (int i = 0; i < DNP / 4; i++) row[s + L * i] = make_float4(r[4 * i], r[4 * i + 1], r[4 * i + 2], r[4 * i + 3]); +} + +__global__ void dn16(const float* y, float* S, const float* beta, const float* g, float* o, + int nk, int nv, int ilv, int dk, int dv, float scale, int T, int ych, float* snap, int nsnap, + const float* dtb, const float* ga) { + dn_opt<16, false>(y, S, beta, g, o, nk, nv, ilv, dk, dv, scale, T, ych, snap, nsnap, dtb, ga); +} +__global__ void dn32(const float* y, float* S, const float* beta, const float* g, float* o, + int nk, int nv, int ilv, int dk, int dv, float scale, int T, int ych, float* snap, int nsnap, + const float* dtb, const float* ga) { + dn_opt<32, false>(y, S, beta, g, o, nk, nv, ilv, dk, dv, scale, T, ych, snap, nsnap, dtb, ga); +} +__global__ void dn16s(const float* y, float* S, const float* beta, const float* g, float* o, + int nk, int nv, int ilv, int dk, int dv, float scale, int T, int ych, float* snap, int nsnap, + const float* dtb, const float* ga) { + dn_opt<16, true>(y, S, beta, g, o, nk, nv, ilv, dk, dv, scale, T, ych, snap, nsnap, dtb, ga); +} +__global__ void dn32s(const float* y, float* S, const float* beta, const float* g, float* o, + int nk, int nv, int ilv, int dk, int dv, float scale, int T, int ych, float* snap, int nsnap, + const float* dtb, const float* ga) { + dn_opt<32, true>(y, S, beta, g, o, nk, nv, ilv, dk, dv, scale, T, ych, snap, nsnap, dtb, ga); +} + +__global__ void dn16x(const float* y, float* S, const float* beta, const float* g, float* o, + int nk, int nv, int ilv, int dk, int dv, float scale, int T, int ych, float* snap, int nsnap, + const float* dtb, const float* ga) { + dn_opt<16, false, 1>(y, S, beta, g, o, nk, nv, ilv, dk, dv, scale, T, ych, snap, nsnap, dtb, ga); +} +__global__ void dn16r(const float* y, float* S, const float* beta, const float* g, float* o, + int nk, int nv, int ilv, int dk, int dv, float scale, int T, int ych, float* snap, int nsnap, + const float* dtb, const float* ga) { + dn_opt<16, false, 2>(y, S, beta, g, o, nk, nv, ilv, dk, dv, scale, T, ych, snap, nsnap, dtb, ga); +} +// --------------------------------------------------------------------------------------------------------------- +constexpr int DKN = 128, NKN = 16, NVN = 32, DVN = 128, TN = 4096, YCH = NVN * DVN + 2 * NKN * DKN; +struct Args { + std::vector y, S, beta, g, o; + float *dy, *dS, *dbeta, *dg, *dout, *dsnap; +}; +static void init(Args& a) { + size_t ny = (size_t)TN * YCH; + a.y.assign(ny, 0.f); a.S.assign((size_t)NVN * DVN * DKN, 0.f); + a.beta.assign(TN * NVN, 0.f); a.g.assign(TN * NVN, 0.f); a.o.assign((size_t)TN * NVN * DVN, 0.f); + srand(1234); + auto rnd = [] { return (float)rand() / 2147483647.f - 0.5f; }; + for (auto& v : a.y) v = rnd(); + for (auto& v : a.S) v = rnd() * 0.1f; + for (auto& v : a.beta) v = rnd(); + for (auto& v : a.g) v = -0.01f - fabsf(rnd()) * 0.02f; // decay < 1: a real gated delta rule + hipMalloc(&a.dy, ny * 4); hipMalloc(&a.dS, a.S.size() * 4); hipMalloc(&a.dbeta, a.beta.size() * 4); + hipMalloc(&a.dg, a.g.size() * 4); hipMalloc(&a.dout, a.o.size() * 4); hipMalloc(&a.dsnap, 4); + hipMemcpy(a.dy, a.y.data(), ny * 4, hipMemcpyHostToDevice); + hipMemcpy(a.dbeta, a.beta.data(), a.beta.size() * 4, hipMemcpyHostToDevice); + hipMemcpy(a.dg, a.g.data(), a.g.size() * 4, hipMemcpyHostToDevice); +} +struct Res { float ms; std::vector out; }; +template static Res run(K k, Args& a, int dnp, int ych = YCH) { + int rows = 32 * dnp / DKN, gy = DVN / (8 * rows); + dim3 grid(NVN, gy), block(256); + auto launch = [&] { k<<>>(a.dy, a.dS, a.dbeta, a.dg, a.dout, NKN, NVN, 0, DKN, DVN, 1.0f / sqrtf(DKN), TN, ych, a.dsnap, 0, nullptr, nullptr); }; + hipMemcpy(a.dS, a.S.data(), a.S.size() * 4, hipMemcpyHostToDevice); + hipMemset(a.dout, 0, a.o.size() * 4); + launch(); hipDeviceSynchronize(); + hipEvent_t e0, e1; hipEventCreate(&e0); hipEventCreate(&e1); + const int reps = 10; + hipEventRecord(e0); + for (int i = 0; i < reps; i++) launch(); + hipEventRecord(e1); hipEventSynchronize(e1); + float ms = 0; hipEventElapsedTime(&ms, e0, e1); + hipMemcpy(a.o.data(), a.dout, a.o.size() * 4, hipMemcpyDeviceToHost); + return {ms / reps, a.o}; +} +int main() { + Args a; init(a); + Res ref = run(dn_base, a, 16); + printf("%-10s %8.3f ms %5.2fx max |reldiff| vs base\n", "base", ref.ms, 1.0); + struct V { const char* name; void (*k)(const float*, float*, const float*, const float*, float*, int, int, int, int, int, float, int, int, float*, int, const float*, const float*); int dnp; }; + V vs[] = {{"dn16", dn16, 16}, {"dn16s", dn16s, 16}, {"dn32", dn32, 32}, {"dn32s", dn32s, 32}, + {"no expf(g)", dn16x, 16}, {"no reductions", dn16r, 16}}; + for (auto& v : vs) { + Res r = run(v.k, a, v.dnp); + double worst = 0; + for (size_t i = 0; i < ref.out.size(); i++) { + double d = ref.out[i] != 0 ? fabs((ref.out[i] - r.out[i]) / ref.out[i]) : fabs(ref.out[i] - r.out[i]); + if (d > worst) worst = d; + } + printf("%-13s %8.3f ms %5.2fx %.2e\n", v.name, r.ms, ref.ms / r.ms, worst); + } + // The same scan with every token reading token 0's q/k/v (ych = 0): the per-token reads then stay in L1, which + // separates "cost of the data" from "cost of the strided, 128-blocks-redundant reads". + Res l1 = run(dn16, a, 16, 0); + printf("%-10s %8.3f ms %5.2fx (same token's q/k/v every step)\n", "dn16-l1", l1.ms, ref.ms / l1.ms); + return 0; +} From 3bf807991d30aa0eba0eba1012fdf6250c4e2903 Mon Sep 17 00:00:00 2001 From: Hannes Klas Date: Tue, 17 Nov 2026 07:12:56 +0100 Subject: [PATCH 015/515] docs: the two matrix-core ports, against what Strata already had Cross-checked this backend's work against the reference engine (same card, same models, MIT) and recorded the comparison rather than leaving it implicit: - Strata's prompt attention has had the same two instructions (gfx11 `v_wmma_f32_16x16x16_f16_w32`, gfx12 the `_gfx12` form) since its 0.1.32, with the fragment layout this backend probed: `A` lane l holds `A[l % 16][(l / 16) * 8 + i]` on gfx12, `D[2i + l / 16][l % 16]` on gfx11. It is default on gfx12 Linux, tied to an int8 KV cache (q and p as FP16 hi+lo parts), and worth 7.2-7.5x their portable kernel / +31% prompt throughput at 8.8K tokens. Ours works on an f16 KV cache and stays inside the CUDA-era m16n8k16 code by staging the scores; the two land in the same place, ~2x the attention and +22-35% prefill at depth. - They did write the chunked gated delta-rule scan this backend measured and declined (`gdn_chunk.cu` FP32, `gdn_tc.cuh` gfx11, `gdn_wmma12.inc` gfx12), and their own numbers are the argument: recurrence 1.6x, whole prompt +1.4-2.1% on an RDNA3 iGPU, 0.73-0.87x (slower) on CUDA, off by default because the rounding differs. - The int8-WMMA verdict needed a scope: it holds for GGUF K-quants dequantized on the fly. Strata gets +19.1% at 4K (8-8.5% at 16K/32K) from int8 matrix cores on gfx12 for prompt experts, because it repacks the weights into a format laid out for the fragment (A = 16 weight rows, so a lane's eight results share one token's activation scale). That is the class of evidence that would reopen GEMM_TC here, and it costs a repack pass. --- docs/HIP.md | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/docs/HIP.md b/docs/HIP.md index 10d41d74..7d555519 100644 --- a/docs/HIP.md +++ b/docs/HIP.md @@ -148,6 +148,13 @@ the time of f16, with a vector-friendly rescale 6.6x *slower*, with the layout t integer path cannot pay for itself here, so `GEMM_TC` stays 0 on HIP and the prefill GEMM dequantizes to f16 in shared memory and runs on the f16 matrix cores, which is what puts it ahead of the Vulkan backend. +That verdict is about GGUF K-quants dequantized on the fly, and there is a known way out of it: **repack the weights**. +Strata runs int8 matrix cores for prompt experts on gfx12 (its `STRATA_PF_FUSED`, on by default for its own IQ3_S, +IQ3_XXS and Q2_0 packs) and measures a 4K prompt 1,612 -> 1,353 ms (+19.1%, 8-8.5% at 16K/32K), because a pack can be +laid out for the fragment (A = 16 weight rows, so a lane's eight results share one token's activation scale) instead +of the per-16-weight K-quant rescale that kills it here. Doing that in this engine would mean a repack pass and our own +pack format — a project, not a kernel — but it is the shape of the evidence that would reopen `GEMM_TC`. + ## What is left, measured Profiled on the same 35B prefill (`rocprofv3 --kernel-trace`, pp 4096): 54% of the kernel time is the quantized @@ -168,7 +175,11 @@ of its time waiting on the CPU expert worker, which is an expert-tier question, away with the chunked WY/UT-transform form (a small triangular inverse plus a few matmuls over a chunk), which wants f32 for the state and therefore does not get tensor cores. -Since the whole kernel is 12% of prefill, that rewrite's ceiling is ~4% of prefill. Left alone deliberately. +Since the whole kernel is 12% of prefill, that rewrite's ceiling is ~4% of prefill. Left alone deliberately — and +Strata, which did write it (chunked scans on the gfx11 matrix cores in `gdn_tc.cuh` and the gfx12 ones in +`gdn_wmma12.inc`, both MIT), measures exactly that: their recurrence is 1.6x faster on an RDNA3 iGPU for a **1.4-2.1%** +gain in whole-prompt time (docs/DETAILS.md), it is off by default because the rounding differs from the token-by-token +FP32 scan, and on CUDA it is 0.73-0.87x, i.e. slower. ## Next @@ -182,3 +193,15 @@ Since the whole kernel is 12% of prefill, that rewrite's ceiling is ~4% of prefi The compatibility shim follows the structure and several implementations of Strata's `include/strata/hip_compat/intrinsics.hpp` (MIT, (c) 2025 Niko1221, https://github.com/Niko1221/Strata), which runs CUDA-shaped kernels on the same wave32 targets. See `THANKS.md`. + +The two matrix-core ports in this backend were written independently and turned out to match work already in Strata, in +a different design: + +- **Prompt attention on the matrix cores**: their `src/kernels/cuda/qsa_prompt_attn.cu` has the same instruction for + gfx11 and gfx12 with the fragment layout noted here (`A` lane l holds `A[l % 16][(l / 16) * 8 + i]`, gfx11 + `D[2i + l / 16][l % 16]`), default on gfx12 Linux but tied to an int8 KV cache and to keeping q and p as FP16 + hi+lo parts; it is 7.2-7.5x their portable kernel and +31% prompt throughput at 8.8K tokens. This backend's version + works on an f16 KV cache and reuses the CUDA-era m16n8k16 softmax by staging the scores, at ~2x the prefill + attention and +22-35% prefill at depth. +- **A chunked gated delta-rule scan** (`gdn_chunk.cu`, `gdn_tc.cuh`, `gdn_wmma12.inc`): the rewrite this backend + measured and declined, with their own numbers agreeing with the estimate (see "What is left, measured"). From 9a504a64f4732bdb297f4d9b641675b0ef721ae5 Mon Sep 17 00:00:00 2001 From: Hannes Klas Date: Tue, 24 Nov 2026 06:53:23 +0100 Subject: [PATCH 016/515] hip: follow main's kernel arguments (weight scale, rope pairs, tq_lut, KV_MODE) Adds rope_pairs and dflash2_conv; --kv q4/q2 is refused on HIP instead of running f16. --- src/hip/mod.rs | 43 ++++++++++++++++++++++++++++--------------- 1 file changed, 28 insertions(+), 15 deletions(-) diff --git a/src/hip/mod.rs b/src/hip/mod.rs index 84d0726e..900d11ad 100644 --- a/src/hip/mod.rs +++ b/src/hip/mod.rs @@ -114,7 +114,8 @@ fn source(kv_q8: bool) -> String { __device__ const unsigned int iq3s_grid[512] = {{{}}};\n\ __device__ const unsigned char ksigns_iq2xs[128] = {{{}}};\n\ __device__ const signed char kvalues_iq4nl[16] = {{{}}};\n\ - #define LLAMA_Q8 {}\n#define KV_Q8 {}\n#define GEMM_TC 0\n#define GEMM_WMMA (STRATA_WMMA && {})\n\ + __device__ const float tq_lut[4096] = {{{}}};\n\ + #define LLAMA_Q8 {}\n#define KV_MODE {}\n#define GEMM_TC 0\n#define GEMM_WMMA (STRATA_WMMA && {})\n\ #define GEMM_BM {}\n#define GEMM_BK {}\n#define GEMM_MIN_BLOCKS 1\n#define GEMV_LOADW {}\n\ #define FA_BQ {}\n#define FA_BK {}\n{}", include_str!("compat.h"), @@ -126,6 +127,7 @@ fn source(kv_q8: bool) -> String { join(IQ3S_GRID.iter().map(|v| format!("{v:#x}ULL")).collect()), join(KSIGNS_IQ2XS.iter().map(|v| v.to_string()).collect()), join(KVALUES_IQ4NL.iter().map(|v| v.to_string()).collect()), + join(crate::quant::TQ_LUT.iter().flatten().map(|v| format!("{v:e}f")).collect()), crate::cuda::llama_numerics() as u8, kv_q8 as u8, // `STRATA_HIP_WMMA=0` falls back to the CUDA-core multiplications (A/B comparison, and a workaround if a @@ -169,6 +171,8 @@ impl Gpu { max_smem = hip.attribute(ffi::ATTR_SHARED_PER_BLOCK, device as i32).unwrap_or(16 << 10) as usize; } anyhow::ensure!(max_smem >= (16 << 10), "HIP device reports {max_smem} B of shared memory a block"); + // The HIP kernels hold an f16 or q8 cache (KV_MODE 0 or 1): refuse q4 and q2 rather than run f16 unasked. + anyhow::ensure!(crate::cuda::kv_mode() <= 1, "--kv q4 and q2 are not available on the HIP backend (f16 or q8)"); let kv_q8 = crate::cuda::kv_q8(); let rtc = ffi::Rtc::get().context("HIP init").context("hiprtc is required to compile the kernels")?; let (maj, min) = rtc.version(); @@ -313,7 +317,7 @@ impl Gpu { /// `gemvq`; with z = 2 also the matrix of `pair.2` rows at byte offset `pair.0` into the output at byte offset /// `pair.1` (token stride `pair.2`). fn gemvq_pair(&self, w: &GpuTensor, x: u64, x_stride: usize, xq: u64, y: u64, y_stride: usize, nt: usize, - pair: (i64, i64, i32), z: u32) -> anyhow::Result<()> { + pair: (i64, i64, i32, f32), z: u32) -> anyhow::Result<()> { if !(1..=4).contains(&nt) { bail!("gemvn: {nt} inputs (1 to 4)"); } let (ncols, k1) = Self::gemv_cols("gemv", w.ty, w.cols)?; let (mut c, rpw) = Self::gemv_cfg(w.ty, w.rows, w.cols, 1); @@ -325,23 +329,23 @@ impl Gpu { c.shared_mem_bytes = per; for t in 0..nt { let (xt, yt) = (x + 4 * t as u64 * x_stride as u64, y + 4 * t as u64 * y_stride as u64); - launch!(self, &k1, c, w.ptr, xt, yt, w.rows as i32, ncols, rpw, xq, pair.0, pair.1, pair.2); + launch!(self, &k1, c, w.ptr, xt, yt, w.rows as i32, ncols, rpw, xq, pair.0, pair.1, pair.2, w.scale, pair.3); } return Ok(()); } if nt == 1 { - launch!(self, &k1, c, w.ptr, x, y, w.rows as i32, ncols, rpw, xq, pair.0, pair.1, pair.2); + launch!(self, &k1, c, w.ptr, x, y, w.rows as i32, ncols, rpw, xq, pair.0, pair.1, pair.2, w.scale, pair.3); return Ok(()); } let kn = k1.replacen("gemv", "gemvn", 1); - launch!(self, &kn, c, w.ptr, x, x_stride as i32, y, y_stride as i32, w.rows as i32, ncols, rpw, nt as i32, xq, pair.0, pair.1, pair.2); + launch!(self, &kn, c, w.ptr, x, x_stride as i32, y, y_stride as i32, w.rows as i32, ncols, rpw, nt as i32, xq, pair.0, pair.1, pair.2, w.scale, pair.3); Ok(()) } /// Prefill GEMM over a tile list (or one dense matrix when `tiles` is 0). Without int8 tensor cores the f16 /// `gemm_*`/`gemms_*` kernels run; `gemm_tc` is compiled out of this build (`GEMM_TC 0`). fn gemm_raw(&self, ty: GgmlType, rows: usize, cols: usize, tiles: u64, n_tiles: usize, wd: u64, nd: usize, - x: u64, x_stride: usize, _n_x: usize, xrow: u64, y: u64, y_stride: usize, act: i32) -> anyhow::Result<()> { + x: u64, x_stride: usize, _n_x: usize, xrow: u64, y: u64, y_stride: usize, act: i32, w_scale: f32) -> anyhow::Result<()> { if cols % 64 != 0 { bail!("{} matrix with {cols} columns: GEMM needs a multiple of 64", ty.name()); } if n_tiles == 0 { return Ok(()) } let (same, act) = (act & SAME_X != 0, act & !SAME_X); @@ -350,11 +354,11 @@ impl Gpu { let sm = tiles == 0 && (grid.0 * grid.1 < 112 || nd <= 32); let grid = if sm { (grid.0, nd.div_ceil(32) as u32) } else { grid }; launch!(self, &kname(if sm { "gemms" } else { "gemm" }, ty), cfg(grid, 2 * GEMM_BM as u32, 0), - tiles, wd, nd as i32, x, x_stride as i32, xrow, y, y_stride as i32, rows as i32, (cols / 64) as i32, act); + tiles, wd, nd as i32, x, x_stride as i32, xrow, y, y_stride as i32, rows as i32, (cols / 64) as i32, act, w_scale); // Tile lists: gemm_* skips the tiles of at most 32 positions, which gemms_* takes. if tiles != 0 { launch!(self, &kname("gemms", ty), cfg(grid, 2 * GEMM_BM as u32, 0), - tiles, wd, nd as i32, x, x_stride as i32, xrow, y, y_stride as i32, rows as i32, (cols / 64) as i32, act); + tiles, wd, nd as i32, x, x_stride as i32, xrow, y, y_stride as i32, rows as i32, (cols / 64) as i32, act, w_scale); } Ok(()) } @@ -582,11 +586,11 @@ impl Backend for Gpu { fn gemm(&self, ty: GgmlType, rows: usize, cols: usize, tiles: u64, n_tiles: usize, x: u64, x_stride: usize, n_x: usize, xrow: u64, y: u64, y_stride: usize, act: i32) -> anyhow::Result<()> { - self.gemm_raw(ty, rows, cols, tiles, n_tiles, 0, 0, x, x_stride, n_x, xrow, y, y_stride, act) + self.gemm_raw(ty, rows, cols, tiles, n_tiles, 0, 0, x, x_stride, n_x, xrow, y, y_stride, act, 1.0f32) } fn gemm_dense(&self, w: &GpuTensor, n: usize, x: u64, x_stride: usize, y: u64, y_stride: usize, act: i32) -> anyhow::Result<()> { - self.gemm_raw(w.ty, w.rows, w.cols, 0, n.div_ceil(GEMM_BM), w.ptr, n, x, x_stride, n, 0, y, y_stride, act) + self.gemm_raw(w.ty, w.rows, w.cols, 0, n.div_ceil(GEMM_BM), w.ptr, n, x, x_stride, n, 0, y, y_stride, act, w.scale) } fn int8_gemm(&self, _ty: GgmlType) -> bool { false } @@ -594,7 +598,7 @@ impl Backend for Gpu { fn gemv(&self, w: &GpuTensor, x: u64, y: u64) -> anyhow::Result<()> { let (ncols, kn) = Self::gemv_cols("gemv", w.ty, w.cols)?; let (c, rpw) = Self::gemv_cfg(w.ty, w.rows, w.cols, 1); - launch!(self, &kn, c, w.ptr, x, y, w.rows as i32, ncols, rpw, 0u64, 0i64, 0i64, 0i32); + launch!(self, &kn, c, w.ptr, x, y, w.rows as i32, ncols, rpw, 0u64, 0i64, 0i64, 0i32, w.scale, 1.0f32); Ok(()) } @@ -603,7 +607,7 @@ impl Backend for Gpu { } fn gemvq(&self, w: &GpuTensor, x: u64, x_stride: usize, xq: u64, y: u64, y_stride: usize, nt: usize) -> anyhow::Result<()> { - self.gemvq_pair(w, x, x_stride, xq, y, y_stride, nt, (0, 0, 0), 1) + self.gemvq_pair(w, x, x_stride, xq, y, y_stride, nt, (0, 0, 0, 1.0f32), 1) } fn gemvq2(&self, a: &GpuTensor, b: &GpuTensor, x: u64, x_stride: usize, xq: u64, ya: u64, yb: u64, nt: usize) -> anyhow::Result<()> { @@ -612,7 +616,7 @@ impl Backend for Gpu { return self.gemvq(b, x, x_stride, xq, yb, b.rows, nt); } let ((a, ya), (b, yb)) = if a.rows >= b.rows { ((a, ya), (b, yb)) } else { ((b, yb), (a, ya)) }; - self.gemvq_pair(a, x, x_stride, xq, ya, a.rows, nt, (b.ptr as i64 - a.ptr as i64, yb as i64 - ya as i64, b.rows as i32), 2) + self.gemvq_pair(a, x, x_stride, xq, ya, a.rows, nt, (b.ptr as i64 - a.ptr as i64, yb as i64 - ya as i64, b.rows as i32, b.scale), 2) } fn moe_gemv(&self, ty: GgmlType, rows: usize, cols: usize, w: u64, stride: usize, ids: u64, k: usize, x: u64, x_stride: usize, @@ -631,7 +635,7 @@ impl Backend for Gpu { } fn dequant(&self, w: &GpuTensor, rows: usize, out: u64) -> anyhow::Result<()> { - launch!(self, &kname("dequant", w.ty), cfg((rows as u32, 1), 256, 0), w.ptr, out, Self::gemv_cols("dequant", w.ty, w.cols)?.0); + launch!(self, &kname("dequant", w.ty), cfg((rows as u32, 1), 256, 0), w.ptr, out, Self::gemv_cols("dequant", w.ty, w.cols)?.0, w.scale); Ok(()) } @@ -668,7 +672,11 @@ impl Backend for Gpu { } fn rope_neox(&self, x: u64, stride: usize, heads: usize, per: usize, n_rot: usize, step: u64, base: f32) -> anyhow::Result<()> { - launch!(self, "rope_neox", cfg(((heads / per) as u32, 1), (n_rot / 2) as u32, 0), x, stride as i32, per as i32, n_rot as i32, step, base); + self.rope_pairs(x, stride, heads, per, n_rot, step, base, 0, n_rot / 2) + } + + fn rope_pairs(&self, x: u64, stride: usize, heads: usize, per: usize, n_rot: usize, step: u64, base: f32, lo: usize, hi: usize) -> anyhow::Result<()> { + launch!(self, "rope_neox", cfg(((heads / per) as u32, 1), (n_rot / 2) as u32, 0), x, stride as i32, per as i32, n_rot as i32, step, base, lo as i32, hi as i32); Ok(()) } @@ -751,6 +759,11 @@ impl Backend for Gpu { Ok(()) } + fn dflash2_conv(&self, x: u64, dyn_w: u64, base: u64, out: u64, h: usize, gs: usize, k: usize, t: usize, part: usize) -> anyhow::Result<()> { + launch!(self, "dflash2_conv", cfg((h.div_ceil(256) as u32, t as u32), 256, 0), x, dyn_w, base, out, h as i32, gs as i32, k as i32, t as i32, part as i32); + Ok(()) + } + fn attn_prefill_m(&self, q: u64, kc: u64, vc: u64, qg: u64, out: u64, step: u64, t: usize, nh: usize, nkv: usize, hd: usize, scale: f32, qm: u64, mw: usize, sink: u64, win: usize) -> anyhow::Result<()> { if !matches!(hd, 64 | 128 | 256) { bail!("attention prefill: head_dim {hd} unsupported (64, 128 or 256)"); } From 98b1898b5a9497148e75157a8dcf733d0706a795 Mon Sep 17 00:00:00 2001 From: Hannes Klas Date: Tue, 24 Nov 2026 07:28:32 +0100 Subject: [PATCH 017/515] hip: the kv_q8 comment names KV_MODE --- src/hip/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/hip/mod.rs b/src/hip/mod.rs index 900d11ad..beab48e0 100644 --- a/src/hip/mod.rs +++ b/src/hip/mod.rs @@ -39,7 +39,7 @@ pub struct Gpu { fns: HashMap, /// "gfx1201": the target hiprtc compiled for. arch: String, - /// `--kv q8` (the kernels were compiled with KV_Q8). + /// `--kv q8` (the kernels were compiled with `KV_MODE` 0 or 1; HIP has no q4/q2 cache rows). pub kv_q8: bool, /// Opt-in shared memory per block on this device (64 KiB on RDNA). max_smem: usize, From 272bb2c1631bd4882c93652402f60c32c967d993 Mon Sep 17 00:00:00 2001 From: Hannes Klas Date: Tue, 24 Nov 2026 07:40:56 +0100 Subject: [PATCH 018/515] hip: say which libhiprtc paths were tried and why each failed Rtc::get returns the reasons like Hip::open does; it returned None with no reason. --- src/hip/ffi.rs | 19 ++++++++++++------- src/hip/mod.rs | 4 ++-- 2 files changed, 14 insertions(+), 9 deletions(-) diff --git a/src/hip/ffi.rs b/src/hip/ffi.rs index a8a7590e..5d4a2d1d 100644 --- a/src/hip/ffi.rs +++ b/src/hip/ffi.rs @@ -231,19 +231,24 @@ pub struct Rtc { _lib: Library, } -static RTC: OnceLock> = OnceLock::new(); +static RTC: OnceLock> = OnceLock::new(); impl Rtc { - pub fn get() -> Option<&'static Rtc> { RTC.get_or_init(Self::open).as_ref() } + /// The library, or which paths were tried and why each failed. + pub fn get() -> Result<&'static Rtc, &'static str> { RTC.get_or_init(Self::open).as_ref().map_err(|e| e.as_str()) } - fn open() -> Option { + fn open() -> Result { let want = candidates(std::env::var_os("STRATA_HIPRTC").map(Into::into), &["libhiprtc.so", "libhiprtc.so.7", "libhiprtc.so.6"]); + let mut tried = Vec::new(); for path in &want { - let Ok(lib) = (unsafe { Library::new(path) }) else { continue }; + let lib = match unsafe { Library::new(path) } { + Ok(l) => l, + Err(e) => { tried.push(format!("{}: not loadable ({e})", path.display())); continue } + }; unsafe { - macro_rules! g { ($n:literal) => { match Self::sym(&lib, $n) { Some(f) => f, None => continue } } } - return Some(Rtc { + macro_rules! g { ($n:literal) => { match Self::sym(&lib, $n) { Some(f) => f, None => { tried.push(format!("{}: no {}", path.display(), $n)); continue } } } } + return Ok(Rtc { version: g!("hiprtcVersion"), create: g!("hiprtcCreateProgram"), compile: g!("hiprtcCompileProgram"), @@ -258,7 +263,7 @@ impl Rtc { }); } } - None + Err(format!("no hiprtc: {}", tried.join(", "))) } unsafe fn sym(lib: &Library, name: &str) -> Option { diff --git a/src/hip/mod.rs b/src/hip/mod.rs index beab48e0..3e575c35 100644 --- a/src/hip/mod.rs +++ b/src/hip/mod.rs @@ -174,7 +174,7 @@ impl Gpu { // The HIP kernels hold an f16 or q8 cache (KV_MODE 0 or 1): refuse q4 and q2 rather than run f16 unasked. anyhow::ensure!(crate::cuda::kv_mode() <= 1, "--kv q4 and q2 are not available on the HIP backend (f16 or q8)"); let kv_q8 = crate::cuda::kv_q8(); - let rtc = ffi::Rtc::get().context("HIP init").context("hiprtc is required to compile the kernels")?; + let rtc = ffi::Rtc::get().map_err(|e| anyhow::anyhow!("{e}")).context("HIP init").context("hiprtc is required to compile the kernels")?; let (maj, min) = rtc.version(); let tag = format!("{maj}.{min}"); eprintln!("hip: {} ({arch}, wave{warp}, {} B shared memory a block)", @@ -1062,7 +1062,7 @@ mod tests { /// The generated source compiles for this device through hiprtc (the CUDA source with `STRATA_HIP` taken). #[test] fn hiprtc_compiles_the_kernels() { - let Some(rtc) = ffi::Rtc::get() else { + let Ok(rtc) = ffi::Rtc::get() else { eprintln!("skipping: no hiprtc"); return; }; From 1fcca1c06b722e2d19aca7d72ad6a697df102ab8 Mon Sep 17 00:00:00 2001 From: Hannes Klas Date: Tue, 24 Nov 2026 07:41:13 +0100 Subject: [PATCH 019/515] hip: gfx11 WMMA results go to the rows RDNA3 puts them in RDNA3 interleaves the D rows (2i + lane/16), RDNA4 keeps them in blocks (8*(lane/16) + i); the epilogues assumed the gfx12 layout. gfx11 numerics are not checked on a card; a test compiles the gfx11 branch. --- src/cuda/kernels.cu | 12 ++++++------ src/hip/compat.h | 9 ++++++--- src/hip/mod.rs | 11 +++++++++++ 3 files changed, 23 insertions(+), 9 deletions(-) diff --git a/src/cuda/kernels.cu b/src/cuda/kernels.cu index 0c45be62..578325da 100644 --- a/src/cuda/kernels.cu +++ b/src/cuda/kernels.cu @@ -1265,9 +1265,9 @@ __device__ __forceinline__ void gemm_q(const GemmTile* tiles, const u8* wd, int if (kb + 1 < nk) stw(); } #if GEMM_WMMA - // D layout of the AMD WMMA: lane 16*(lane>>4) keeps column lane & 15 and rows 8*(lane>>4) .. +7 of each tile. + // D layout of the AMD WMMA: the lane keeps column lane & 15 and rows STRATA_WMMA_ROW(lane, 0..7) of each tile. { - const int l16 = lane & 15, wl = lane >> 4; + const int l16 = lane & 15; constexpr int MT = SM ? 1 : 2, NTW = SM ? 1 : 2; #pragma unroll for (int mt = 0; mt < MT; mt++) @@ -1277,7 +1277,7 @@ __device__ __forceinline__ void gemm_q(const GemmTile* tiles, const u8* wd, int if (n >= rows) continue; #pragma unroll for (int i = 0; i < 8; i++) { - int r = wm + mt * 16 + 8 * wl + i; + int r = wm + mt * 16 + STRATA_WMMA_ROW(lane, i); if (r >= tl.cnt) continue; float* yr = y + (size_t)(tl.m0 + r) * y_stride; float v = accw[mt * NTW + nt][i]; @@ -3323,7 +3323,7 @@ __device__ __forceinline__ void attn_prefill_t(const float* q, const u16* kc, co for (int kk = 0; kk < HD; kk += 16) acc = strata_hip::strata_wmma(strata_hip::strata_ld_wmma(qrow + kk), strata_hip::strata_ld_wmma(krow + kk), acc); #pragma unroll - for (int i = 0; i < 8; i++) sw[(8 * (lane >> 4) + i) * PW + kg * 16 + l16] = acc[i]; + for (int i = 0; i < 8; i++) sw[STRATA_WMMA_ROW(lane, i) * PW + kg * 16 + l16] = acc[i]; } __syncwarp(); #pragma unroll @@ -3464,7 +3464,7 @@ __device__ __forceinline__ void attn_prefill_t(const float* q, const u16* kc, co #if GEMM_WMMA // P * V on the matrix cores, the way the scores are: A = P (this warp's 16 query rows x the tile's keys, in // halves), B = V^T (16 head dimensions x the same keys, one half a tile row apart). The lane's 8 results land - // in AMD's layout again (query rows 8*(lane>>4) + i, dim column lane & 15), so each 16 x 16 result tile is + // in AMD's layout again (query rows STRATA_WMMA_ROW(lane, i), dim column lane & 15), so each 16 x 16 result tile is // staged in f32 and read back as the two m16n8k16 dim tiles the rescale above, the epilogue below and the // score stage all use (`st` is free again by now: it held the scores of this tile). if (!skip) { @@ -3489,7 +3489,7 @@ __device__ __forceinline__ void attn_prefill_t(const float* q, const u16* kc, co acc = strata_hip::strata_wmma(strata_hip::strata_ld_wmma(pa), strata_hip::strata_ld_wmma_t(pb, PQ), acc); } #pragma unroll - for (int i = 0; i < 8; i++) sw[(8 * (lane >> 4) + i) * 16 + l16] = acc[i]; + for (int i = 0; i < 8; i++) sw[STRATA_WMMA_ROW(lane, i) * 16 + l16] = acc[i]; __syncwarp(); #pragma unroll for (int r = 0; r < 2; r++) diff --git a/src/hip/compat.h b/src/hip/compat.h index 6202692a..85381e8c 100644 --- a/src/hip/compat.h +++ b/src/hip/compat.h @@ -88,16 +88,19 @@ __device__ __forceinline__ int any_sync(unsigned, int predicate) { return (int)( // ---- matrix cores (gfx11/gfx12 WMMA) ---- // D[16x16] += A[16x16] * B^T[16x16]: both operands are 16 rows of 16 halves, which is exactly how the prefill GEMM // stages X (positions) and W (output rows) in shared memory, so no transpose is needed. Each lane supplies the -// k-values of its own row of both operands and holds 8 results: rows 8*(lane>>4) + i, column lane & 15. -// gfx12 splits the k dimension across the two half-waves (each lane gives 8 halves, lanes 16-31 the upper half); -// gfx11 takes all 16 from one lane. +// k-values of its own row of both operands and holds 8 results of column lane & 15, in rows STRATA_WMMA_ROW(lane, i). +// gfx12 splits the k dimension across the two half-waves (each lane gives 8 halves, lanes 16-31 the upper half) and +// gives lanes 16-31 rows 8..15; gfx11 takes all 16 halves from every lane (lanes 16-31 repeat lanes 0-15) and +// interleaves the rows, even ones in lanes 0-15 and odd ones in lanes 16-31 (as llama.cpp's mma.cuh has it for RDNA3). #if defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1103__) || defined(__gfx1150__) || \ defined(__gfx1151__) || defined(__gfx1152__) #define STRATA_WMMA 1 #define STRATA_WMMA_K 16 +#define STRATA_WMMA_ROW(lane, i) (2 * (i) + ((lane) >> 4)) #elif defined(__gfx1200__) || defined(__gfx1201__) #define STRATA_WMMA 1 #define STRATA_WMMA_K 8 +#define STRATA_WMMA_ROW(lane, i) (8 * ((lane) >> 4) + (i)) #else #define STRATA_WMMA 0 #define STRATA_WMMA_K 0 diff --git a/src/hip/mod.rs b/src/hip/mod.rs index 3e575c35..31c3edef 100644 --- a/src/hip/mod.rs +++ b/src/hip/mod.rs @@ -1073,4 +1073,15 @@ mod tests { let arch = hip.arch(0).unwrap(); rtc.compile(&source(false), "kernels.cu", &arch, &[]).expect("hiprtc compiles kernels.cu for the device"); } + + /// The gfx11 (RDNA3) WMMA branch compiles, whatever card is present: its intrinsics, operand width and + /// `STRATA_WMMA_ROW` layout differ from gfx12's. Numerics on gfx11 need an RDNA3 card to check. + #[test] + fn hiprtc_compiles_the_kernels_for_gfx11() { + let Ok(rtc) = ffi::Rtc::get() else { + eprintln!("skipping: no hiprtc"); + return; + }; + rtc.compile(&source(false), "kernels.cu", "gfx1100", &[]).expect("hiprtc compiles kernels.cu for gfx1100"); + } } From 10a5fcbf32f5b3f156f2838c2162607e19380f2f Mon Sep 17 00:00:00 2001 From: Hannes Klas Date: Tue, 24 Nov 2026 07:41:15 +0100 Subject: [PATCH 020/515] hip: read the device properties into a buffer with room to spare, and scan it in bounds The 1472-byte buffer was ROCm 7's struct size, and the gfx scan could slice past its end. --- src/hip/ffi.rs | 53 +++++++++++++++++++++++++++++++++++++------------- 1 file changed, 39 insertions(+), 14 deletions(-) diff --git a/src/hip/ffi.rs b/src/hip/ffi.rs index 5d4a2d1d..076fc186 100644 --- a/src/hip/ffi.rs +++ b/src/hip/ffi.rs @@ -35,10 +35,23 @@ pub const ATTR_INTEGRATED: c_int = 16; pub const ATTR_MULTIPROCESSOR_COUNT: c_int = 63; pub const ATTR_MAX_THREADS_PER_BLOCK: c_int = 56; -/// `hipDeviceProp_t` from ROCm 7: the field offsets the backend reads. The struct is version-specific, so every -/// read is validated (the architecture name must look like `gfxNNNN`) and `STRATA_HIP_ARCH` overrides it. -const PROP_SIZE: usize = 1472; -const PROP_GCN_ARCH_NAME: usize = 1160; +/// Room for `hipDeviceProp_t`, which `hipGetDeviceProperties` writes whole. ROCm 7's `hipDeviceProp_tR0600` is 1472 +/// bytes; the size is not exported and changes between versions, so the buffer leaves ample room for a larger one. +/// The architecture name is found by shape (`find_gfx`), and `STRATA_HIP_ARCH` overrides it. +const PROP_BUF: usize = 16 << 10; + +/// The first `gfxNNNN`-looking string at a 4-byte offset in `bytes` (at least 6 characters, at most 16), read only +/// within `bytes`. +fn find_gfx(bytes: &[u8]) -> Option { + for i in (0..bytes.len()).step_by(4) { + let w = &bytes[i..(i + 16).min(bytes.len())]; + if !w.starts_with(b"gfx") { continue } + let end = w.iter().position(|&b| b == 0 || !b.is_ascii_alphanumeric()).unwrap_or(w.len()); + if end < 6 { continue } + return String::from_utf8(w[..end].to_vec()).ok(); + } + None +} type Fn = unsafe extern "C" fn(); @@ -189,18 +202,10 @@ impl Hip { fn prop_arch(&self, device: c_int) -> Option { // Resolved here and not in `bind`: this is the only use, and a missing symbol must not fail the backend. let f: unsafe extern "C" fn(*mut c_void, c_int) -> c_int = unsafe { Self::sym(&self._lib, "hipGetDeviceProperties") }?; - let mut buf = vec![0u64; PROP_SIZE / 8]; + let mut buf = vec![0u64; PROP_BUF / 8]; let r = unsafe { f(buf.as_mut_ptr().cast(), device) }; if r != HIP_SUCCESS { return None } - let bytes = unsafe { std::slice::from_raw_parts(buf.as_ptr().cast::(), PROP_SIZE) }; - for i in (0..bytes.len().saturating_sub(8)).step_by(4) { - if &bytes[i..i + 3] != b"gfx" { continue } - let end = bytes[i..i + 16].iter().position(|&b| b == 0 || !(b as char).is_ascii_alphanumeric()).unwrap_or(16); - if end < 6 { continue } - let s = String::from_utf8(bytes[i..i + end].to_vec()).ok()?; - return Some(s); - } - None + find_gfx(unsafe { std::slice::from_raw_parts(buf.as_ptr().cast::(), PROP_BUF) }) } pub fn device_name(&self, device: c_int) -> String { @@ -346,3 +351,23 @@ struct ProgGuard { impl Drop for ProgGuard { fn drop(&mut self) { unsafe { (self.destroy)(&mut self.prog) }; } } + +#[cfg(test)] +mod tests { + use super::find_gfx; + + /// The name is found at the end of the buffer without reading past it, a short `gfx` is passed over, and a + /// buffer without one gives None. + #[test] + fn find_gfx_reads_only_inside_the_buffer() { + let mut b = vec![0u8; 64]; + b[8..11].copy_from_slice(b"gfx"); + b[56..63].copy_from_slice(b"gfx1201"); + assert_eq!(find_gfx(&b).as_deref(), Some("gfx1201")); + assert_eq!(find_gfx(&b[..60]), None); + let mut tail = vec![0u8; 61]; + tail[52..61].copy_from_slice(b"gfx1100ab"); + assert_eq!(find_gfx(&tail).as_deref(), Some("gfx1100ab")); + assert_eq!(find_gfx(&[0u8; 32]), None); + } +} From 8ca7e9a30da25984b59597a3f1e73843548cfad9 Mon Sep 17 00:00:00 2001 From: Hannes Klas Date: Tue, 24 Nov 2026 07:41:17 +0100 Subject: [PATCH 021/515] hip: comments and HIP.md match the code (staging tile size, small-tile warps, prefill matrix cores) moe_prefetch on HIP is one #if around the body instead of a loop that breaks at once. --- docs/HIP.md | 2 +- src/cuda/kernels.cu | 15 +++++++-------- src/hip/compat.h | 5 +++-- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/docs/HIP.md b/docs/HIP.md index 7d555519..594228cc 100644 --- a/docs/HIP.md +++ b/docs/HIP.md @@ -95,7 +95,7 @@ the KV cache than a 16 GB card has left over for experts, so the run above strea Both results land in AMD's layout — 8 a lane, rows `8*(lane>>4) + i`, column `lane & 15` — rather than the m16n8k16 layout the softmax, the causal mask and the epilogue are written for, so each 16x16 result tile is staged in f32 and read back as `s[ng][2h + e] == S[warp*16 + g + 8h][ng*8 + 2t + e]` (scores) or `o[d][2r + e]` (P·V). One warp - staging tile serves both stages (`FA_BQ` x (`FA_BKL` + 8) floats, 4-6 KiB added to the block's dynamic shared + staging tile serves both stages (`FA_BQ` x (`FA_BKL` + 8) floats, 6-10 KiB added to the block's dynamic shared memory), and it is why head_dim 256 prefill takes 16 keys a step (`FA_BK_FOR`, as on Turing's 64 KB blocks): 32 keys would need 78 KiB of a block's 64. `STRATA_HIP_WMMA=0` runs the same numerics on the CUDA cores; the CPU-reference test covers both. diff --git a/src/cuda/kernels.cu b/src/cuda/kernels.cu index 578325da..43c30077 100644 --- a/src/cuda/kernels.cu +++ b/src/cuda/kernels.cu @@ -1204,7 +1204,7 @@ __device__ __forceinline__ void gemm_q(const GemmTile* tiles, const u8* wd, int #if GEMM_WMMA // AMD matrix cores: the tile in xs (positions, rows = m) and ws (rows = n) is fed straight in as A and B // of D[16x16] += A * B^T. A warp owns MT x NT 16x16 tiles: (32 positions, 32 rows) for the big kernel and - // (16 positions, 64 rows) for the small-tile one. Each lane holds 8 results of every tile. + // one (16 positions, 16 rows) for the small-tile one, whose 8 warps cover 32 positions x 64 rows. Each lane holds 8 results of every tile. const int l16 = lane & 15, w0 = STRATA_WMMA_K0(lane); constexpr int MT = SM ? 1 : 2, NTW = SM ? 1 : 2; strata_hip::strata_hk wa[MT], wb[NTW]; @@ -3111,20 +3111,19 @@ extern "C" __global__ void moe_route(const float* p, int n, int k, float extra_s // One block per expert (grid.y) and line range (grid.x). STRATA_MOE_PREFETCH=1 only; a hint, never a correctness // dependency. Volta: prefetch.global.L2 exists since sm_20. extern "C" __global__ void moe_prefetch(const int* ids, int k, const int* table, const char* base, int stride, int bytes) { +#if STRATA_HIP + // AMD has no L2 prefetch instruction to give: on HIP this hint does nothing. + (void)ids; (void)k; (void)table; (void)base; (void)stride; (void)bytes; +#else int j = blockIdx.y; if (j >= k) return; int s = table[ids[j]]; if (s < 0) return; const char* p = base + (size_t)((unsigned int)s * (unsigned int)stride); int lines = bytes >> 7; - for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < lines; i += gridDim.x * blockDim.x) { -#if STRATA_HIP - (void)p; // no L2 prefetch instruction to give: moe_prefetch is a CUDA-only hint - break; -#else + for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < lines; i += gridDim.x * blockDim.x) asm volatile("prefetch.global.L2 [%0];" ::"l"(p + ((size_t)i << 7))); #endif - } } // x += sum_j w[j] ye[j] + sigmoid(sg) sh + cpu. If a slot missed, wait for the CPU worker's done flag first. @@ -3218,7 +3217,7 @@ __device__ __forceinline__ void attn_prefill_t(const float* q, const u16* kc, co // HIP: the P staging tile in halves (the PV A fragments, as on Volta) and, after it, the f32 tile the matrix-core // scores are staged through before they are read in the m16n8k16 layout the softmax below is written for. Both // sit after `vs` so the qs/ks/vs offsets do not move; `hip::Gpu::attn_prefill_m` adds the f32 tile to the block's - // dynamic shared memory (FA_BQ * (FA_BKL + 8) floats, 4-8 KiB). + // dynamic shared memory (FA_BQ * (FA_BKL + 8) floats: 10 KiB at 32 keys, 6 KiB at 16). u16* ps = vs + FA_BKL * PQ; float* st = (float*)(ps + FA_BQ * (FA_BKL + 8)); #endif diff --git a/src/hip/compat.h b/src/hip/compat.h index 85381e8c..936e4b93 100644 --- a/src/hip/compat.h +++ b/src/hip/compat.h @@ -16,8 +16,9 @@ // kernels.cu selects its code paths by the CUDA architecture level: ldmatrix from sm_75, cp.async/m16n8k16/int8-mma // from sm_80, m8n8k4 (mma884) from sm_70. AMD has none of those instructions, so the build takes the portable // pre-Volta level: per-lane shared loads instead of ldmatrix, plain typed copies instead of cp.async, and the -// CUDA-core (f16 FMA) multiplicands instead of mma.sync. Prefill therefore runs without matrix cores until the -// gfx12 WMMA path lands; decode is unaffected (it has no tensor-core path). +// CUDA-core (f16 FMA) multiplicands instead of mma.sync. On gfx11 and gfx12 the prefill GEMM and attention use the +// WMMA matrix cores instead (GEMM_WMMA, below); other targets and STRATA_HIP_WMMA=0 keep the f16 FMA path. Decode is +// unaffected (it has no tensor-core path). #ifndef __CUDA_ARCH__ #define __CUDA_ARCH__ 700 #endif From 22467e5a95de858612aa27ca2e897e7dab60b8bf Mon Sep 17 00:00:00 2001 From: Volt Date: Tue, 24 Nov 2026 07:50:05 +0100 Subject: [PATCH 022/515] inkling2: harden GPU markov_w2 bounds/fallback and deduplicate step loop --- src/inkling2/dspark.rs | 119 +++++++++++++-------------------- src/inkling2/forward.rs | 29 ++++---- src/inkling2/forward/device.rs | 11 +-- 3 files changed, 70 insertions(+), 89 deletions(-) diff --git a/src/inkling2/dspark.rs b/src/inkling2/dspark.rs index 5a336083..3a368129 100644 --- a/src/inkling2/dspark.rs +++ b/src/inkling2/dspark.rs @@ -433,31 +433,37 @@ impl DsparkDrafter { let mut prev = anchor_tok; let mut drafts = Vec::with_capacity(count); + let markov_step = |prev_tok: u32, + h_row: &[f32], + state: &mut [f32], + prev_embd: &mut [f32], + joint_in: &mut [f32], + joint: &mut [f32], + latent: &mut [f32]| { + self.markov_w1.row_into(prev_tok as usize, prev_embd); + joint_in[..r].copy_from_slice(state); + joint_in[r..2 * r].copy_from_slice(prev_embd); + joint_in[2 * r..2 * r + n].copy_from_slice(h_row); + self.joint_proj.matvec(joint_in, joint); + for (v, &b) in joint.iter_mut().zip(&self.joint_proj_b) { *v += b; } + for k in 0..r { + let gate = crate::ops::sigmoid(joint[k]); + let cand = joint[r + k].tanh(); + state[k] = cand + gate * (state[k] - cand); + latent[k] = joint[2 * r + k].tanh(); + } + }; + match &self.markov_head { MarkovHead::HiddenOut { weight, bias } => { let mut corr = vec![0.0f32; n]; for step in 0..count { let h_row = &hidden[(step + 1) * n..(step + 2) * n]; - self.markov_w1.row_into(prev as usize, &mut prev_embd); - joint_in[..r].copy_from_slice(&state); - joint_in[r..2 * r].copy_from_slice(&prev_embd); - joint_in[2 * r..2 * r + n].copy_from_slice(h_row); - - self.joint_proj.matvec(&joint_in, &mut joint); - for (v, &b) in joint.iter_mut().zip(&self.joint_proj_b) { *v += b; } - - for k in 0..r { - let gate = crate::ops::sigmoid(joint[k]); - let cand = joint[r + k].tanh(); - state[k] = cand + gate * (state[k] - cand); - latent[k] = joint[2 * r + k].tanh(); - } - + markov_step(prev, h_row, &mut state, &mut prev_embd, &mut joint_in, &mut joint, &mut latent); weight.matvec(&latent, &mut corr); for ((c, &b), &h_v) in corr.iter_mut().zip(bias).zip(h_row) { *c = *c + b + h_v; } - prev = target.lm_head_argmax(&corr); drafts.push(prev); } @@ -481,70 +487,39 @@ impl DsparkDrafter { be.put(bias, &bias_buf, 0).ok()?; Some(MarkovW2Gpu { w2: w2_gpu, bias: bias_buf }) }); - let use_gpu = gpu_w2.is_some() + let mut use_gpu = gpu_w2.is_some() && target.lm_head_batch_gpu(&hidden[n..(1 + count) * n], count); - if use_gpu { - let g = gpu_w2.as_ref().unwrap(); - let bias_addr = g.bias.addr(); - for step in 0..count { - let h_row = &hidden[(step + 1) * n..(step + 2) * n]; - self.markov_w1.row_into(prev as usize, &mut prev_embd); - joint_in[..r].copy_from_slice(&state); - joint_in[r..2 * r].copy_from_slice(&prev_embd); - joint_in[2 * r..2 * r + n].copy_from_slice(h_row); - - self.joint_proj.matvec(&joint_in, &mut joint); - for (v, &b) in joint.iter_mut().zip(&self.joint_proj_b) { *v += b; } + let mut cpu_base: Option> = None; + let mut delta = Vec::new(); + let n_vocab = target.cfg.n_vocab; + let nv = n_vocab.min(w2.rows).min(bias.len()); - for k in 0..r { - let gate = crate::ops::sigmoid(joint[k]); - let cand = joint[r + k].tanh(); - state[k] = cand + gate * (state[k] - cand); - latent[k] = joint[2 * r + k].tanh(); - } - - if let Some(id) = target.markov_w2_argmax_gpu(&g.w2, bias_addr, &latent, step) { + for step in 0..count { + let h_row = &hidden[(step + 1) * n..(step + 2) * n]; + markov_step(prev, h_row, &mut state, &mut prev_embd, &mut joint_in, &mut joint, &mut latent); + if use_gpu { + let g = gpu_w2.as_ref().unwrap(); + if let Some(id) = target.markov_w2_argmax_gpu(&g.w2, g.bias.addr(), bias.len(), &latent, step) { prev = id; drafts.push(prev); - } else { - break; + continue; } + use_gpu = false; } - } else { - let n_vocab = target.cfg.n_vocab; - let base_logits = target.lm_head_batch(&hidden[n..(1 + count) * n], count); - let mut delta = vec![0.0f32; w2.rows]; - for step in 0..count { - let h_row = &hidden[(step + 1) * n..(step + 2) * n]; - self.markov_w1.row_into(prev as usize, &mut prev_embd); - joint_in[..r].copy_from_slice(&state); - joint_in[r..2 * r].copy_from_slice(&prev_embd); - joint_in[2 * r..2 * r + n].copy_from_slice(h_row); - - self.joint_proj.matvec(&joint_in, &mut joint); - for (v, &b) in joint.iter_mut().zip(&self.joint_proj_b) { *v += b; } - - for k in 0..r { - let gate = crate::ops::sigmoid(joint[k]); - let cand = joint[r + k].tanh(); - state[k] = cand + gate * (state[k] - cand); - latent[k] = joint[2 * r + k].tanh(); - } - - w2.matvec(&latent, &mut delta); - let base = &base_logits[step * n_vocab..(step + 1) * n_vocab]; - let nv = n_vocab.min(w2.rows).min(bias.len()); - let (mut best_i, mut best_v) = (0usize, f32::NEG_INFINITY); - for i in 0..nv { - let v = base[i] + delta[i] + bias[i]; - if v > best_v { - best_v = v; - best_i = i; - } + let base_all = cpu_base.get_or_insert_with(|| target.lm_head_batch_cpu(&hidden[n..(1 + count) * n], count)); + if delta.is_empty() { delta.resize(w2.rows, 0.0); } + w2.matvec(&latent, &mut delta); + let base = &base_all[step * n_vocab..(step + 1) * n_vocab]; + let (mut best_i, mut best_v) = (0usize, f32::NEG_INFINITY); + for i in 0..nv { + let v = base[i] + delta[i] + bias[i]; + if v > best_v { + best_v = v; + best_i = i; } - prev = best_i as u32; - drafts.push(prev); } + prev = best_i as u32; + drafts.push(prev); } } } diff --git a/src/inkling2/forward.rs b/src/inkling2/forward.rs index c4c4954f..040ef310 100644 --- a/src/inkling2/forward.rs +++ b/src/inkling2/forward.rs @@ -601,23 +601,15 @@ impl<'a> Inkling2Model<'a> { /// Add `w2 @ latent + bias` onto `pf.logits_buf[step]` on GPU and return the argmax token ID. pub(super) fn markov_w2_argmax_gpu( - &self, w2: &crate::backend::GpuTensor, bias_addr: u64, latent: &[f32], step: usize, + &self, w2: &crate::backend::GpuTensor, bias_addr: u64, bias_len: usize, latent: &[f32], step: usize, ) -> Option { - self.device.as_ref()?.markov_w2_argmax_gpu(self, w2, bias_addr, latent, step).ok() + self.device.as_ref()?.markov_w2_argmax_gpu(self, w2, bias_addr, bias_len, latent, step).ok() } pub(super) fn output_rows(&self) -> usize { self.output.rows } - /// Project `nt` hidden states (`[nt, n_embd]`) through the target LM head (`output.weight`) and return - /// `[nt, cfg.n_vocab]` logits before softcap. - pub fn lm_head_batch(&mut self, h_rows: &[f32], nt: usize) -> Vec { - if let Some(mut d) = self.device.take() { - let res = d.lm_head_batch(self, h_rows, nt); - self.device = Some(d); - if let Ok(v) = res { - return v; - } - } + /// Project `nt` hidden states (`[nt, n_embd]`) through the target LM head on CPU only. + pub(super) fn lm_head_batch_cpu(&self, h_rows: &[f32], nt: usize) -> Vec { let rows: Vec<&[f32]> = h_rows.chunks_exact(self.cfg.n_embd).take(nt).collect(); let raw = matvec_rows(&self.output, &rows); if self.output.rows == self.cfg.n_vocab { @@ -630,6 +622,19 @@ impl<'a> Inkling2Model<'a> { out } + /// Project `nt` hidden states (`[nt, n_embd]`) through the target LM head (`output.weight`) and return + /// `[nt, cfg.n_vocab]` logits before softcap. + pub fn lm_head_batch(&mut self, h_rows: &[f32], nt: usize) -> Vec { + if let Some(mut d) = self.device.take() { + let res = d.lm_head_batch(self, h_rows, nt); + self.device = Some(d); + if let Ok(v) = res { + return v; + } + } + self.lm_head_batch_cpu(h_rows, nt) + } + /// Project a single hidden state `h` (`[n_embd]`) through the target LM head (`output.weight`) and return the /// greedy argmax token ID (`0..cfg.n_vocab`) of the logits before the softcap. For drafts. pub fn lm_head_argmax(&self, h: &[f32]) -> u32 { diff --git a/src/inkling2/forward/device.rs b/src/inkling2/forward/device.rs index 061dbb65..836fcceb 100644 --- a/src/inkling2/forward/device.rs +++ b/src/inkling2/forward/device.rs @@ -693,26 +693,27 @@ impl Device { pub(super) fn lm_head_batch_gpu(&mut self, m: &Inkling2Model, h_rows: &[f32], nt: usize) -> Result<()> { let c = &m.cfg; let vrows = m.output.rows; - let d = dev::get().unwrap().lock().unwrap(); + let d = dev::get().context("no GPU device")?.lock().map_err(|_| anyhow::anyhow!("GPU device lock poisoned"))?; let be = &*d.parts[0].be; self.ensure_pf(be, c, vrows, nt)?; let pf = self.pf.as_ref().unwrap(); let o = pf.buf.addr(); be.put(h_rows, &pf.buf, ((pf.p.hn - o) / 4) as usize)?; - be.gemvq(d.tensor(m.output.gpu.unwrap()), pf.p.hn, c.n_embd, 0, pf.logits_buf.addr(), vrows, nt)?; + be.gemvq(d.tensor(m.output.gpu.context("output.weight not on GPU")?), pf.p.hn, c.n_embd, 0, pf.logits_buf.addr(), vrows, nt)?; Ok(()) } /// Add low-rank `w2 @ latent + bias` onto `pf.logits_buf[step]` on GPU and return the argmax token ID. pub(super) fn markov_w2_argmax_gpu( - &self, m: &Inkling2Model, w2: &crate::backend::GpuTensor, bias_addr: u64, latent: &[f32], step: usize, + &self, m: &Inkling2Model, w2: &crate::backend::GpuTensor, bias_addr: u64, bias_len: usize, latent: &[f32], step: usize, ) -> Result { let c = &m.cfg; let vrows = m.output.rows; - let nv = c.n_vocab.min(w2.rows); + let nv = c.n_vocab.min(w2.rows).min(bias_len); + ensure!(nv > 0, "markov_w2: empty vocabulary intersection"); let pf = self.pf.as_ref().context("lm_head_batch_gpu not called")?; let (s, o) = (self.s, self.scr.addr()); - let d = dev::get().unwrap().lock().unwrap(); + let d = dev::get().context("no GPU device")?.lock().map_err(|_| anyhow::anyhow!("GPU device lock poisoned"))?; let be = &*d.parts[0].be; be.put(latent, &self.scr, ((s.hn - o) / 4) as usize)?; be.gemvq(w2, s.hn, w2.cols, 0, s.logits, w2.rows, 1)?; 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 023/515] 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 024/515] 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 025/515] 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 026/515] 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 027/515] 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 028/515] 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 029/515] 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 030/515] 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 031/515] 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() From 9ff263aabaf4cc854bf4af2c7cd38ca5241ee90b Mon Sep 17 00:00:00 2001 From: Vasyl-Trefilov Date: Tue, 24 Nov 2026 13:09:54 +0100 Subject: [PATCH 032/515] batched decode: a GEMM of a batch step (step_batch, at most 64 positions) on the int8 path runs the new gemmd_* kernels, where a warp owns 16 rows of W and its lanes decode the weights from global memory into registers while x comes from a shared-memory window of q8 rows (it ran gemmi_*/gemmis_*, which stage W in shared memory with two barriers per 64 columns); for a matrix of at most 16384 rows two blocks share 128 rows, each over half of the columns, and the block that ends second adds the sums of the other; the GEMMs of step_batch pass the new BATCHED flag, so the GEMMs of a single request take the kernels they took and their bits do not change; Qwen3-4B-Instruct-2507 Q4_K_M on the RTX 3060, one forward of 8 / 16 / 32 / 64 rows: 29.3 / 28.6 / 35.7 / 51.9 -> 19.7 / 21.9 / 28.9 / 42.1 ms; tests/kernels.rs compares the kernel with per-row dot products and with the tile GEMM for every type --- src/backend.rs | 4 + src/cuda/kernels.cu | 208 +++++++++++++++++++++++++++++++++++++++ src/cuda/mod.rs | 44 +++++++-- src/gpu_model/prefill.rs | 18 ++-- src/vulkan/mod.rs | 2 +- tests/kernels.rs | 53 +++++++++- 6 files changed, 308 insertions(+), 21 deletions(-) diff --git a/src/backend.rs b/src/backend.rs index 12fad957..d9013e61 100644 --- a/src/backend.rs +++ b/src/backend.rs @@ -91,6 +91,10 @@ pub fn device_order(cuda: &[Option], vk: &[T]) -> Vec(tiles, wd, nd, x, xrow, y, y_stride, rows, n64, act, sc); \ } ITYPES(DEF_GEMMI) + +// ---- small-batch int8 GEMM (batched decode: at most 64 positions) ---- +// grid = ks * ceil(rows / 128), block = 256, dynamic shared memory (Gpu::gemm_raw has the size); pb = 8, 16, 32 or 64 +// is nd rounded up. +// A warp owns 16 W rows as the mma A operand. Lane (g, t) decodes the 8 weights 32 q + 8 t .. of rows g and g + 8 +// from global memory itself, so W is not staged in shared memory and the K loop has no barrier per step +// (gemmi_q: two barriers per 64 columns and every warp of the block decodes for the mmas of half of them). +// Both operands permute the k index of the mma the same way (column 8 t + j is k 4 t + j, column 8 t + 4 + j is +// k 16 + 4 t + j), so a lane's 8 weights are one QI get and its 8 x values one load. A type with a scale per 16 runs +// two mmas per 32 columns, each with the lanes of the other half zeroed. +// X (q8 rows) is the B operand, from a shared-memory window of GEMMD_XW(pb) columns that cp.async double-buffers: one +// barrier per window. +// ks = 2: two blocks (seg 0, 1) share 128 rows, each over half of the columns (Gpu::gemm_raw has the rule and the +// measurement). Both blocks store their partial sums in scr ([seg][position][row]); the one that ends second (flag: +// the count of blocks done for these rows, over all launches) adds the other's and writes y. a + b is b + a, so the +// result does not depend on which block that is. +#define GEMMD_XW(pb) ((pb) >= 32 ? 128 : 4096 / (pb)) +template +__device__ __forceinline__ void gemmd_q(const u8* w, const u8* __restrict__ x, int nd, int pb, int ks, float* scr, int* flag, + float* y, int y_stride, int rows, int cols, int act, float sc) { + // One window: pb rows of xw + 32 int8 (the pitch puts two lanes on a bank, the least an 8-byte load allows), + // then xw / 32 scales and xw / 16 sums per row. Two windows, then pk. + extern __shared__ __align__(16) signed char gemmd_s[]; + int tid = threadIdx.x, warp = tid >> 5, lane = tid & 31, g = lane >> 2, t = lane & 3; + int seg = blockIdx.x % ks, rb = blockIdx.x / ks, bs = blockDim.x, ts = tid; + int xw = GEMMD_XW(pb), lx = 31 - __clz(xw), pitch = xw + 32, od = pb * pitch, os = od + pb * (xw >> 3), xb_ = os + pb * (xw >> 2); + int nq = cols / 32, qw = xw >> 5, nwin = (cols + xw - 1) >> lx, nws = (nwin + ks - 1) / ks, w0 = seg * nws; + signed char* gx = gemmd_s; + float* pk = (float*)(gx + 2 * xb_); // per (position pair, 32 columns): d0, d1, s0, s1, then the four half sums + int np = nd, npt = (np + 7) >> 3, r0 = (rb * (bs >> 5) + warp) * 16; + const u8* xr = x; + int nc0 = pb * (xw >> 4), nc1 = nc0 + pb * (xw >> 7), nc2 = nc1 + pb * (xw >> 6); + auto ldx = [&](int wi) { // window wi of this block's columns + signed char* d = gx + (wi & 1) * xb_; + int k0 = (w0 + wi) * xw; + for (int c = ts; c < nc2; c += bs) { // 16-byte chunks: int8, then scales, then sums + int pos, o; const u8* src; signed char* dst; bool ok; + if (c < nc0) { + pos = c >> (lx - 4); o = (c & ((xw >> 4) - 1)) * 16; + src = xr + (size_t)pos * Q8_ROW(cols) + k0 + o; dst = d + pos * pitch + o; ok = k0 + o < cols; + } else if (c < nc1) { + pos = (c - nc0) >> (lx - 7); o = ((c - nc0) & ((xw >> 7) - 1)) * 16; + src = xr + (size_t)pos * Q8_ROW(cols) + cols + (k0 >> 3) + o; dst = d + od + pos * (xw >> 3) + o; ok = k0 + o * 8 < cols; + } else { + pos = (c - nc1) >> (lx - 6); o = ((c - nc1) & ((xw >> 6) - 1)) * 16; + src = xr + (size_t)pos * Q8_ROW(cols) + cols + cols / 8 + (k0 >> 2) + o; dst = d + os + pos * (xw >> 2) + o; ok = k0 + o * 4 < cols; + } + cp_async16(dst, src, ok && pos < np); + } + cp_async_commit(); + }; + const bool live = r0 < rows; + const u8* pa = w + (size_t)min(r0 + g, rows - 1) * ROWB(cols, SBB); + const u8* pb_ = w + (size_t)min(r0 + g + 8, rows - 1) * ROWB(cols, SBB); + constexpr int KS = scale32() ? 32 : 16; + float acc[8][4] = {}; + const signed char* xb; + // The scales and sums of window wi, from the staged q8 rows into pk: one load per mma instead of four. + auto pack = [&](int wi) { + const float* xd = (const float*)(gx + (wi & 1) * xb_ + od); const float* xs = (const float*)(gx + (wi & 1) * xb_ + os); + for (int c = ts; c < (pb >> 1) * qw; c += bs) { + int p = 2 * (c % (pb >> 1)), kw = c / (pb >> 1); // [kw][pair]: the four t of a warp load from 16 banks + float* o = pk + c * 8; + *(float2*)o = make_float2(xd[p * qw + kw], xd[(p + 1) * qw + kw]); + if (QI::MIN) { + float2 s0 = *(const float2*)(xs + p * 2 * qw + 2 * kw), s1 = *(const float2*)(xs + (p + 1) * 2 * qw + 2 * kw); + *(float2*)(o + 2) = make_float2(s0.x + s0.y, s1.x + s1.y); + *(float4*)(o + 4) = make_float4(s0.x, s0.y, s1.x, s1.y); + } + } + __syncthreads(); + }; + // The mmas of one 32-column block (kw in the window): A fragment a0..a3, W scale and min of rows g and g + 8. + auto blk = [&](int kw, u32 a0, u32 a1, u32 a2, u32 a3, float wda, float wma, float wdb, float wmb) { + // Scale per 16: lanes t < 2 hold the first 16 columns of the 32, lane t ^ 2 the scale of the other 16. + float oda = 0.f, oma = 0.f, odb = 0.f, omb = 0.f; + if (KS == 16) { + oda = __shfl_xor_sync(0xffffffffu, wda, 2); odb = __shfl_xor_sync(0xffffffffu, wdb, 2); + if (QI::MIN) { oma = __shfl_xor_sync(0xffffffffu, wma, 2); omb = __shfl_xor_sync(0xffffffffu, wmb, 2); } + } + #pragma unroll + for (int pt = 0; pt < 8; pt++) { // 8 positions an mma + if (pt >= npt) break; + const uint2 bx = *(const uint2*)(xb + (pt * 8 + g) * pitch + kw * 32 + 8 * t); + const float* o = pk + (kw * (pb >> 1) + pt * 4 + t) * 8; + float dx[2], s32[2] = {0.f, 0.f}; + float2 sx[2] = {make_float2(0.f, 0.f), make_float2(0.f, 0.f)}; + if (QI::MIN && KS == 32) { const float4 v = *(const float4*)o; dx[0] = v.x; dx[1] = v.y; s32[0] = v.z; s32[1] = v.w; } + else { + const float2 v = *(const float2*)o; dx[0] = v.x; dx[1] = v.y; + if (QI::MIN) { const float4 u = *(const float4*)(o + 4); sx[0] = make_float2(u.x, u.y); sx[1] = make_float2(u.z, u.w); } + } + #pragma unroll + for (int h = 0; h < 32 / KS; h++) { + const bool mine = KS == 32 || (t >> 1) == h; + int c[4]; + mma_s8_16832_b(c, mine ? a0 : 0, mine ? a1 : 0, mine ? a2 : 0, mine ? a3 : 0, bx.x, bx.y); + const float dw[2] = {mine ? wda : oda, mine ? wdb : odb}, mw[2] = {mine ? wma : oma, mine ? wmb : omb}; + #pragma unroll + for (int i = 0; i < 4; i++) { + // Two fmas into the sum (a product, a subtraction and an add cost one instruction more). + acc[pt][i] = fmaf(__int_as_float(c[i]) - 12582912.0f, dx[i & 1] * dw[i >> 1], acc[pt][i]); // i2f_small + if (QI::MIN) acc[pt][i] = fmaf(-(KS == 32 ? s32[i & 1] : h ? sx[i & 1].y : sx[i & 1].x), mw[i >> 1], acc[pt][i]); + } + } + } + }; + // Generic: block q + 1 is decoded during block q's mmas. + int la = 0, ha = 0, lb = 0, hb = 0; float da = 0.f, ma = 0.f, db = 0.f, mb = 0.f; + auto dec = [&](int q) { + ma = mb = 0.f; + int sub = (q & 7) * 4 + t; size_t o = (size_t)(q >> 3) * SBB; + QI::get(pa + o, sub, la, ha, da, ma); + QI::get(pb_ + o, sub, lb, hb, db, mb); + }; + // Q4_K: 64 columns of a row are 32 bytes of nibbles (low: the first 32 columns), so the lane's two blocks are one + // 8-byte load a row; the pair after is loaded before this pair's mmas. + const bool k4 = T == 12 && ((size_t)w & 15) == 0 && cols % 256 == 0; + uint4 sa_ = make_uint4(0, 0, 0, 0), sb_ = sa_; uint2 ua = make_uint2(0, 0), ub = ua; + float sda = 0.f, sma = 0.f, sdb = 0.f, smb = 0.f; + auto ldp = [&](int p, bool hdr) { // hdr: the pair is the first of its super-block that this block reads + size_t o = (size_t)(p >> 2) * 144; int j = 16 + 32 * (p & 3) + 8 * t; + if (hdr) { sa_ = *(const uint4*)(pa + o); sb_ = *(const uint4*)(pb_ + o); } + ua = *(const uint2*)(pa + o + j); ub = *(const uint2*)(pb_ + o + j); + }; + ldx(0); + cp_async_wait<0>(); + __syncthreads(); + pack(0); + if (live && w0 * qw < nq) { if (k4) ldp(w0 * qw / 2, true); else dec(w0 * qw); } + for (int wi = 0; wi < nws; wi++) { + if (wi + 1 < nws) ldx(wi + 1); // into the buffer of window wi - 1: every thread passed the barrier below + xb = gx + (wi & 1) * xb_; + int qa = (w0 + wi) * qw, q1 = min(nq, qa + qw); + if (live && k4) { + for (int p = qa / 2; p < q1 / 2; p++) { + const uint4 ca = sa_, cb = sb_; const uint2 va = ua, vb = ub; + if (p + 1 < nq / 2) ldp(p + 1, !((p + 1) & 3)); + // The four lanes of a row would decode the same scale: at an even pair (a window starts at one: it + // is 128 columns or more) lane t decodes the scale of block t of the next four, and a shuffle + // hands each block's scale to the row's lanes. + if (!(p & 1)) { + k4_dm_w(ca.x, ca.y, ca.z, ca.w, 2 * (p & 2) + t, sda, sma); + k4_dm_w(cb.x, cb.y, cb.z, cb.w, 2 * (p & 2) + t, sdb, smb); + } + #pragma unroll + for (int h = 0; h < 2; h++) { + const int from = (lane & ~3) | (2 * (p & 1) + h); + const float wda = __shfl_sync(0xffffffffu, sda, from), wma = __shfl_sync(0xffffffffu, sma, from); + const float wdb = __shfl_sync(0xffffffffu, sdb, from), wmb = __shfl_sync(0xffffffffu, smb, from); + blk(2 * p + h - qa, (va.x >> (4 * h)) & 0x0F0F0F0Fu, (vb.x >> (4 * h)) & 0x0F0F0F0Fu, + (va.y >> (4 * h)) & 0x0F0F0F0Fu, (vb.y >> (4 * h)) & 0x0F0F0F0Fu, wda, wma, wdb, wmb); + } + } + } else if (live) { + for (int q = qa; q < q1; q++) { + const u32 a0 = la, a1 = lb, a2 = ha, a3 = hb; + const float wda = da, wma = ma, wdb = db, wmb = mb; + if (q + 1 < nq) dec(q + 1); + blk(q - qa, a0, a1, a2, a3, wda, wma, wdb, wmb); + } + } + cp_async_wait<0>(); __syncthreads(); + if (wi + 1 < nws) pack(wi + 1); + } + if (ks > 1) { + float* mine = scr + (size_t)seg * nd * rows; + const volatile float* other = scr + (size_t)(seg ^ 1) * nd * rows; // another block's stores: not cached + if (live) { + #pragma unroll + for (int j = 0; j < 32; j++) { + int r = r0 + g + 8 * ((j >> 1) & 1), p = (j >> 2) * 8 + 2 * t + (j & 1); + if (r < rows && p < np) mine[(size_t)p * rows + r] = acc[j >> 2][j & 3]; + } + } + __threadfence(); // every thread's sums are in memory before the count says so + __syncthreads(); + int* second = (int*)gemmd_s; + if (tid == 0) *second = atomicAdd(flag + rb, 1) & 1; + __syncthreads(); + if (!*second) return; + if (live) { + #pragma unroll + for (int j = 0; j < 32; j++) { + int r = r0 + g + 8 * ((j >> 1) & 1), p = (j >> 2) * 8 + 2 * t + (j & 1); + if (r < rows && p < np) acc[j >> 2][j & 3] += other[(size_t)p * rows + r]; + } + } + } + if (live) { + #pragma unroll + for (int pt = 0; pt < 8; pt++) + #pragma unroll + for (int i = 0; i < 4; i++) { + int r = r0 + g + 8 * (i >> 1), p = pt * 8 + 2 * t + (i & 1); + if (r >= rows || p >= np) continue; + float* yp = y + (size_t)p * y_stride + r; + float v = acc[pt][i] * sc; + *yp = act == 0 ? v : act == 1 ? silu(*yp) * v : *yp + v; + } + } +} +#define DEF_GEMMD(T, NAME, SBB) \ + extern "C" __global__ void __launch_bounds__(256, 2) gemmd_##NAME(const u8* w, const u8* x, int nd, int pb, \ + int ks, float* scr, int* flag, float* y, int y_stride, int rows, int cols, int act, float sc) { \ + gemmd_q(w, x, nd, pb, ks, scr, flag, y, y_stride, rows, cols, act, sc); \ + } +ITYPES(DEF_GEMMD) #endif // ---- elementwise / norm ---- diff --git a/src/cuda/mod.rs b/src/cuda/mod.rs index f07f182c..85ad4d1f 100644 --- a/src/cuda/mod.rs +++ b/src/cuda/mod.rs @@ -3,7 +3,7 @@ use crate::quant::{GgmlType, tables::*}; use anyhow::{Context, bail}; -use crate::backend::{Backend, Buf, SAME_X}; +use crate::backend::{BATCHED, Backend, Buf, SAME_X}; use cudarc::driver::{CudaContext, CudaEvent, CudaFunction, CudaGraph, CudaSlice, CudaStream, DevicePtr, PinnedHostSlice, LaunchConfig, PushKernelArg, result, sys}; use cudarc::nvrtc::Ptx; use std::collections::{BTreeMap, HashMap, VecDeque}; @@ -42,6 +42,9 @@ pub struct Gpu { /// q8 rows of the last integer GEMM's X (see quant_q8 in kernels.cu), grown on demand, and which x they hold /// (x, x_stride, n_x, cols) for a `SAME_X` call; None after a call without it that did not quantize. q8: std::sync::Mutex<(CudaSlice, Option<[u64; 4]>)>, + /// `gemmd_*` scratch for a GEMM that two blocks share the columns of: a slot per stream (see `GEMMD_SLOT`), + /// allocated by the first such GEMM. + gd: std::sync::OnceLock>, /// The kernels were compiled for KV cache mode (0 = f16, 1 = q8, 2 = q4). pub kv_mode: u32, /// The GPU has int8 tensor-core mma (sm_80+). Turing runs the prefill GEMM on the f16 path instead. @@ -71,6 +74,12 @@ const RING: usize = 64 << 20; const RING_MIN: usize = 256 << 10; /// `nb` inside `beside`: launches stay on the main stream, copies go to the side stream. const BESIDE: usize = usize::MAX - 1; +/// `gemmd_*` splits the columns of a matrix of at most this many rows between two blocks. Measured on an RTX 3060 +/// with Qwen3-4B: the 9728-row FFN matrices gain at 8 and 16 positions and are level at 64; the output head (151936 +/// rows) fills the card without the split. +const GEMMD_SPLIT_ROWS: usize = 16384; +/// A scratch slot of `gemmd_*`: a count per 128 rows, then the partial sums of both blocks for 64 positions. +const GEMMD_SLOT: usize = GEMMD_SPLIT_ROWS / 128 * 4 + 2 * 64 * GEMMD_SPLIT_ROWS * 4; /// A recorded graph. Its handles are plain CUDA driver handles, which any thread may launch once the context is /// bound (cudarc leaves `CudaGraph` without `Send` only because it holds raw pointers). @@ -355,15 +364,15 @@ fn smem_log(family: &str, optin: usize, stat: usize, set: Option, carveou format!("cuda shared memory: opt-in {optin} B per block, {family}: {stat} B static, dynamic max {dynamic}, carveout {carveout}") } -/// The kernel names to load from the cubin: the full list on sm_80+, without the int8 prefill GEMM (`gemmi_*` and -/// `gemmis_*`, 23 non-float types x 2 fewer names) on a device where that code is not compiled in. Pure so a CPU test can pin -/// both lists (326 / 280 names). +/// The kernel names to load from the cubin: the full list on sm_80+, without the int8 GEMM (`gemmi_*`, `gemmis_*` and +/// `gemmd_*`, 23 non-float types x 3 fewer names) on a device where that code is not compiled in. Pure so a CPU test can pin +/// both lists (393 / 324 names). fn kernel_names(sm80: bool) -> Vec { let int8 = move |&&t: &&GgmlType| sm80 && !t.float_x(); KERNELS.iter().map(|s| s.to_string()) .chain(QTYPES.iter().flat_map(|&t| ["dequant", "gemv", "gemvn", "moe_gemv", "gemm", "gemms"].map(|p| kname(p, t)))) .chain(QTYPES.iter().flat_map(|&t| ["gemv", "gemvn", "moe_gemv"].map(|p| kname(p, t) + "_p"))) - .chain(QTYPES.iter().filter(int8).flat_map(|&t| [kname("gemmi", t), kname("gemmis", t)])) + .chain(QTYPES.iter().filter(int8).flat_map(|&t| [kname("gemmi", t), kname("gemmis", t), kname("gemmd", t)])) .chain([64, 128, 256, 512].iter().flat_map(|h| [format!("attn_decode_{h}"), format!("attn_decode_gqa_{h}")])) .chain(["attn_decode_gqa4_128".to_string()]) .collect() @@ -523,7 +532,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, gd: Default::default(), kv_mode, 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] } @@ -590,7 +599,7 @@ impl Gpu { // So does one of at most 32 positions (batched decode): the same blocks, a quarter of the positions in each. let sm = tiles == 0 && (grid.0 * grid.1 < 112 || nd <= 32); let grid = if sm { (grid.0, nd.div_ceil(32) as u32) } else { grid }; - let (same, act) = (act & SAME_X != 0, act & !SAME_X); + let (same, batched, act) = (act & SAME_X != 0, act & BATCHED != 0, act & 3); let mut q8 = self.q8.lock().unwrap(); let key = Some([x, x_stride as u64, n_x as u64, cols as u64]); let reuse = same && q8.1 == key; @@ -613,6 +622,20 @@ impl Gpu { // Only SAME_X promises that x still holds what was quantized: the same address can hold new rows. if !same { q8.1 = None; } let xq = self.q8_x(&mut q8, ty, cols, n_x, x, x_stride)?.expect("int8 GEMM without a quantized x"); + // A step of a batch of requests: at most 64 rows of x, no tile list. + if batched && tiles == 0 && xrow == 0 && nd <= 64 { + let pb = nd.next_power_of_two().max(8); + let xw = if pb >= 32 { 128 } else { 4096 / pb }; // GEMMD_XW + let ks = if rows <= GEMMD_SPLIT_ROWS && cols >= 2 * xw { 2 } else { 1 }; + // The launches of a stream run in order, so each stream has a slot (`st`: the odd launches of a batch go to `side`). + let n = self.nb.load(Relaxed); + if self.gd.get().is_none() { let _ = self.gd.set(self.stream.alloc_zeros(2 * GEMMD_SLOT)?); } + let slot = self.ptr(self.gd.get().unwrap()) + if n < BESIDE && n % 2 == 1 { GEMMD_SLOT as u64 } else { 0 }; + launch!(self, &kname("gemmd", ty), + cfg(((ks * rows.div_ceil(128)) as u32, 1), 256, (2 * pb * (xw + 32 + xw / 8 + xw / 4) + pb / 2 * (xw / 32) * 32) as u32), + wd, xq, nd as i32, pb as i32, ks as i32, slot + (GEMMD_SPLIT_ROWS / 128 * 4) as u64, slot, y, y_stride as i32, rows as i32, cols as i32, act, w_scale); + return Ok(()); + } launch!(self, &kname(if sm { "gemmis" } else { "gemmi" }, ty), cfg(grid, 2 * GEMM_BM as u32, 0), tiles, wd, nd as i32, xq, xrow, y, y_stride as i32, rows as i32, (cols / 64) as i32, act, w_scale); if tiles != 0 { @@ -774,6 +797,7 @@ impl Backend for Gpu { fns: self.fns.clone(), i8_gemm: self.i8_gemm, q8, + gd: Default::default(), kv_mode: self.kv_mode, int8_mma: self.int8_mma, turing: self.turing, @@ -1498,13 +1522,13 @@ mod tests { } /// M1-T5, CPU-only: the loaded name list drops `gemmi_*`/`gemmis_*` only on a device where kernels.cu compiles - /// them out. 370 names today (sm_80); 23 non-float types x 2 fewer names = 324 on sm_70. + /// them out. 393 names today (sm_80); 23 non-float types x 3 fewer names = 324 on sm_70. #[test] fn kernel_names() { let (sm70, sm80) = (super::kernel_names(false), super::kernel_names(true)); - assert_eq!(sm80.len(), 370); + assert_eq!(sm80.len(), 393); assert_eq!(sm70.len(), 324); - assert!(sm70.iter().all(|n| !n.starts_with("gemmi") && !n.starts_with("gemmis")), + assert!(sm70.iter().all(|n| !n.starts_with("gemmi") && !n.starts_with("gemmd")), "sm_70 must not load the int8 prefill GEMM: {:?}", sm70.iter().filter(|n| n.starts_with("gemmi")).collect::>()); assert!(sm80.contains(&"gemmi_q4_k".to_string())); diff --git a/src/gpu_model/prefill.rs b/src/gpu_model/prefill.rs index 7c0170c1..838dd90f 100644 --- a/src/gpu_model/prefill.rs +++ b/src/gpu_model/prefill.rs @@ -3,7 +3,7 @@ //! copied into a small staging area, a group of them at a time, each group's copy beside the previous group's GEMMs. use super::{Ffn, GpuModel, HcAt, Mixer}; -use crate::backend::{Backend, Buf, GEMM_BM, SAME_X}; +use crate::backend::{BATCHED, Backend, Buf, GEMM_BM, SAME_X}; use crate::expert_cache::MATS; use crate::model::Model; use crate::weights::Prefetch; @@ -812,18 +812,18 @@ impl GpuModel<'_> { let (Mixer::Attn { q, k, v, qn, kn, o, sink, .. }, Ffn::Dense { gate, up, down }) = (&ly.mixer, &ly.ffn) else { unreachable!() }; let kvt = bt.kvt.addr() + (8 * i * 2 * bt.rows) as u64; g.rms_norm(x, ne, ly.attn_norm.as_ref().unwrap().ptr, h, ne, ne, t, eps)?; - g.gemm_dense(q, t, h, ne, at(l.a), nh * qs, 0)?; - g.gemm_dense(k, t, h, ne, kraw, kv, SAME_X)?; - g.gemm_dense(v, t, h, ne, vv, kv, SAME_X)?; + g.gemm_dense(q, t, h, ne, at(l.a), nh * qs, BATCHED)?; + g.gemm_dense(k, t, h, ne, kraw, kv, SAME_X | BATCHED)?; + g.gemm_dense(v, t, h, ne, vv, kv, SAME_X | BATCHED)?; let win = c.swa.get(self.first + i).copied().unwrap_or(false).then_some(c.n_swa).unwrap_or(0); g.rms_norm_rope_qk_rows(at(l.a), qs, qn.ptr, at(l.b), nh, kraw, kn.ptr, kk, nkv, hd, eps, c.n_rot, step, c.rope_base, vv, kvt, t)?; g.attn_rows(at(l.b), if c.q_gate { at(l.a) } else { 0 }, at(l.d), bt.attp.addr(), step, nh, nkv, hd, 1.0 / (hd as f32).sqrt(), t, sink.as_ref().map_or(0, |s| s.ptr), win, kvt, splits)?; - g.gemm_dense(o, t, at(l.d), nh * hd, x, ne, 2)?; + g.gemm_dense(o, t, at(l.d), nh * hd, x, ne, 2 | BATCHED)?; g.rms_norm(x, ne, ly.post_norm.as_ref().unwrap().ptr, h, ne, ne, t, eps)?; - g.gemm_dense(gate, t, h, ne, at(l.ge), c.n_ff, 0)?; - g.gemm_dense(up, t, h, ne, at(l.ge), c.n_ff, 1 | SAME_X)?; - g.gemm_dense(down, t, at(l.ge), c.n_ff, x, ne, 2)?; + g.gemm_dense(gate, t, h, ne, at(l.ge), c.n_ff, BATCHED)?; + g.gemm_dense(up, t, h, ne, at(l.ge), c.n_ff, 1 | SAME_X | BATCHED)?; + g.gemm_dense(down, t, at(l.ge), c.n_ff, x, ne, 2 | BATCHED)?; g.kick()?; } // Region a, not h: the next forward's first GEMM reads h, and the backend may keep the quantized rows of @@ -831,7 +831,7 @@ impl GpuModel<'_> { let (on, nr) = (self.output_norm.as_ref().unwrap().ptr, heads.len()); if all { g.rms_norm(x, ne, on, at(l.a), ne, ne, t, eps)?; } else { for (j, &r) in heads.iter().enumerate() { g.rms_norm(at(r * ne), ne, on, at(l.a + j * ne), ne, ne, 1, eps)?; } } - g.gemm_dense(self.output.as_ref().unwrap(), nr, at(l.a), ne, bt.logits.addr(), nvoc, 0)?; + g.gemm_dense(self.output.as_ref().unwrap(), nr, at(l.a), ne, bt.logits.addr(), nvoc, BATCHED)?; g.argmax_rows(bt.logits.addr(), nvoc, nr, bt.amax.addr())?; let am = g.get::(&bt.amax, 0, nr)?; heads.iter().zip(am).enumerate() diff --git a/src/vulkan/mod.rs b/src/vulkan/mod.rs index 158b5080..65e74b44 100644 --- a/src/vulkan/mod.rs +++ b/src/vulkan/mod.rs @@ -988,7 +988,7 @@ impl Vk { ensure!(cols % 64 == 0, "{} matrix with {cols} columns: GEMM needs a multiple of 64", ty.name()); if n_tiles == 0 { return Ok(()); } let (spec, grid, nk) = (self.wspec(ty), [rows.div_ceil(64), n_tiles, 1], (cols / 64) as u32); - let (same, act) = (act & SAME_X != 0, act & !SAME_X); + let (same, act) = (act & SAME_X != 0, act & 3); // BATCHED: the same kernels let mut q8 = self.q8_mutex(n_x, cols).lock().unwrap(); let key = Some([x, x_stride as u64, n_x as u64, cols as u64]); // as on CUDA let reuse = same && q8.1 == key; diff --git a/tests/kernels.rs b/tests/kernels.rs index 8313ed50..44622294 100644 --- a/tests/kernels.rs +++ b/tests/kernels.rs @@ -1,7 +1,7 @@ //! Kernel tests, run on every backend that opens (`common::backends`). mod common; use common::{down, up}; -use rusting_strata::backend::{Backend, ATT_GQA_MIN, ATT_SPLITS, GEMM_BM, GpuTensor, SAME_X}; +use rusting_strata::backend::{Backend, ATT_GQA_MIN, ATT_SPLITS, BATCHED, GEMM_BM, GpuTensor, SAME_X}; use rusting_strata::{cuda::Gpu, gguf::Gguf, quant::GgmlType, weights::{Tensor, Weights}}; fn xs(n: usize) -> Vec { @@ -446,6 +446,57 @@ fn gemm_matches_reference_for_every_type() { } } +/// The small-batch GEMM (a `BATCHED` `gemm_dense` of at most 64 rows of x, the decode of a batch) against per-row dot products of the +/// first 300 rows, and against the tile-list GEMM, for every type, with partial warps and position groups. +#[test] +fn small_batch_gemm_matches_tile_gemm() { + let Some(p) = common::model_path() else { return }; + for (bk, gpu) in common::backends() { + let gpu = &*gpu; + let g = Gguf::open(&p).unwrap(); + let w = Weights::new(&g).unwrap(); + let mut seen = std::collections::BTreeSet::new(); + for (name, info) in &g.tensors { + let Ok(ty) = GgmlType::from_u32(info.ty) else { continue }; + if info.dims.len() < 2 || info.dims[0] % 256 != 0 || !seen.insert(ty.name()) { continue; } + let t = w.get(name).unwrap(); + // 300 rows: two blocks of 128 and a part of a third, whose last warp has 12 rows. + let t = Tensor { rows: t.rows.min(300), data: &t.data[..t.data.len() / t.rows * t.rows.min(300)], ..t }; + let dt = gpu.upload(&t).unwrap(); + let int8 = gpu.mmq(t.ty) && t.cols % 128 == 0; + for n in [1usize, 7, 16, 40, 64] { + let x = xs(n * t.cols); + let xrow: Vec = (0..n as i32).collect(); + let (dx, dr, dtl) = (up(gpu, &x), up(gpu, &xrow), up(gpu, &[dt.ptr, (n as u64) << 32])); + let (dy, dz) = (gpu.zeros::(n * t.rows).unwrap(), gpu.zeros::(n * t.rows).unwrap()); + gpu.gemm_dense(&dt, n, dx.addr(), t.cols, dy.addr(), t.rows, BATCHED).unwrap(); + gpu.gemm(t.ty, t.rows, t.cols, dtl.addr(), 1, dx.addr(), t.cols, n, dr.addr(), dz.addr(), t.rows, 0).unwrap(); + let (got, tile) = (down::(gpu, &dy), down::(gpu, &dz)); + if int8 { + let mut wr = vec![0f32; t.cols]; + let mut want = vec![0f32; n * t.rows]; + for r in 0..t.rows { + t.row(r, &mut wr); + for i in 0..n { want[i * t.rows + r] = wr.iter().zip(as_seen(t.ty, &x[i * t.cols..][..t.cols])).map(|(a, b)| a * b).sum(); } + } + let e = rel_l2(&got, &want); + assert!(e <= 1e-4, "{bk} {} ({name}), {n} rows of x: rel err {e}", ty.name()); + } + // The same products as the tile GEMM, summed as two halves of the columns. + let e = rel_l2(&got, &tile); + assert!(e <= 1e-5, "{bk} {} ({name}), {n} rows of x: rel err {e} against the tile GEMM", ty.name()); + // Either block of a pair of the column split may end last: the bits do not depend on which. + for _ in 0..4 { + gpu.gemm_dense(&dt, n, dx.addr(), t.cols, dy.addr(), t.rows, BATCHED).unwrap(); + let again = down::(gpu, &dy); + assert!(again.iter().zip(&got).all(|(a, b)| a.to_bits() == b.to_bits()), "{bk} {} ({name}), {n} rows of x: two runs differ", ty.name()); + } + } + eprintln!("{bk} {:8} {name}: ok", ty.name()); + } + } +} + /// A `SAME_X` GEMM inside `batch` whose x was not quantized by the previous GEMM (that one's type is off the int8 /// path, e.g. IQ2_XS) falls back to the f16 kernel instead of failing. Mixed-quant models hit this in prefill. #[test] From 8ac37e68e9031099aaa5b4a71f92d6c5872e72a4 Mon Sep 17 00:00:00 2001 From: Vasyl-Trefilov Date: Tue, 24 Nov 2026 13:29:10 +0100 Subject: [PATCH 033/515] serve: a chat request without max_tokens for DeepSeek, GLM, Hy4, Inkling 2 and Gemma 4 runs until the model stops or the context is full, as it does for the Qwen models (it stopped after 256 tokens); --max-tokens on the server and max_tokens in the request limit it as before (#93) --- docs/USAGE.md | 2 ++ src/deepseek/chat.rs | 2 +- src/gemma4/mod.rs | 2 +- src/glm/mod.rs | 2 +- src/hy4/chat.rs | 2 +- src/inkling2/chat.rs | 2 +- 6 files changed, 7 insertions(+), 5 deletions(-) diff --git a/docs/USAGE.md b/docs/USAGE.md index f22cff24..3666be11 100644 --- a/docs/USAGE.md +++ b/docs/USAGE.md @@ -193,6 +193,8 @@ other MCP clients use, and pass it with `--mcp ` (or `STRATA_MCP`; the def `penalty_last_n` tokens of the reply (default 64; 0 turns it off, -1 takes the whole reply). The window is for the repeat penalty only: the presence and frequency penalties count the whole reply. - `max_tokens` (or `max_completion_tokens`) and `stop` (up to 16 strings) work as in the OpenAI API; `n` must be 1. + Without `max_tokens` (and without `--max-tokens` on the server) a reply runs until the model stops or the context + is full. - A request whose last message has role `assistant` (and no tool calls) continues that message: the reply holds only the new text. The chat page's continue button uses this. - Thinking is on by default (`--think false` turns it off). A request overrides it with `chat_template_kwargs.enable_thinking` diff --git a/src/deepseek/chat.rs b/src/deepseek/chat.rs index a028374b..bb8afe10 100644 --- a/src/deepseek/chat.rs +++ b/src/deepseek/chat.rs @@ -103,7 +103,7 @@ pub fn serve<'a>(g: &'a Gguf, tok: &'a Tokenizer, name: &'a str) -> anyhow::Resu let keep = if m.toks.len() < ids.len() && ids.starts_with(&m.toks) { m.toks.len() } else { m.reset(); 0 }; let mut logits = m.prefill(&ids[keep..]); let prefill_s = t.elapsed().as_secs_f64(); - let n = q.max_tokens.unwrap_or(256).min(ctx - ids.len()); + let n = q.max_tokens.unwrap_or(usize::MAX).min(ctx - ids.len()); if q.stream { let _ = write!(c, "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n"); } let chunk = |d: serde_json::Value, fin: Option<&str>| json!({"object": "chat.completion.chunk", "model": name, "choices": [{"index": 0, "delta": d, "finish_reason": fin}]}); let tools = q.tool_calls && !q.tools.is_empty(); diff --git a/src/gemma4/mod.rs b/src/gemma4/mod.rs index a881e630..b77ed630 100644 --- a/src/gemma4/mod.rs +++ b/src/gemma4/mod.rs @@ -290,7 +290,7 @@ pub fn serve<'a>(g: &'a Gguf, tok: &'a crate::tokenizer::Tokenizer, name: &'a st // A failed feed leaves part of the prompt in the cache, so the next request starts over. let logits = match feed(&mut m, &seq[keep..]) { Ok(l) => l, Err(e) => { m.reset(); return Err(e) } }; let prefill_s = t.elapsed().as_secs_f64(); - let n = q.max_tokens.unwrap_or(256).min(ctx - ids.len()); + let n = q.max_tokens.unwrap_or(usize::MAX).min(ctx - ids.len()); if q.stream { let _ = write!(c, "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n"); } let stream = q.stream; let chunk = |d: serde_json::Value, fin: Option<&str>| json!({"object": "chat.completion.chunk", "model": name, "choices": [{"index": 0, "delta": d, "finish_reason": fin}]}); diff --git a/src/glm/mod.rs b/src/glm/mod.rs index 48dfc42a..8dc80d44 100644 --- a/src/glm/mod.rs +++ b/src/glm/mod.rs @@ -424,7 +424,7 @@ pub fn serve<'a>(g: &'a Gguf, tok: &'a crate::tokenizer::Tokenizer, name: &'a st let keep = if m.toks.len() < ids.len() && ids.starts_with(&m.toks) { m.toks.len() } else { m.reset(); 0 }; let logits = m.prefill(&ids[keep..]); let prefill_s = t.elapsed().as_secs_f64(); - let n = q.max_tokens.unwrap_or(256).min(ctx - ids.len()); + let n = q.max_tokens.unwrap_or(usize::MAX).min(ctx - ids.len()); if q.stream { let _ = write!(c, "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n"); } let chunk = |d: serde_json::Value, fin: Option<&str>| json!({"object": "chat.completion.chunk", "model": name, "choices": [{"index": 0, "delta": d, "finish_reason": fin}]}); let stream = q.stream; diff --git a/src/hy4/chat.rs b/src/hy4/chat.rs index 652c5d3a..6564ed40 100644 --- a/src/hy4/chat.rs +++ b/src/hy4/chat.rs @@ -191,7 +191,7 @@ pub fn serve<'a>(g: &'a Gguf, tok: &'a Tokenizer, name: &'a str) -> anyhow::Resu let keep = if m.toks.len() < ids.len() && ids.starts_with(&m.toks) { m.toks.len() } else { m.reset(); 0 }; let logits = m.prefill(&ids[keep..]); let prefill_s = t.elapsed().as_secs_f64(); - let n = q.max_tokens.unwrap_or(256).min(max_ctx - ids.len()); + let n = q.max_tokens.unwrap_or(usize::MAX).min(max_ctx - ids.len()); if q.stream { let _ = write!(c, "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n"); } let chunk = |d: serde_json::Value, fin: Option<&str>| json!({"object": "chat.completion.chunk", "model": name, "choices": [{"index": 0, "delta": d, "finish_reason": fin}]}); let tools = q.tool_calls && !q.tools.is_empty(); diff --git a/src/inkling2/chat.rs b/src/inkling2/chat.rs index 1ee3e799..c51495d2 100644 --- a/src/inkling2/chat.rs +++ b/src/inkling2/chat.rs @@ -553,7 +553,7 @@ pub fn serve<'a>(g: &'a Gguf, tok: &'a Tokenizer, name: &'a str, opts: Inkling2O if let Some(s) = q.seed { smp.rng = s.max(1); } let budget = q.thinking_budget.unwrap_or(opts.thinking_budget); - let n = q.max_tokens.unwrap_or(256).min(m.max_ctx - m.toks.len()); + let n = q.max_tokens.unwrap_or(usize::MAX).min(m.max_ctx - m.toks.len()); if q.stream { let _ = write!(c, "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n"); } let chunk = |d: serde_json::Value, fin: Option<&str>| json!({"object": "chat.completion.chunk", "model": name, "choices": [{"index": 0, "delta": d, "finish_reason": fin}]}); let tools = q.tool_calls && !q.tools.is_empty(); From b3c5dfa5dcb33115a92f1ac18b1e9fcd97df1ece Mon Sep 17 00:00:00 2001 From: Vasyl-Trefilov Date: Tue, 24 Nov 2026 13:29:10 +0100 Subject: [PATCH 034/515] weights: a model file on a network file system (SMB, NFS, 9p, Ceph, Gluster, a FUSE mount, from /proc/self/mountinfo) is not read ahead into the page cache at start, because the request for the whole file at once takes the link from all other programs; its pages are read when they are used, and STRATA_PRELOAD=1 reads it ahead all the same (#94) --- docs/USAGE.md | 2 ++ src/gguf.rs | 4 ++-- src/weights.rs | 30 ++++++++++++++++++++++++++++++ 3 files changed, 34 insertions(+), 2 deletions(-) diff --git a/docs/USAGE.md b/docs/USAGE.md index 3666be11..de7286f2 100644 --- a/docs/USAGE.md +++ b/docs/USAGE.md @@ -259,6 +259,8 @@ file system that caches data, or from a tmpfs copy. When the model files fit in RAM with 4 GiB to spare, they are read into the page cache in the background from the start and nothing is dropped, so experts that run on the CPU do not wait for the drive on their first use. `STRATA_PRELOAD=1` forces that, `STRATA_PRELOAD=0` turns it off. +A file on a network file system (SMB, NFS, a FUSE mount) is not read ahead, because that asks the server for the whole +file at once: its pages are read when they are used (`STRATA_PRELOAD=1` reads it ahead all the same). Otherwise bytes copied to VRAM are dropped from the page cache (`MADV_DONTNEED`), so on a model close to the machine's RAM the experts that missed VRAM keep their pages; `STRATA_COLD_KEEP=1` only marks them reclaimable instead. `serve` learns diff --git a/src/gguf.rs b/src/gguf.rs index 45332d0a..a98284d5 100644 --- a/src/gguf.rs +++ b/src/gguf.rs @@ -108,7 +108,7 @@ impl Gguf { // The reads are queued by `weights::preload`, one call per file. Said here because nothing else shows it: the // pages are not mapped into the process, so its resident size does not grow. #[cfg(target_os = "linux")] - if crate::weights::fits_ram() { + if crate::weights::fits_ram() && !crate::weights::net_fs(path) { crate::say!("page cache: reading {} MB of {} in the background (it shows as buff/cache, not as used memory)", g.files.iter().map(|(m, _)| m.0.len()).sum::() >> 20, path.file_name().and_then(|s| s.to_str()).unwrap_or("the model")); } @@ -129,7 +129,7 @@ impl Gguf { if std::env::var_os("STRATA_HUGEPAGE").is_some() { let _ = mmap.advise(memmap2::Advice::HugePage); } - crate::weights::preload(&mmap, read); + crate::weights::preload(&mmap, read && !crate::weights::net_fs(path)); let mmap = Map(mmap); let mut c = Cur { b: &mmap.0, p: 0 }; if c.take(4)? != b"GGUF" { bail!("{}: not a GGUF file", path.display()); } diff --git a/src/weights.rs b/src/weights.rs index 0f21cd67..fe63b6a3 100644 --- a/src/weights.rs +++ b/src/weights.rs @@ -306,6 +306,36 @@ pub fn fits_ram() -> bool { } } +/// Whether `path` is on a network file system (SMB, NFS, 9p, Ceph, Gluster or a FUSE mount), from +/// `/proc/self/mountinfo`. `preload` asks for the whole file at once: a server on the network then gets every read +/// together, and they take the link from all other programs (issue #94). So such a file is read when its pages are +/// touched. `STRATA_PRELOAD=1` reads it ahead all the same. +pub fn net_fs(path: &std::path::Path) -> bool { + if std::env::var_os("STRATA_PRELOAD").is_some() { return false; } + let (Ok(p), Ok(mounts)) = (path.canonicalize(), std::fs::read_to_string("/proc/self/mountinfo")) else { return false }; + net_fs_in(&p, &mounts) +} + +/// `net_fs` for the text of a mountinfo file: the type of the longest mount point that is a prefix of `p` decides. +// ponytail: a mount point with a space is written with \040 and does not match, so the mount above it decides. +fn net_fs_in(p: &std::path::Path, mounts: &str) -> bool { + mounts.lines().filter_map(|l| { let (a, b) = l.split_once(" - ")?; Some((a.split(' ').nth(4)?, b.split(' ').next()?)) }) + .filter(|(m, _)| p.starts_with(m)).max_by_key(|(m, _)| m.len()) + .is_some_and(|(_, t)| ["cifs", "smb3", "smbfs", "nfs", "nfs4", "9p", "ceph", "glusterfs"].contains(&t) || t.starts_with("fuse.")) +} + +#[test] +fn net_fs_reads_mountinfo() { + let m = "22 1 8:2 / / rw,relatime shared:1 - ext4 /dev/sda2 rw\n\ + 40 22 0:35 / /mnt/nas rw,relatime shared:20 - cifs //nas/models rw,vers=3.1.1\n\ + 41 40 8:17 / /mnt/nas/local rw - xfs /dev/sdb1 rw\n\ + 42 22 0:40 / /home/u/remote rw,nosuid - fuse.sshfs u@host:/ rw\n\ + 43 22 8:33 / /mnt/win rw - fuseblk /dev/sdc1 rw\n"; + let on = |p: &str| net_fs_in(std::path::Path::new(p), m); + assert!(on("/mnt/nas/a.gguf") && on("/home/u/remote/a.gguf")); + assert!(!on("/mnt/nas/local/a.gguf") && !on("/mnt/nasty/a.gguf") && !on("/home/u/a.gguf") && !on("/mnt/win/a.gguf")); +} + /// Counts a newly mapped model file; with `read`, when the files fit in RAM (`fits_ram`), a background thread starts /// reading it into the page cache, so experts that run on the CPU do not wait for the drive on their first use /// (issue #49). From d8d681b04bcd6d91cae4e75a99ddad89b78b88ed Mon Sep 17 00:00:00 2001 From: Vasyl-Trefilov Date: Tue, 24 Nov 2026 13:37:34 +0100 Subject: [PATCH 035/515] inkling2: a DSpark draft file whose markov_w2 matrix does not have the rank of markov_w1 as its column count, whose markov_w2.bias does not have one value per row of the matrix, or whose mask_embd is not whole rows of the embedding size is refused at load with a message (it could panic in the first draft); the doc comment of embed_normed is on its function again; the two lm_head_batch functions that nothing called are deleted --- src/inkling2/dspark.rs | 10 +++++----- src/inkling2/forward.rs | 16 ++-------------- src/inkling2/forward/device.rs | 20 -------------------- 3 files changed, 7 insertions(+), 39 deletions(-) diff --git a/src/inkling2/dspark.rs b/src/inkling2/dspark.rs index 3a368129..ee6d6186 100644 --- a/src/inkling2/dspark.rs +++ b/src/inkling2/dspark.rs @@ -161,15 +161,15 @@ impl DsparkDrafter { None }; let mask_embd = f32s(g_ref, "mask_embd.weight")?; + ensure!(mask_embd.len() >= n_embd && mask_embd.len() % n_embd == 0, "dspark: mask_embd.weight len {} is not rows of {n_embd}", mask_embd.len()); let output_norm = f32s(g_ref, "output_norm.weight")?; let joint_proj = host_mat(g_ref, "joint_proj.weight")?; let joint_proj_b = f32s(g_ref, "joint_proj.bias")?; let markov_head = if g_ref.tensors.contains_key("markov_w2.weight") { - MarkovHead::Logits { - w2: host_mat(g_ref, "markov_w2.weight")?, - bias: f32s(g_ref, "markov_w2.bias")?, - gpu: std::sync::OnceLock::new(), - } + let (w2, bias) = (host_mat(g_ref, "markov_w2.weight")?, f32s(g_ref, "markov_w2.bias")?); + ensure!(w2.cols == rank, "dspark: markov_w2.weight has {} columns, markov_w1 gives rank {rank}", w2.cols); + ensure!(bias.len() == w2.rows, "dspark: markov_w2.bias len {} != {} rows of markov_w2.weight", bias.len(), w2.rows); + MarkovHead::Logits { w2, bias, gpu: std::sync::OnceLock::new() } } else { MarkovHead::HiddenOut { weight: host_mat(g_ref, "dspark_hidden_out.weight")?, diff --git a/src/inkling2/forward.rs b/src/inkling2/forward.rs index 040ef310..69ba0cf4 100644 --- a/src/inkling2/forward.rs +++ b/src/inkling2/forward.rs @@ -576,12 +576,13 @@ impl<'a> Inkling2Model<'a> { self.ngram.as_ref().is_some_and(|ng| ng.cfg.is_enabled()) || self.dspark.is_some() } - /// Look up `tok` in `tok_embd` and RMS-normalize with `tok_norm` (`cfg.eps`), writing `out` (`[n_embd]`). + /// Look up `tok` in `tok_embd`, writing the row to `out` (`[n_embd]`) with no norm. pub fn embed_raw(&self, tok: u32, out: &mut [f32]) { assert!((tok as usize) < self.tok_embd.rows, "token {tok} is outside the vocabulary"); self.tok_embd.row_into(tok as usize, out); } + /// Look up `tok` in `tok_embd` and RMS-normalize with `tok_norm` (`cfg.eps`), writing `out` (`[n_embd]`). pub fn embed_normed(&self, tok: u32, out: &mut [f32]) { assert!((tok as usize) < self.tok_embd.rows, "token {tok} is outside the vocabulary"); let mut emb = vec![0.0f32; self.cfg.n_embd]; @@ -622,19 +623,6 @@ impl<'a> Inkling2Model<'a> { out } - /// Project `nt` hidden states (`[nt, n_embd]`) through the target LM head (`output.weight`) and return - /// `[nt, cfg.n_vocab]` logits before softcap. - pub fn lm_head_batch(&mut self, h_rows: &[f32], nt: usize) -> Vec { - if let Some(mut d) = self.device.take() { - let res = d.lm_head_batch(self, h_rows, nt); - self.device = Some(d); - if let Ok(v) = res { - return v; - } - } - self.lm_head_batch_cpu(h_rows, nt) - } - /// Project a single hidden state `h` (`[n_embd]`) through the target LM head (`output.weight`) and return the /// greedy argmax token ID (`0..cfg.n_vocab`) of the logits before the softcap. For drafts. pub fn lm_head_argmax(&self, h: &[f32]) -> u32 { diff --git a/src/inkling2/forward/device.rs b/src/inkling2/forward/device.rs index 836fcceb..8aa879e9 100644 --- a/src/inkling2/forward/device.rs +++ b/src/inkling2/forward/device.rs @@ -724,26 +724,6 @@ impl Device { Ok(id) } - /// Project `nt` hidden vectors (`[nt, n_embd]`) through the target's LM head on GPU in one batched matvec - /// and return `[nt, c.n_vocab]` logits (before softcap). - pub(super) fn lm_head_batch(&mut self, m: &Inkling2Model, h_rows: &[f32], nt: usize) -> Result> { - let c = &m.cfg; - let vrows = m.output.rows; - self.lm_head_batch_gpu(m, h_rows, nt)?; - let d = dev::get().unwrap().lock().unwrap(); - let be = &*d.parts[0].be; - let pf = self.pf.as_ref().unwrap(); - let raw = be.get::(&pf.logits_buf, 0, nt * vrows)?; - if vrows == c.n_vocab { - return Ok(raw); - } - let mut out = Vec::with_capacity(nt * c.n_vocab); - for row in raw.chunks_exact(vrows) { - out.extend_from_slice(&row[..c.n_vocab]); - } - Ok(out) - } - fn record_dspark_visit(&self, visit: usize, cur_a: u64, nt: usize, n: usize) -> Result<()> { let Some(k) = DSPARK_VISITS.iter().position(|&v| v == visit) else { return Ok(()) }; let d = dev::get().unwrap().lock().unwrap(); From 76142a0195613e757596a47365d4eacab1fcee4b Mon Sep 17 00:00:00 2001 From: Hannes Klas Date: Tue, 24 Nov 2026 13:41:23 +0100 Subject: [PATCH 036/515] hip: a batch step's GEMM ignores main's BATCHED flag act & !SAME_X let BATCHED (8) reach the kernel, which ran it as an add to y; the activation is act & 3, as on Vulkan. --- src/hip/mod.rs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/hip/mod.rs b/src/hip/mod.rs index 31c3edef..66df59eb 100644 --- a/src/hip/mod.rs +++ b/src/hip/mod.rs @@ -348,7 +348,8 @@ impl Gpu { x: u64, x_stride: usize, _n_x: usize, xrow: u64, y: u64, y_stride: usize, act: i32, w_scale: f32) -> anyhow::Result<()> { if cols % 64 != 0 { bail!("{} matrix with {cols} columns: GEMM needs a multiple of 64", ty.name()); } if n_tiles == 0 { return Ok(()) } - let (same, act) = (act & SAME_X != 0, act & !SAME_X); + // Only the activation reaches the kernel: SAME_X and BATCHED (the same kernels here) are flags for the host. + let (same, act) = (act & SAME_X != 0, act & 3); let _ = same; let grid = (rows.div_ceil(64) as u32, n_tiles as u32); let sm = tiles == 0 && (grid.0 * grid.1 < 112 || nd <= 32); @@ -977,6 +978,13 @@ mod tests { g.gemm_dense(&t, n, gx.addr(), cols, gy.addr(), rows, 0).unwrap(); g.sync().unwrap(); let got: Vec = g.get(&gy, 0, n * rows).unwrap(); + // A batch step's flag picks no other kernel here, so it gives the same bits (it reached the kernel as an add, + // which y filled with ones shows). + g.put(&vec![1f32; n * rows], &gy, 0).unwrap(); + g.gemm_dense(&t, n, gx.addr(), cols, gy.addr(), rows, crate::backend::BATCHED).unwrap(); + g.sync().unwrap(); + let batched: Vec = g.get(&gy, 0, n * rows).unwrap(); + assert!(got.iter().zip(&batched).all(|(a, b)| a.to_bits() == b.to_bits()), "rows {rows}: BATCHED changed the result"); let mut worst = 0f32; let mut at = 0; for i in 0..n * rows { From d29454722a31ec52170de0aa4b62c54e17b626cc Mon Sep 17 00:00:00 2001 From: Hannes Klas Date: Tue, 24 Nov 2026 13:58:41 +0100 Subject: [PATCH 037/515] hip: the BATCHED test comment says the flag is masked, not added The host strips the flag with act & 3, so the ones-prefill is overwritten. A leaked flag would reach the kernel as act 8 and fail the bit comparison. --- src/hip/mod.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/hip/mod.rs b/src/hip/mod.rs index 66df59eb..ba30bb25 100644 --- a/src/hip/mod.rs +++ b/src/hip/mod.rs @@ -978,8 +978,9 @@ mod tests { g.gemm_dense(&t, n, gx.addr(), cols, gy.addr(), rows, 0).unwrap(); g.sync().unwrap(); let got: Vec = g.get(&gy, 0, n * rows).unwrap(); - // A batch step's flag picks no other kernel here, so it gives the same bits (it reached the kernel as an add, - // which y filled with ones shows). + // A batch step's flag picks no other kernel here, so it gives the same bits. The host masks the flag off + // (`act & 3`), so this call stores over y. If the flag ever reached the kernel as `act` 8, the kernel would add + // to the ones and the bit comparison below would fail. g.put(&vec![1f32; n * rows], &gy, 0).unwrap(); g.gemm_dense(&t, n, gx.addr(), cols, gy.addr(), rows, crate::backend::BATCHED).unwrap(); g.sync().unwrap(); From 57299c04c39d9918f4b0cc96bff9ee8cd4466cca Mon Sep 17 00:00:00 2001 From: Hannes Klas Date: Tue, 24 Nov 2026 14:59:44 +0100 Subject: [PATCH 038/515] hip: argmax_rows sizes its partials in bytes, so 9 to 64 rows fit Each int2 partial is 8 bytes; the buffer was 64 * AMAX_PARTS bytes and the check counted rows, not bytes. A test runs argmax on 64 rows against a CPU argmax and opens the backend through backend::open. --- src/hip/mod.rs | 36 ++++++++++++++++++++++++++++++++++-- 1 file changed, 34 insertions(+), 2 deletions(-) diff --git a/src/hip/mod.rs b/src/hip/mod.rs index ba30bb25..65b6459d 100644 --- a/src/hip/mod.rs +++ b/src/hip/mod.rs @@ -206,7 +206,8 @@ impl Gpu { } fns.insert(name, f); } - let am_buf = alloc_raw(&hip, 64 * AMAX_PARTS)?; + // argmax_part writes an int2 (8 bytes) per partial: AMAX_PARTS per row, up to 64 rows. + let am_buf = alloc_raw(&hip, 64 * AMAX_PARTS * 8)?; let q8_buf = alloc_raw(&hip, 1)?; // Pinned ring for large host-to-device copies. let mut host: *mut c_void = std::ptr::null_mut(); @@ -661,7 +662,7 @@ impl Backend for Gpu { fn argmax_rows(&self, x: u64, n: usize, rows: usize, out: u64) -> anyhow::Result<()> { let part = self.ptr(&self.am); - anyhow::ensure!(rows * AMAX_PARTS <= self.am.len(), "argmax_rows: {rows} rows"); + anyhow::ensure!(rows * AMAX_PARTS * 8 <= self.am.len(), "argmax_rows: {rows} rows"); // len is in bytes launch!(self, "argmax_part", cfg((AMAX_PARTS as u32, rows as u32), 256, 0), x, n as i32, part); launch!(self, "argmax_rows", cfg((rows as u32, 1), AMAX_PARTS as u32, 0), part, n as i32, out); Ok(()) @@ -912,6 +913,37 @@ mod tests { assert!(got.iter().zip(&want).all(|(a, b)| a == b), "first mismatch at {:?}", got.iter().zip(&want).position(|(a, b)| a != b)); } + /// `argmax_rows` on 64 rows, the most a batch step has. The partials are 8 bytes each, AMAX_PARTS per row; the + /// buffer used to be sized as if they were one byte, so rows past 8 wrote past its end. + #[test] + fn argmax_rows_takes_64_rows() { + let Ok(gpu) = Gpu::new(0) else { eprintln!("skipping: no HIP device"); return }; + let g: &dyn Backend = &gpu; + let (rows, n) = (64usize, 1000usize); + let mut st = 5u32; + let x: Vec = (0..rows * n).map(|_| { st = st.wrapping_mul(1664525).wrapping_add(1013904223); (st >> 8) as f32 }).collect(); + let want: Vec = (0..rows).map(|r| { + let row = &x[r * n..(r + 1) * n]; + let mut best = 0; + for i in 1..n { if row[i] > row[best] { best = i; } } + best as i32 + }).collect(); + let bx = g.alloc(4 * rows * n).unwrap(); + let bo = g.alloc(4 * rows).unwrap(); + g.put(&x, &bx, 0).unwrap(); + g.argmax_rows(bx.addr(), n, rows, bo.addr()).unwrap(); + g.sync().unwrap(); + let got: Vec = g.get(&bo, 0, rows).unwrap(); + assert_eq!(got, want); + } + + /// `--backend hip` reaches this backend through `backend::open`, the path the CLI takes. + #[test] + fn opens_through_backend_open() { + let Ok(b) = crate::backend::open(Some("hip"), 0) else { eprintln!("skipping: no HIP device"); return }; + assert_eq!(b.name(), "hip"); + } + /// `norm_gate` with the quantize-to-int8 epilogue: the first kernel of the qwen35 attention layer, and the one /// that faulted first on the card, so it gets its own comparison against the reference math. #[test] From 6b58bac93a88a1903480d719fcf02fc3bdb4c9d2 Mon Sep 17 00:00:00 2001 From: Hannes Klas Date: Tue, 24 Nov 2026 14:59:44 +0100 Subject: [PATCH 039/515] hip: --device with several indices is refused, and --backend lists hip hip runs one device per process, so a split would put every layer on the first card. The --backend help and docs/USAGE.md name hip. --- docs/USAGE.md | 3 ++- src/backend.rs | 19 ++++++++++++++++++- src/main.rs | 8 ++++++-- 3 files changed, 26 insertions(+), 4 deletions(-) diff --git a/docs/USAGE.md b/docs/USAGE.md index f22cff24..46c22b8d 100644 --- a/docs/USAGE.md +++ b/docs/USAGE.md @@ -71,6 +71,7 @@ other MCP clients use, and pass it with `--mcp ` (or `STRATA_MCP`; the def ## Flags +- `--backend NAME` GPU backend: `cuda`, `vulkan` or `hip` (AMD cards through ROCm, one device per run, see [HIP.md](HIP.md)). Without it CUDA is used when it loads, else Vulkan. - `--ctx` KV cache size in tokens (default 4096). For Inkling 2, Hy4, GLM, DeepSeek and Gemma 4 it is the prompt plus reply limit instead, and the default is the context the model was trained on; their caches grow with the text. - `--mtp [N]` speculative decoding with the model's draft head. Greedy tokens stay the same; sampling keeps its distribution. Needs a GGUF with an MTP head (for example the Qwen3.6-35B-A3B MTP files). @@ -225,7 +226,7 @@ OpenCode and other agents use the OpenAI address. `--device 0,1` splits the layers over the cards in proportion to their free VRAM, so more experts stay resident. The cards run one after the other, so one request gets more memory, not twice the speed of one card. MTP drafting is off on -a split model. +a split model. The HIP backend runs one device, so `--device 0,1` is refused with `--backend hip`. An index is the same card on both backends. NVIDIA cards are counted as CUDA counts them (by default the fastest card first, which is not the order of `nvidia-smi`), on Vulkan too; the other Vulkan devices follow, dedicated cards before diff --git a/src/backend.rs b/src/backend.rs index fc56393c..1fa750dd 100644 --- a/src/backend.rs +++ b/src/backend.rs @@ -59,6 +59,15 @@ unsafe impl Plain for u64 {} /// Device memory, recorded graphs and kernel ops. Host copies are synchronous; device work runs in queue order. /// Pointer arguments are device addresses; strides are in floats unless named otherwise. /// The backend `kind` ("cuda", "vulkan" or "hip") on GPU `device`; with no kind, CUDA if it loads, else Vulkan. +/// Refuses a `--device` list with several indices on the HIP backend: `hip::Gpu` opens one device per process +/// (hipSetDevice runs once, in `Gpu::new`), so a split over two cards would run both layers on the first one. +pub fn check_devices(kind: Option<&str>, devices: &[usize]) -> anyhow::Result<()> { + if kind == Some("hip") && devices.len() > 1 { + anyhow::bail!("the hip backend runs one device: --device {} needs cuda or vulkan", devices.iter().map(|d| d.to_string()).collect::>().join(",")); + } + Ok(()) +} + pub fn open(kind: Option<&str>, device: usize) -> anyhow::Result> { match kind { Some("cuda") => Ok(Box::new(crate::cuda::Gpu::new(device)?)), @@ -534,7 +543,15 @@ impl<'a> dyn Backend + 'a { #[cfg(test)] mod tests { - use super::device_order; + use super::{check_devices, device_order}; + + #[test] + fn hip_refuses_a_device_split_and_nothing_else() { + assert!(check_devices(Some("hip"), &[0, 1]).is_err()); + assert!(check_devices(Some("hip"), &[0]).is_ok()); + assert!(check_devices(Some("cuda"), &[0, 1]).is_ok()); + assert!(check_devices(None, &[0, 1]).is_ok()); + } /// Identifiers are letters here. Two cards of one model have one name and two identifiers, so names play no part. #[test] diff --git a/src/main.rs b/src/main.rs index 30f8ee18..34638d11 100644 --- a/src/main.rs +++ b/src/main.rs @@ -146,7 +146,7 @@ struct Engine { /// 5.3x smaller KV memory for 512k-1M ctx; numerics differ from f16). #[arg(long, default_value = "f16", value_parser = ["f16", "q8", "q4", "q2"])] kv: String, - /// GPU backend: cuda or vulkan [default: cuda if it loads, else vulkan]. + /// GPU backend: cuda, vulkan or hip [default: cuda if it loads, else vulkan]. #[arg(long)] backend: Option, /// GPU index, or several separated by commas (such as 0,1) to split the layers over those GPUs in proportion to @@ -394,7 +394,10 @@ impl Engine { } if self.llama_numerics { unsafe { std::env::set_var("STRATA_LLAMA_NUMERICS", "1") } } // read by Gpu::new set_kv_env(&self.kv); // read by Gpu::new and Vk::new - let open = || self.device.iter().map(|&d| backend::open(self.backend.as_deref(), d)).collect::>>(); + let open = || { + backend::check_devices(self.backend.as_deref(), &self.device)?; + self.device.iter().map(|&d| backend::open(self.backend.as_deref(), d)).collect::>>() + }; let bk = match self.gpu.then(open).transpose() { Err(e) if self.cpu_fallback => { say!("no GPU backend ({e:#}), running on the CPU"); None } r => r?, @@ -2090,6 +2093,7 @@ fn best(f: &mut dyn FnMut() -> anyhow::Result<()>) -> anyhow::Result { /// With `aux` (`--mtp-model`/`--draft-model`) the drafts are measured with that file, and runs given the same file use /// the measured draft count. fn calibrate(model: &Path, aux: Option<&Path>, ctx: usize, margin: &[usize], kind: Option<&str>, device: &[usize], mut split: Option>) -> anyhow::Result<()> { + backend::check_devices(kind, device)?; let g = Gguf::open(model)?; let aux_g = open_mtp_gguf(aux)?; let m = Model::load_with_aux(&g, aux_g.as_ref(), &[])?; From 48e35b1097b0648edabc8bf1f5d73a2413ae8cc0 Mon Sep 17 00:00:00 2001 From: Hannes Klas Date: Tue, 24 Nov 2026 15:06:21 +0100 Subject: [PATCH 040/515] hip: the argmax test gives each row one maximum Each row is a permutation of 0..n, so the strict-greater reference needs no tie rule. The old random rows passed only because the seed is fixed. --- src/hip/mod.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/hip/mod.rs b/src/hip/mod.rs index 65b6459d..0fa55ae3 100644 --- a/src/hip/mod.rs +++ b/src/hip/mod.rs @@ -920,8 +920,8 @@ mod tests { let Ok(gpu) = Gpu::new(0) else { eprintln!("skipping: no HIP device"); return }; let g: &dyn Backend = &gpu; let (rows, n) = (64usize, 1000usize); - let mut st = 5u32; - let x: Vec = (0..rows * n).map(|_| { st = st.wrapping_mul(1664525).wrapping_add(1013904223); (st >> 8) as f32 }).collect(); + // Each row is a permutation of 0..n, so its maximum is unique and the reference needs no tie rule. + let x: Vec = (0..rows * n).map(|k| { let (r, i) = (k / n, k % n); ((i * 7919 + r * 31) % n) as f32 }).collect(); let want: Vec = (0..rows).map(|r| { let row = &x[r * n..(r + 1) * n]; let mut best = 0; From e4baa037e792c68303b707131044257a9d60d010 Mon Sep 17 00:00:00 2001 From: Hannes Klas Date: Tue, 24 Nov 2026 15:06:21 +0100 Subject: [PATCH 041/515] backend: open_all checks a device list once for every caller serve and calibrate opened a list with their own check; a new caller could skip it and split a hip run. calibrate now fails when it opens its devices, after the model is loaded, not before. --- src/backend.rs | 6 ++++++ src/main.rs | 8 ++------ 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/src/backend.rs b/src/backend.rs index 1fa750dd..12489b2d 100644 --- a/src/backend.rs +++ b/src/backend.rs @@ -68,6 +68,12 @@ pub fn check_devices(kind: Option<&str>, devices: &[usize]) -> anyhow::Result<() Ok(()) } +/// Opens every device of a `--device` list, after the check above. Callers open a list through this, not one device at a time. +pub fn open_all(kind: Option<&str>, devices: &[usize]) -> anyhow::Result>> { + check_devices(kind, devices)?; + devices.iter().map(|&d| open(kind, d)).collect() +} + pub fn open(kind: Option<&str>, device: usize) -> anyhow::Result> { match kind { Some("cuda") => Ok(Box::new(crate::cuda::Gpu::new(device)?)), diff --git a/src/main.rs b/src/main.rs index 34638d11..18f7e4f0 100644 --- a/src/main.rs +++ b/src/main.rs @@ -394,10 +394,7 @@ impl Engine { } if self.llama_numerics { unsafe { std::env::set_var("STRATA_LLAMA_NUMERICS", "1") } } // read by Gpu::new set_kv_env(&self.kv); // read by Gpu::new and Vk::new - let open = || { - backend::check_devices(self.backend.as_deref(), &self.device)?; - self.device.iter().map(|&d| backend::open(self.backend.as_deref(), d)).collect::>>() - }; + let open = || backend::open_all(self.backend.as_deref(), &self.device); let bk = match self.gpu.then(open).transpose() { Err(e) if self.cpu_fallback => { say!("no GPU backend ({e:#}), running on the CPU"); None } r => r?, @@ -2093,7 +2090,6 @@ fn best(f: &mut dyn FnMut() -> anyhow::Result<()>) -> anyhow::Result { /// With `aux` (`--mtp-model`/`--draft-model`) the drafts are measured with that file, and runs given the same file use /// the measured draft count. fn calibrate(model: &Path, aux: Option<&Path>, ctx: usize, margin: &[usize], kind: Option<&str>, device: &[usize], mut split: Option>) -> anyhow::Result<()> { - backend::check_devices(kind, device)?; let g = Gguf::open(model)?; let aux_g = open_mtp_gguf(aux)?; let m = Model::load_with_aux(&g, aux_g.as_ref(), &[])?; @@ -2104,7 +2100,7 @@ fn calibrate(model: &Path, aux: Option<&Path>, ctx: usize, margin: &[usize], kin anyhow::ensure!(n_pf >= 512, "--ctx too small to calibrate"); let pf = prose(&tok, n_pf)?; let load = |chunk: usize, split: Option<&[f64]>| -> anyhow::Result { - let bk = device.iter().map(|&d| backend::open(kind, d)).collect::>>()?; + let bk = backend::open_all(kind, device)?; let mut gm = GpuModel::load_split_margins(&m, bk, ctx, chunk, margin, split, kload, 1).context(LOAD_HINT)?; gm.adapt_every = 0; // fixed placement: steadier timings Ok(gm) From aed841f28ebde01671da8bc3e00eb466a4ae9f6d Mon Sep 17 00:00:00 2001 From: Hannes Klas Date: Tue, 24 Nov 2026 15:15:02 +0100 Subject: [PATCH 042/515] backend: calibrate checks its --device list before it reads the GGUF A bad --device used to fail after the model was loaded, and the check ran again for every chunk. It now fails before Gguf::open; open_all still checks when the devices open. --- src/main.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main.rs b/src/main.rs index 18f7e4f0..00314b51 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2090,6 +2090,7 @@ fn best(f: &mut dyn FnMut() -> anyhow::Result<()>) -> anyhow::Result { /// With `aux` (`--mtp-model`/`--draft-model`) the drafts are measured with that file, and runs given the same file use /// the measured draft count. fn calibrate(model: &Path, aux: Option<&Path>, ctx: usize, margin: &[usize], kind: Option<&str>, device: &[usize], mut split: Option>) -> anyhow::Result<()> { + backend::check_devices(kind, device)?; // before the GGUF is read: a bad --device fails here, not after the load let g = Gguf::open(model)?; let aux_g = open_mtp_gguf(aux)?; let m = Model::load_with_aux(&g, aux_g.as_ref(), &[])?; From af3a8fc518c9bf7f0cf5f09b5a85420d3e0cee7c Mon Sep 17 00:00:00 2001 From: Hannes Klas Date: Tue, 24 Nov 2026 15:15:02 +0100 Subject: [PATCH 043/515] hip: an argmax test with ties checks the first index Values 0..16 give most rows a tied maximum; the CPU reference takes the first index, as the kernel does. The permutation test keeps the unique-maximum case. --- src/hip/mod.rs | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/src/hip/mod.rs b/src/hip/mod.rs index 0fa55ae3..235e99d0 100644 --- a/src/hip/mod.rs +++ b/src/hip/mod.rs @@ -937,6 +937,30 @@ mod tests { assert_eq!(got, want); } + /// `argmax_rows` on values 0..16, so most rows tie for the maximum: the first index wins, as in the CPU reference. + #[test] + fn argmax_rows_breaks_ties_at_the_first_index() { + let Ok(gpu) = Gpu::new(0) else { eprintln!("skipping: no HIP device"); return }; + let g: &dyn Backend = &gpu; + let (rows, n) = (64usize, 1000usize); + let mut st = 77u32; + let x: Vec = (0..rows * n).map(|_| { st = st.wrapping_mul(1664525).wrapping_add(1013904223); ((st >> 16) % 16) as f32 }).collect(); + let want: Vec = (0..rows).map(|r| { + let row = &x[r * n..(r + 1) * n]; + let mut best = 0; + for i in 1..n { if row[i] > row[best] { best = i; } } + best as i32 + }).collect(); + assert!(want.iter().enumerate().any(|(r, &b)| x[r * n..(r + 1) * n].iter().filter(|&&v| v == x[r * n + b as usize]).count() > 1), "no row has a tie"); + let bx = g.alloc(4 * rows * n).unwrap(); + let bo = g.alloc(4 * rows).unwrap(); + g.put(&x, &bx, 0).unwrap(); + g.argmax_rows(bx.addr(), n, rows, bo.addr()).unwrap(); + g.sync().unwrap(); + let got: Vec = g.get(&bo, 0, rows).unwrap(); + assert_eq!(got, want); + } + /// `--backend hip` reaches this backend through `backend::open`, the path the CLI takes. #[test] fn opens_through_backend_open() { From 79173bf3253814d31d9e6960842d4ede533aa8f0 Mon Sep 17 00:00:00 2001 From: Vasyl-Trefilov Date: Tue, 24 Nov 2026 17:14:07 +0100 Subject: [PATCH 044/515] Release 1.3.1: idk --- Cargo.lock | 2 +- Cargo.toml | 2 +- README.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index edc681e6..7447971b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -819,7 +819,7 @@ dependencies = [ [[package]] name = "rusting_strata" -version = "1.3.0" +version = "1.3.1" dependencies = [ "anyhow", "ash", diff --git a/Cargo.toml b/Cargo.toml index 2a377dae..2169da7e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "rusting_strata" -version = "1.3.0" +version = "1.3.1" edition = "2024" license-file = "LICENSE.md" diff --git a/README.md b/README.md index 3b9e7f2f..4402f59d 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ Supported models: Qwen3, Qwen3-Next, Qwen3.5/3.6, Qwen3.8-Flash-Next, Recursive GLM-5.3-Flash, Hy4-flash and Inkling 2 Mini. The architectures, the GGUF types and the notes for each model are in [docs/MODELS.md](docs/MODELS.md). -Version 1.3.0. +Version 1.3.1. ## Numbers From 473a8d6948115e8f5e8043b225ed7b22f54426c3 Mon Sep 17 00:00:00 2001 From: Vasyl-Trefilov Date: Tue, 24 Nov 2026 17:29:20 +0100 Subject: [PATCH 045/515] serve: a stream for Inkling 2, DeepSeek, GLM or Hy4 writes an SSE comment every 15 seconds while the text of a tool call is held back, as the Qwen stream does (it wrote nothing until the call was whole, so a long call, like a file the model writes through a tool, met the read timeout of the client: 300 seconds in undici); with Inkling 2 Mini IQ4_NL on the RTX 3060 and a call that writes an HTML file, the longest time with no byte goes from 39.5 to 15.0 seconds in a reply of 1500 tokens (#97) --- src/deepseek/chat.rs | 3 ++- src/glm/mod.rs | 3 ++- src/hy4/chat.rs | 3 ++- src/inkling2/chat.rs | 3 ++- src/serve.rs | 9 +++++++++ tests/serve.rs | 13 +++++++++++++ 6 files changed, 30 insertions(+), 4 deletions(-) diff --git a/src/deepseek/chat.rs b/src/deepseek/chat.rs index bb8afe10..5467e8bb 100644 --- a/src/deepseek/chat.rs +++ b/src/deepseek/chat.rs @@ -109,6 +109,7 @@ pub fn serve<'a>(g: &'a Gguf, tok: &'a Tokenizer, name: &'a str) -> anyhow::Resu let tools = q.tool_calls && !q.tools.is_empty(); let mut hold = crate::chat::Hold::new(tools, vec![]).tagged(Template::Ds.call_tag()); let (mut out, mut shown, mut done) = (vec![], 0, "length"); + let mut alive = std::time::Instant::now(); for i in 0..n { let next = logits.iter().enumerate().max_by(|a, b| a.1.partial_cmp(b.1).unwrap()).unwrap().0 as u32; if eos.contains(&next) { done = "stop"; break; } @@ -117,7 +118,7 @@ pub fn serve<'a>(g: &'a Gguf, tok: &'a Tokenizer, name: &'a str) -> anyhow::Resu if !s.ends_with('\u{FFFD}') && s.len() > shown && s.is_char_boundary(shown) { let t = hold.push(&s[shown..]); shown = s.len(); - if q.stream && !t.is_empty() && write!(c, "data: {}\n\n", chunk(json!({"content": t}), None)).is_err() { break; } + if q.stream && !(if t.is_empty() { crate::serve::held(c, &mut alive) } else { write!(c, "data: {}\n\n", chunk(json!({"content": t}), None)).is_ok() }) { break; } } if i + 1 < n { logits = m.step(next); } } diff --git a/src/glm/mod.rs b/src/glm/mod.rs index 8dc80d44..aebc5061 100644 --- a/src/glm/mod.rs +++ b/src/glm/mod.rs @@ -430,9 +430,10 @@ pub fn serve<'a>(g: &'a Gguf, tok: &'a crate::tokenizer::Tokenizer, name: &'a st let stream = q.stream; let tools = q.tool_calls && !q.tools.is_empty(); let mut hold = crate::chat::Hold::new(tools, vec![]); + let mut alive = std::time::Instant::now(); let (out, done) = decode_greedy(&mut m, &tok, &stop, logits, n, &mut |t| { let t = hold.push(t); - !stream || t.is_empty() || write!(c, "data: {}\n\n", chunk(json!({"content": t}), None)).is_ok() + !stream || if t.is_empty() { crate::serve::held(c, &mut alive) } else { write!(c, "data: {}\n\n", chunk(json!({"content": t}), None)).is_ok() } }); let calls = if tools { parse_calls(&hold.text, &q.tools) } else { None }; let done = if calls.is_some() { "tool_calls" } else { done }; diff --git a/src/hy4/chat.rs b/src/hy4/chat.rs index 6564ed40..2f81c2dc 100644 --- a/src/hy4/chat.rs +++ b/src/hy4/chat.rs @@ -196,9 +196,10 @@ pub fn serve<'a>(g: &'a Gguf, tok: &'a Tokenizer, name: &'a str) -> anyhow::Resu let chunk = |d: serde_json::Value, fin: Option<&str>| json!({"object": "chat.completion.chunk", "model": name, "choices": [{"index": 0, "delta": d, "finish_reason": fin}]}); let tools = q.tool_calls && !q.tools.is_empty(); let mut hold = crate::chat::Hold::new(tools, vec![]).tagged(CALLS); + let mut alive = std::time::Instant::now(); let (out, stopped) = decode(&mut m, &tok, logits, n, |p| { let t = hold.push(p); - !q.stream || t.is_empty() || write!(c, "data: {}\n\n", chunk(json!({"content": t}), None)).is_ok() + !q.stream || if t.is_empty() { crate::serve::held(c, &mut alive) } else { write!(c, "data: {}\n\n", chunk(json!({"content": t}), None)).is_ok() } }); let calls = if tools { parse_calls(&hold.text) } else { None }; let done = if calls.is_some() { "tool_calls" } else if stopped { "stop" } else { "length" }; diff --git a/src/inkling2/chat.rs b/src/inkling2/chat.rs index c51495d2..87661b05 100644 --- a/src/inkling2/chat.rs +++ b/src/inkling2/chat.rs @@ -558,12 +558,13 @@ pub fn serve<'a>(g: &'a Gguf, tok: &'a Tokenizer, name: &'a str, opts: Inkling2O let chunk = |d: serde_json::Value, fin: Option<&str>| json!({"object": "chat.completion.chunk", "model": name, "choices": [{"index": 0, "delta": d, "finish_reason": fin}]}); let tools = q.tool_calls && !q.tools.is_empty(); let (mut content, mut reasoning, mut bodies) = (String::new(), String::new(), Vec::::new()); + let mut alive = std::time::Instant::now(); let (count, stopped) = decode_with(&mut m, tok, logits, n, &mut smp, budget, &q.stop, |p, start, s| { let key = match p { Part::Call if tools => { if start { bodies.push(String::new()); } *bodies.last_mut().unwrap() += s; - return true; + return !q.stream || crate::serve::held(c, &mut alive); } Part::Think => { reasoning += s; "reasoning_content" } _ => { content += s; "content" } diff --git a/src/serve.rs b/src/serve.rs index 313330c9..c344ce2a 100644 --- a/src/serve.rs +++ b/src/serve.rs @@ -97,6 +97,15 @@ pub fn gone(c: &std::net::TcpStream) -> bool { match r { Ok(n) => n == 0, Err(e) => e.kind() != std::io::ErrorKind::WouldBlock } } +/// What a stream writes while its text is held back (the body of a tool call): an SSE comment when `last` is 15 s +/// old, so a client that gives up after some minutes without a byte (undici: 300 s) keeps reading. False when the +/// client is gone. +pub fn held(c: &mut impl std::io::Write, last: &mut std::time::Instant) -> bool { + if last.elapsed() < std::time::Duration::from_secs(15) { return true; } + *last = std::time::Instant::now(); + c.write_all(b": keep-alive\n\n").is_ok() +} + /// `Authorization` header check for `--api-key`, without an early exit on the first differing byte. /// The chat page of `serve`. pub const PAGE: &str = include_str!("web/index.html"); diff --git a/tests/serve.rs b/tests/serve.rs index f03fdaa9..fffcae8e 100644 --- a/tests/serve.rs +++ b/tests/serve.rs @@ -735,3 +735,16 @@ fn serve_auto_unload_loads_again_on_a_chat() { for r in [first, second] { assert!(r.contains("200 OK") && r.contains("\"choices\""), "--parallel {parallel}: {r}"); } } } + +/// A stream with held text writes an SSE comment once its last write is 15 s old, and nothing before that. +#[test] +fn held_stream_writes_a_comment_after_15_seconds() { + use rusting_strata::serve::held; + use std::time::{Duration, Instant}; + let (mut out, mut last) = (Vec::new(), Instant::now()); + assert!(held(&mut out, &mut last) && out.is_empty()); + last = Instant::now().checked_sub(Duration::from_secs(16)).expect("uptime under 16 s"); + assert!(held(&mut out, &mut last)); + assert_eq!(out, b": keep-alive\n\n"); + assert!(held(&mut out, &mut last) && out.len() == 14, "the comment restarts the 15 s"); +} From 4b3f44bf328c9ba8f4f3ea5c0897d6763010abaf Mon Sep 17 00:00:00 2001 From: Vasyl-Trefilov Date: Tue, 24 Nov 2026 17:42:07 +0100 Subject: [PATCH 046/515] serve: a streamed chat sends its response head before the prompt runs and the SSE comment ": keep-alive" every 15 s while the prompt runs (the head went out after the prompt, so a long prompt gave no byte for its whole prefill and a client with a time limit for the head gave up); this is in the loops of the main engine, Inkling 2, DeepSeek, GLM, Hy4 and Gemma 4, through serve::alive; a Gemma 4 prompt that fails after the head ends the stream with one error line; Inkling 2 Mini IQ4_NL on the RTX 3060, 14726-token prompt (prefill 91 s): the head comes after 0.01 s and the longest time with no byte is 15.0 s; docs/USAGE.md describes it (#97) --- docs/USAGE.md | 4 ++++ src/deepseek/chat.rs | 4 ++-- src/gemma4/mod.rs | 14 ++++++++++++-- src/glm/mod.rs | 4 ++-- src/hy4/chat.rs | 4 ++-- src/inkling2/chat.rs | 6 +++--- src/main.rs | 7 ++++--- src/serve.rs | 24 +++++++++++++++++++++++- tests/serve.rs | 20 ++++++++++++++++++++ 9 files changed, 72 insertions(+), 15 deletions(-) diff --git a/docs/USAGE.md b/docs/USAGE.md index 720faad3..32e0375e 100644 --- a/docs/USAGE.md +++ b/docs/USAGE.md @@ -177,6 +177,10 @@ other MCP clients use, and pass it with `--mcp ` (or `STRATA_MCP`; the def `model` that no listed file has is answered by the loaded model. If the load fails, the request gets `503` with the reason and the next chat request loads the model that was there before. With API keys only the admin key sees the other models and switches; a customer key sees and gets the loaded model. +- A streamed reply sends its response head when the model takes the request, before the prompt runs. While the prompt + runs, and while the text of a tool call is held back, the stream sends the SSE comment `: keep-alive` every 15 s, so + a client that stops after some minutes without a byte keeps reading. If the prompt fails after the head, the stream + ends early. - It runs one request at a time; `--parallel N` (GPU) decodes up to N together (4 requests: 164 tok/s in total on the RTX 3060, 41 each; see [HOSTING.md](HOSTING.md)). From 8 requests decoding at once (`STRATA_BATCH_MIN` sets the count), a dense model without MTP, LoRA or recurrent layers on CUDA runs them in one batched forward, and the diff --git a/src/deepseek/chat.rs b/src/deepseek/chat.rs index 5467e8bb..ba1ddac2 100644 --- a/src/deepseek/chat.rs +++ b/src/deepseek/chat.rs @@ -101,10 +101,10 @@ pub fn serve<'a>(g: &'a Gguf, tok: &'a Tokenizer, name: &'a str) -> anyhow::Resu anyhow::ensure!(ids.len() <= ctx, "prompt is {} tokens, the limit is {ctx}", ids.len()); let t = std::time::Instant::now(); let keep = if m.toks.len() < ids.len() && ids.starts_with(&m.toks) { m.toks.len() } else { m.reset(); 0 }; - let mut logits = m.prefill(&ids[keep..]); + if q.stream { let _ = write!(c, "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n"); } + let mut logits = crate::serve::alive(c, q.stream, || m.prefill(&ids[keep..])); let prefill_s = t.elapsed().as_secs_f64(); let n = q.max_tokens.unwrap_or(usize::MAX).min(ctx - ids.len()); - if q.stream { let _ = write!(c, "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n"); } let chunk = |d: serde_json::Value, fin: Option<&str>| json!({"object": "chat.completion.chunk", "model": name, "choices": [{"index": 0, "delta": d, "finish_reason": fin}]}); let tools = q.tool_calls && !q.tools.is_empty(); let mut hold = crate::chat::Hold::new(tools, vec![]).tagged(Template::Ds.call_tag()); diff --git a/src/gemma4/mod.rs b/src/gemma4/mod.rs index b77ed630..25b9bd7d 100644 --- a/src/gemma4/mod.rs +++ b/src/gemma4/mod.rs @@ -288,10 +288,20 @@ pub fn serve<'a>(g: &'a Gguf, tok: &'a crate::tokenizer::Tokenizer, name: &'a st let t = std::time::Instant::now(); let keep = if m.toks.len() < ids.len() && ids.starts_with(&m.toks) { m.toks.len() } else { m.reset(); 0 }; // A failed feed leaves part of the prompt in the cache, so the next request starts over. - let logits = match feed(&mut m, &seq[keep..]) { Ok(l) => l, Err(e) => { m.reset(); return Err(e) } }; + if q.stream { let _ = write!(c, "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n"); } + let logits = match crate::serve::alive(c, q.stream, || feed(&mut m, &seq[keep..])) { + Ok(l) => l, + Err(e) => { + m.reset(); + // The head of a stream is out, so the error is its last line (a response with a status cannot follow). + if !q.stream { return Err(e); } + eprintln!("request: {e:#}"); + let _ = write!(c, "data: {}\n\n", json!({"error": {"message": format!("{e:#}"), "type": "server_error"}})); + return Ok(crate::serve::Done { prompt: ids.len(), cached: keep, completion: 0, prefill_s: t.elapsed().as_secs_f64(), finish: "error" }); + } + }; let prefill_s = t.elapsed().as_secs_f64(); let n = q.max_tokens.unwrap_or(usize::MAX).min(ctx - ids.len()); - if q.stream { let _ = write!(c, "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n"); } let stream = q.stream; let chunk = |d: serde_json::Value, fin: Option<&str>| json!({"object": "chat.completion.chunk", "model": name, "choices": [{"index": 0, "delta": d, "finish_reason": fin}]}); let (out, done) = decode_greedy(&tok, &mut m, &stop, logits, n, &mut |t| { diff --git a/src/glm/mod.rs b/src/glm/mod.rs index aebc5061..b155351b 100644 --- a/src/glm/mod.rs +++ b/src/glm/mod.rs @@ -422,10 +422,10 @@ pub fn serve<'a>(g: &'a Gguf, tok: &'a crate::tokenizer::Tokenizer, name: &'a st anyhow::ensure!(ids.len() < ctx, "prompt is {} tokens, the limit is {}", ids.len(), ctx - 1); let t = std::time::Instant::now(); let keep = if m.toks.len() < ids.len() && ids.starts_with(&m.toks) { m.toks.len() } else { m.reset(); 0 }; - let logits = m.prefill(&ids[keep..]); + if q.stream { let _ = write!(c, "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n"); } + let logits = crate::serve::alive(c, q.stream, || m.prefill(&ids[keep..])); let prefill_s = t.elapsed().as_secs_f64(); let n = q.max_tokens.unwrap_or(usize::MAX).min(ctx - ids.len()); - if q.stream { let _ = write!(c, "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n"); } let chunk = |d: serde_json::Value, fin: Option<&str>| json!({"object": "chat.completion.chunk", "model": name, "choices": [{"index": 0, "delta": d, "finish_reason": fin}]}); let stream = q.stream; let tools = q.tool_calls && !q.tools.is_empty(); diff --git a/src/hy4/chat.rs b/src/hy4/chat.rs index 2f81c2dc..d1aa8070 100644 --- a/src/hy4/chat.rs +++ b/src/hy4/chat.rs @@ -189,10 +189,10 @@ pub fn serve<'a>(g: &'a Gguf, tok: &'a Tokenizer, name: &'a str) -> anyhow::Resu anyhow::ensure!(ids.len() < max_ctx, "prompt is {} tokens, the limit is {max_ctx}", ids.len()); let t = std::time::Instant::now(); let keep = if m.toks.len() < ids.len() && ids.starts_with(&m.toks) { m.toks.len() } else { m.reset(); 0 }; - let logits = m.prefill(&ids[keep..]); + if q.stream { let _ = write!(c, "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n"); } + let logits = crate::serve::alive(c, q.stream, || m.prefill(&ids[keep..])); let prefill_s = t.elapsed().as_secs_f64(); let n = q.max_tokens.unwrap_or(usize::MAX).min(max_ctx - ids.len()); - if q.stream { let _ = write!(c, "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n"); } let chunk = |d: serde_json::Value, fin: Option<&str>| json!({"object": "chat.completion.chunk", "model": name, "choices": [{"index": 0, "delta": d, "finish_reason": fin}]}); let tools = q.tool_calls && !q.tools.is_empty(); let mut hold = crate::chat::Hold::new(tools, vec![]).tagged(CALLS); diff --git a/src/inkling2/chat.rs b/src/inkling2/chat.rs index 87661b05..3d78ddde 100644 --- a/src/inkling2/chat.rs +++ b/src/inkling2/chat.rs @@ -525,7 +525,8 @@ pub fn serve<'a>(g: &'a Gguf, tok: &'a Tokenizer, name: &'a str, opts: Inkling2O ensure!(!ids.is_empty(), "cannot encode prompt"); ensure!(ids.len() < m.max_ctx, "prompt is {} tokens, the limit is {}", ids.len(), m.max_ctx); let t = std::time::Instant::now(); - let (keep, logits) = if !has_images && m.toks.len() < ids.len() && ids.starts_with(&m.toks) { + if q.stream { let _ = write!(c, "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n"); } + let (keep, logits) = crate::serve::alive(c, q.stream, || if !has_images && m.toks.len() < ids.len() && ids.starts_with(&m.toks) { let k = m.toks.len(); (k, m.prefill_embds(&seq[k..])) } else if !has_images && let Some((ck, ck_logits)) = &turn_ckpt && ck.toks.len() <= ids.len() && ids.starts_with(&ck.toks) { @@ -535,7 +536,7 @@ pub fn serve<'a>(g: &'a Gguf, tok: &'a Tokenizer, name: &'a str, opts: Inkling2O } else { m.reset(); (0, m.prefill_embds(&seq)) - }; + }); turn_ckpt = (!has_images).then(|| (m.checkpoint(), logits.clone())); let prefill_s = t.elapsed().as_secs_f64(); @@ -554,7 +555,6 @@ pub fn serve<'a>(g: &'a Gguf, tok: &'a Tokenizer, name: &'a str, opts: Inkling2O let budget = q.thinking_budget.unwrap_or(opts.thinking_budget); let n = q.max_tokens.unwrap_or(usize::MAX).min(m.max_ctx - m.toks.len()); - if q.stream { let _ = write!(c, "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n"); } let chunk = |d: serde_json::Value, fin: Option<&str>| json!({"object": "chat.completion.chunk", "model": name, "choices": [{"index": 0, "delta": d, "finish_reason": fin}]}); let tools = q.tool_calls && !q.tools.is_empty(); let (mut content, mut reasoning, mut bodies) = (String::new(), String::new(), Vec::::new()); diff --git a/src/main.rs b/src/main.rs index 00314b51..4c20e0a2 100644 --- a/src/main.rs +++ b/src/main.rs @@ -3247,17 +3247,18 @@ fn handle(mut w: TcpStream, q: anyhow::Result, l: Option<&mut Lo let res = (|| -> anyhow::Result<(Vec, bool)> { let logits; if serve::gone(&w) { anyhow::bail!("client closed the connection"); } - let (chat_ids, chat_logits, chat_cached) = match &vision_prompt { + // The head goes out before the prompt runs, and comments follow it while the prompt runs (`serve::alive`). + if req.stream { write!(w, "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nCache-Control: no-cache\r\nConnection: close\r\n\r\n")?; } + let (chat_ids, chat_logits, chat_cached) = serve::alive(&w, req.stream, || anyhow::Ok(match &vision_prompt { Some(p) => (p.ids.clone(), r.chat_image(p, &image_input.as_ref().unwrap().embeddings)?, 0), None => r.chat(tok, &prompt, &tpl.render(&req.messages[..n_hist], &req.tools, req.think.unwrap_or(e.think_default), preserve, false), &system)?, - }; + }))?; (_, logits, cached) = (chat_ids, chat_logits, chat_cached); if let Runner::Slot(c) = &*r && let Some(t) = c.started { t0 = t; start(&mut busy); } prefilled = true; t1 = Instant::now(); if serve::gone(&w) { anyhow::bail!("client closed the connection"); } if req.stream { - write!(w, "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nCache-Control: no-cache\r\nConnection: close\r\n\r\n")?; if anth { sse(&mut w, json!({"type": "message_start", "message": {"id": format!("msg_{i}"), "type": "message", "role": "assistant", "model": name, "content": [], "stop_reason": null, "stop_sequence": null, diff --git a/src/serve.rs b/src/serve.rs index c344ce2a..e72706b9 100644 --- a/src/serve.rs +++ b/src/serve.rs @@ -97,11 +97,33 @@ pub fn gone(c: &std::net::TcpStream) -> bool { match r { Ok(n) => n == 0, Err(e) => e.kind() != std::io::ErrorKind::WouldBlock } } +/// The longest time a stream sends nothing. +const KEEP: std::time::Duration = std::time::Duration::from_secs(15); + +/// Runs `f`, the prefill of a request. For a stream, whose response head is written before the call, an SSE comment +/// goes out every 15 s until `f` returns, so a client that waits a limited time for the next byte keeps waiting +/// through a long prompt (`f` must not write to `c`). +pub fn alive(c: &std::net::TcpStream, stream: bool, f: impl FnOnce() -> T) -> T { alive_every(c, stream.then_some(KEEP), f) } + +/// `alive` with the time between two comments (`None`: no stream, nothing is written). +pub fn alive_every(c: &std::net::TcpStream, every: Option, f: impl FnOnce() -> T) -> T { + use std::io::Write; + let Some(every) = every else { return f() }; + let (tx, rx) = std::sync::mpsc::channel::<()>(); + std::thread::scope(|s| { + // The end of `f` drops `tx`, which ends the wait at once. + s.spawn(move || { let mut c = c; while rx.recv_timeout(every) == Err(std::sync::mpsc::RecvTimeoutError::Timeout) && c.write_all(b": keep-alive\n\n").is_ok() {} }); + let r = f(); + drop(tx); + r + }) +} + /// What a stream writes while its text is held back (the body of a tool call): an SSE comment when `last` is 15 s /// old, so a client that gives up after some minutes without a byte (undici: 300 s) keeps reading. False when the /// client is gone. pub fn held(c: &mut impl std::io::Write, last: &mut std::time::Instant) -> bool { - if last.elapsed() < std::time::Duration::from_secs(15) { return true; } + if last.elapsed() < KEEP { return true; } *last = std::time::Instant::now(); c.write_all(b": keep-alive\n\n").is_ok() } diff --git a/tests/serve.rs b/tests/serve.rs index fffcae8e..c0ffed3b 100644 --- a/tests/serve.rs +++ b/tests/serve.rs @@ -748,3 +748,23 @@ fn held_stream_writes_a_comment_after_15_seconds() { assert_eq!(out, b": keep-alive\n\n"); assert!(held(&mut out, &mut last) && out.len() == 14, "the comment restarts the 15 s"); } + +/// A stream whose prompt is still running gets an SSE comment at each interval and nothing after the prompt ends; +/// a request that is not a stream gets nothing. +#[test] +fn a_running_prompt_keeps_the_stream_alive() { + use rusting_strata::serve::alive_every; + use std::io::Read; + use std::time::Duration; + let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let mut peer = std::net::TcpStream::connect(l.local_addr().unwrap()).unwrap(); + let (c, _) = l.accept().unwrap(); + let work = || { std::thread::sleep(Duration::from_millis(330)); 7 }; + assert_eq!(alive_every(&c, None, work), 7); + assert_eq!(alive_every(&c, Some(Duration::from_millis(100)), work), 7); + std::thread::sleep(Duration::from_millis(250)); + drop(c); + let mut got = String::new(); + peer.read_to_string(&mut got).unwrap(); + assert_eq!(got, ": keep-alive\n\n".repeat(3)); +} From 631975c8e5606d14e3b153b8a9b6c546d9115dab Mon Sep 17 00:00:00 2001 From: Hannes Klas Date: Tue, 24 Nov 2026 18:38:54 +0100 Subject: [PATCH 047/515] hip: remove the unused fields, methods and constants --- src/hip/ffi.rs | 17 ----------------- src/hip/mod.rs | 27 ++++++--------------------- 2 files changed, 6 insertions(+), 38 deletions(-) diff --git a/src/hip/ffi.rs b/src/hip/ffi.rs index 076fc186..3166768a 100644 --- a/src/hip/ffi.rs +++ b/src/hip/ffi.rs @@ -31,9 +31,6 @@ pub const ATTR_MAX_DYNAMIC_SHARED: c_int = 8; pub const ATTR_SHARED_PER_BLOCK_OPTIN: c_int = 75; pub const ATTR_SHARED_PER_BLOCK: c_int = 74; pub const ATTR_WARP_SIZE: c_int = 87; -pub const ATTR_INTEGRATED: c_int = 16; -pub const ATTR_MULTIPROCESSOR_COUNT: c_int = 63; -pub const ATTR_MAX_THREADS_PER_BLOCK: c_int = 56; /// Room for `hipDeviceProp_t`, which `hipGetDeviceProperties` writes whole. ROCm 7's `hipDeviceProp_tR0600` is 1472 /// bytes; the size is not exported and changes between versions, so the buffer leaves ample room for a larger one. @@ -53,8 +50,6 @@ fn find_gfx(bytes: &[u8]) -> Option { None } -type Fn = unsafe extern "C" fn(); - /// Library names to try, in order. `STRATA_HIP` (a path or a name) replaces the whole list. fn candidates(vars: Option, default_suffix: &[&str]) -> Vec { if let Some(p) = vars { return vec![p]; } @@ -76,14 +71,11 @@ pub struct Hip { pub mem_get_info: unsafe extern "C" fn(*mut usize, *mut usize) -> c_int, pub malloc: unsafe extern "C" fn(*mut *mut c_void, usize) -> c_int, pub free: unsafe extern "C" fn(*mut c_void) -> c_int, - pub memset: unsafe extern "C" fn(*mut c_void, c_int, usize) -> c_int, pub memset_async: unsafe extern "C" fn(*mut c_void, c_int, usize, Stream) -> c_int, pub memcpy: unsafe extern "C" fn(*mut c_void, *const c_void, usize, c_int) -> c_int, pub memcpy_async: unsafe extern "C" fn(*mut c_void, *const c_void, usize, c_int, Stream) -> c_int, pub stream_create: unsafe extern "C" fn(*mut Stream, u32) -> c_int, - pub stream_destroy: unsafe extern "C" fn(Stream) -> c_int, pub stream_sync: unsafe extern "C" fn(Stream) -> c_int, - pub stream_wait_event: unsafe extern "C" fn(Stream, Event, u32) -> c_int, pub stream_begin_capture: unsafe extern "C" fn(Stream, c_int) -> c_int, pub stream_end_capture: unsafe extern "C" fn(Stream, *mut Graph) -> c_int, pub stream_is_capturing: unsafe extern "C" fn(Stream, *mut c_int) -> c_int, @@ -94,18 +86,15 @@ pub struct Hip { pub event_create: unsafe extern "C" fn(*mut Event, u32) -> c_int, pub event_record: unsafe extern "C" fn(Event, Stream) -> c_int, pub event_sync: unsafe extern "C" fn(Event) -> c_int, - pub event_query: unsafe extern "C" fn(Event) -> c_int, pub event_destroy: unsafe extern "C" fn(Event) -> c_int, pub host_malloc: unsafe extern "C" fn(*mut *mut c_void, usize, u32) -> c_int, pub host_free: unsafe extern "C" fn(*mut c_void) -> c_int, pub host_device_ptr: unsafe extern "C" fn(*mut *mut c_void, *mut c_void, u32) -> c_int, pub module_load: unsafe extern "C" fn(*mut Module, *const c_void) -> c_int, - pub module_unload: unsafe extern "C" fn(Module) -> c_int, pub function: unsafe extern "C" fn(*mut Func, Module, *const c_char) -> c_int, pub launch: unsafe extern "C" fn(Func, u32, u32, u32, u32, u32, u32, u32, Stream, *mut *mut c_void, *mut *mut c_void) -> c_int, pub func_set_attribute: unsafe extern "C" fn(*const c_void, c_int, c_int) -> c_int, pub error_string: unsafe extern "C" fn(c_int) -> *const c_char, - pub last_error: unsafe extern "C" fn() -> c_int, _lib: Library, } @@ -142,14 +131,11 @@ impl Hip { mem_get_info: g!("hipMemGetInfo"), malloc: g!("hipMalloc"), free: g!("hipFree"), - memset: g!("hipMemset"), memset_async: g!("hipMemsetAsync"), memcpy: g!("hipMemcpy"), memcpy_async: g!("hipMemcpyAsync"), stream_create: g!("hipStreamCreateWithFlags"), - stream_destroy: g!("hipStreamDestroy"), stream_sync: g!("hipStreamSynchronize"), - stream_wait_event: g!("hipStreamWaitEvent"), stream_begin_capture: g!("hipStreamBeginCapture"), stream_end_capture: g!("hipStreamEndCapture"), stream_is_capturing: g!("hipStreamIsCapturing"), @@ -160,18 +146,15 @@ impl Hip { event_create: g!("hipEventCreateWithFlags"), event_record: g!("hipEventRecord"), event_sync: g!("hipEventSynchronize"), - event_query: g!("hipEventQuery"), event_destroy: g!("hipEventDestroy"), host_malloc: g!("hipHostMalloc"), host_free: g!("hipHostFree"), host_device_ptr: g!("hipHostGetDevicePointer"), module_load: g!("hipModuleLoadData"), - module_unload: g!("hipModuleUnload"), function: g!("hipModuleGetFunction"), launch: g!("hipModuleLaunchKernel"), func_set_attribute: g!("hipFuncSetAttribute"), error_string: g!("hipGetErrorString"), - last_error: g!("hipGetLastError"), _lib: lib, }) } diff --git a/src/hip/mod.rs b/src/hip/mod.rs index 235e99d0..fa0c04e2 100644 --- a/src/hip/mod.rs +++ b/src/hip/mod.rs @@ -35,7 +35,6 @@ pub struct Gpu { hip: Arc, device: usize, stream: ffi::Stream, - module: ffi::Module, fns: HashMap, /// "gfx1201": the target hiprtc compiled for. arch: String, @@ -45,13 +44,8 @@ pub struct Gpu { max_smem: usize, /// `argmax_rows` partials. am: Buf, - /// q8 rows of the last integer GEMM's X (see quant_q8 in kernels.cu) and which x they hold; `None` after a call - /// without `SAME_X` that did not quantize. - q8: Mutex<(Buf, Option<[u64; 4]>)>, /// Recorded graphs by `Backend::graph` key. graphs: Mutex>, - /// Recorded by `sync`, so a wait can poll it instead of spinning in the driver. - done: ffi::Event, /// Rope frequency tables, `base` and `n_rot` to the device buffer that holds them. fr: Mutex<(HashMap<(u32, usize), Buf>, Vec<(f32, usize)>)>, /// Pinned staging for large `htod`, used as a ring: the copy returns before its DMA, so the host fills the next @@ -208,21 +202,16 @@ impl Gpu { } // argmax_part writes an int2 (8 bytes) per partial: AMAX_PARTS per row, up to 64 rows. let am_buf = alloc_raw(&hip, 64 * AMAX_PARTS * 8)?; - let q8_buf = alloc_raw(&hip, 1)?; // Pinned ring for large host-to-device copies. let mut host: *mut c_void = std::ptr::null_mut(); hip.check(unsafe { (hip.host_malloc)(&mut host, RING, ffi::HOST_MALLOC_PORTABLE | ffi::HOST_MALLOC_MAPPED) }, "hipHostMalloc(ring)")?; let mut dev: *mut c_void = std::ptr::null_mut(); hip.check(unsafe { (hip.host_device_ptr)(&mut dev, host, 0) }, "hipHostGetDevicePointer(ring)")?; - let staging = Staging { pin: Buf::new(dev as u64, RING, PinnedHost { hip: hip.clone(), p: host }), host: host.cast(), head: 0, busy: VecDeque::new() }; - let mut done: ffi::Event = std::ptr::null_mut(); - hip.check(unsafe { (hip.event_create)(&mut done, ffi::EVENT_DISABLE_TIMING) }, "hipEventCreate")?; - Ok(Gpu { hip, device, stream, module, fns, arch, kv_q8, max_smem, am: am_buf, q8: Mutex::new((q8_buf, None)), - graphs: Mutex::new(HashMap::new()), done, fr: Mutex::new((HashMap::new(), Vec::new())), staging: Mutex::new(staging) }) + let staging = Staging { _pin: Buf::new(dev as u64, RING, PinnedHost { hip: hip.clone(), p: host }), host: host.cast(), head: 0, busy: VecDeque::new() }; + Ok(Gpu { hip, device, stream, fns, arch, kv_q8, max_smem, am: am_buf, + graphs: Mutex::new(HashMap::new()), fr: Mutex::new((HashMap::new(), Vec::new())), staging: Mutex::new(staging) }) } - fn h(&self) -> &ffi::Hip { &self.hip } - pub fn arch(&self) -> &str { &self.arch } /// Launch kernel `name` with `cfg`; `args` are the kernel parameters, in order, read from the given addresses. @@ -249,10 +238,6 @@ impl Gpu { fn ptr(&self, b: &Buf) -> u64 { b.addr() } - fn f(&self, name: &str) -> anyhow::Result { - self.fns.get(name).copied().ok_or_else(|| anyhow::anyhow!("HIP kernel {name} is not loaded")) - } - /// qwen35moe and the other models this backend targets dequantize in the kernel, so the ops below are the /// generic ones. fn float_ty(ty: GgmlType) -> bool { matches!(ty, GgmlType::F32 | GgmlType::BF16) } @@ -405,13 +390,14 @@ impl Drop for PinnedHost { /// Pinned host memory used as a ring for `htod`: a region is free again once the copy that read it has completed. struct Staging { - pin: Buf, + /// Owns the pinned allocation; dropping it frees the ring. + _pin: Buf, host: *mut u8, head: usize, busy: VecDeque<(usize, usize, Event)>, } -/// A `hipEvent_t` that destroys itself; `query` reports completion. +/// A `hipEvent_t` that destroys itself. struct Event { hip: Arc, ev: ffi::Event } impl Event { @@ -423,7 +409,6 @@ impl Event { fn record(&self, stream: ffi::Stream) -> anyhow::Result<()> { self.hip.check(unsafe { (self.hip.event_record)(self.ev, stream) }, "hipEventRecord") } - fn done(&self) -> bool { unsafe { (self.hip.event_query)(self.ev) == ffi::HIP_SUCCESS } } } impl Drop for Event { From 9aa6463591b8aa88da840d5274f20750968667e2 Mon Sep 17 00:00:00 2001 From: sayampy Date: Tue, 24 Nov 2026 04:12:48 +0530 Subject: [PATCH 048/515] calibrate: budgeted search via bench, chunk/MTP/short against current defaults --- src/calibrate.rs | 463 +++++++++++++++++++ src/gemma4/mod.rs | 2 +- src/lib.rs | 1 + src/main.rs | 1125 +++++++++++++++++++++++++++++++++++++-------- 4 files changed, 1407 insertions(+), 184 deletions(-) create mode 100644 src/calibrate.rs diff --git a/src/calibrate.rs b/src/calibrate.rs new file mode 100644 index 00000000..2cc53f2b --- /dev/null +++ b/src/calibrate.rs @@ -0,0 +1,463 @@ +//! Universal calibration search. +//! +//! This module is the model- and backend-agnostic half of `rustingstrata calibrate`. It knows nothing about GGUFs, +//! GPUs or tokenizers: the caller supplies a `measure` closure that, given a set of knobs and a workload matrix, +//! returns throughput numbers. That makes the same search usable with every engine the binary supports. +//! +//! The search is deliberately small-budget and noise-aware: +//! * a deterministic low-discrepancy coarse sweep over the joint knob space, +//! * multi-start coordinate descent from the best coarse points (escapes the local minima of a single greedy walk), +//! * a final joint polish, +//! * a hard sample budget with early stopping, +//! * a baseline measured with the settings a user gets today, not the first point of the search space. + +use anyhow::Result; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; +use std::time::Instant; + +/// A point in the knob space. Values are numeric: integer knobs are rounded by the caller when they are applied. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct Knobs(pub BTreeMap); + +impl Knobs { + pub fn get(&self, name: &str) -> Option { self.0.get(name).copied() } + pub fn i(&self, name: &str) -> Option { self.get(name).map(|v| v.round().max(0.0) as usize) } + pub fn set(&mut self, name: &str, value: f64) { self.0.insert(name.to_string(), value); } + /// A short, stable label used in progress lines and in the JSON report. + pub fn label(&self) -> String { + self.0.iter().map(|(k, v)| format!("{k}={}", if v.fract() == 0.0 { format!("{v:.0}") } else { format!("{v:.2}") })) + .collect::>().join(" ") + } +} + +/// One discrete knob. `reload` marks knobs whose change needs a fresh model load; the measurement closure can use it +/// to avoid reloading on cheap changes. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct KnobSpec { + pub name: String, + pub values: Vec, + #[serde(default)] + pub reload: bool, +} + +impl KnobSpec { + pub fn new(name: &str, values: impl IntoIterator, reload: bool) -> Self { + Self { name: name.into(), values: values.into_iter().collect(), reload } + } +} + +/// A prompt/decode pair to benchmark. `task` is a label the measurement closure interprets ("prose", "coding", +/// "user:PATH"); it is passed through so the report records which corpus produced the numbers. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Workload { + pub pp: usize, + pub tg: usize, + pub task: String, +} + +impl Workload { + pub fn new(pp: usize, tg: usize, task: &str) -> Self { Self { pp, tg, task: task.into() } } + pub fn label(&self) -> String { format!("{}pp/{}tg/{}", self.pp, self.tg, self.task) } +} + +/// Throughput of one workload measurement. Higher is better. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct Measurement { + pub prefill_tok_s: f64, + pub decode_tok_s: f64, + #[serde(default)] + pub drafts_offered: usize, + #[serde(default)] + pub drafts_accepted: usize, +} + +impl Measurement { + fn valid(&self) -> bool { + [self.prefill_tok_s, self.decode_tok_s].iter().all(|v| v.is_finite() && *v > 0.0) + } +} + +/// Relative importance of prefill throughput and decode throughput. Each is divided by its own baseline, so the +/// units cancel. A weighted geometric mean (rather than an arithmetic one) cannot hide a regression in one signal +/// behind a large gain in the other. Time to first token is deliberately not a separate signal: for greedy decoding +/// it is the prefill time, so giving it a weight would just reweight prefill. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Objective { + pub prefill: f64, + pub decode: f64, +} + +impl Objective { + /// Balanced default: prompt handling and reply generation count equally. + pub fn balanced() -> Self { Self { prefill: 0.5, decode: 0.5 } } + fn normalized(&self) -> Self { + let sum = self.prefill + self.decode; + if sum <= 0.0 || !sum.is_finite() { return Self::balanced(); } + Self { prefill: self.prefill / sum, decode: self.decode / sum } + } + /// Score of one measurement relative to its baseline. + pub fn score(&self, m: &Measurement, base: &Measurement) -> f64 { + let clamp = |v: f64| v.clamp(1e-3, 1e3); + let pf = clamp(m.prefill_tok_s / base.prefill_tok_s); + let dec = clamp(m.decode_tok_s / base.decode_tok_s); + let o = self.normalized(); + pf.powf(o.prefill) * dec.powf(o.decode) + } +} + +/// Score of a full workload matrix: geometric mean over workloads, so each prompt depth counts equally. Every depth +/// is compared with its own baseline, so the ratio means what it says at every prompt length. +pub fn aggregate_score(ms: &[Measurement], bases: &[Measurement], obj: &Objective) -> f64 { + let fallback = bases.first().cloned().unwrap_or_default(); + let mut acc = 0.0; + let mut n = 0; + for (i, m) in ms.iter().enumerate() { + if !m.valid() { continue; } + let base = bases.get(i).unwrap_or(&fallback); + acc += obj.score(m, base).ln(); + n += 1; + } + if n == 0 { 0.0 } else { (acc / n as f64).exp() } +} + +/// One evaluated candidate. `error` is set (and `score` is zero) when a measurement failed, e.g. an OOM at a large +/// chunk: failed points stay in the trace so the report explains why a region of the space was skipped. +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct Trial { + pub knobs: Knobs, + pub measurements: Vec, + pub score: f64, + #[serde(skip_serializing_if = "Option::is_none")] + pub error: Option, + pub elapsed_ms: u128, + /// How many workloads were measured. Coarse trials use the first workload only; they must not be compared with + /// full-matrix scores, nor can they win the search. + pub workloads: usize, +} + +/// Budget and stopping settings. +#[derive(Clone, Debug)] +pub struct SearchConfig { + /// Hard cap on measurement closure calls. Reaching it always stops the search. + pub samples: usize, + /// Number of coarse low-discrepancy points (capped at a third of the budget). + pub coarse: usize, + /// Multi-start count for coordinate descent. + pub starts: usize, + /// Stop after this many full refinement rounds without an improvement. + pub patience: usize, + /// Deterministic seed (also used for the low-discrepancy sequence). + pub seed: u64, +} + +impl Default for SearchConfig { + fn default() -> Self { Self { samples: 24, coarse: 8, starts: 3, patience: 2, seed: 1 } } +} + +/// Result of a search, including the full trace for the JSON report. +#[derive(Debug, Serialize, Deserialize)] +pub struct SearchResult { + pub best: Trial, + pub baseline: Vec, + pub trials: Vec, + pub samples_used: usize, + pub stop_reason: String, + pub elapsed_ms: u128, + pub seed: u64, +} + +/// Radical inverse in a prime base: a deterministic, well-spread point set in `[0,1)^dims`. No dependencies, same +/// points on every run for a given seed, so a calibration can be reproduced from its recorded seed. +pub fn low_discrepancy(index: usize, dims: usize, seed: u64) -> Vec { + const PRIMES: [u64; 12] = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]; + (0..dims).map(|d| { + let base = PRIMES.get(d).copied().unwrap_or(37); + let mut n = index as u64 + seed.wrapping_mul(base); + let mut f = 1.0 / base as f64; + let mut out = 0.0; + while n > 0 { + out += f * (n % base) as f64; + n /= base; + f /= base as f64; + } + out + }).collect() +} + +/// Map a unit point to knob values by nearest candidate (a small jitter-free quantization of the unit cube). +fn quantize(space: &[KnobSpec], unit: &[f64]) -> Knobs { + let mut k = Knobs::default(); + for (spec, u) in space.iter().zip(unit) { + let i = (u.clamp(0.0, 0.999999) * spec.values.len() as f64) as usize; + k.set(&spec.name, spec.values[i.min(spec.values.len() - 1)]); + } + k +} + +fn default_knobs(space: &[KnobSpec]) -> Knobs { + let mut k = Knobs::default(); + for s in space { if let Some(v) = s.values.first() { k.set(&s.name, *v); } } + k +} + +/// Run the search. `measure` is called once per sample with the workload matrix; it should apply the knobs, take its +/// own repetitions and return one measurement per workload. `baseline` has one measurement per workload, taken with +/// the settings a user gets without a calibration file. +pub fn search(space: &[KnobSpec], workloads: &[Workload], cfg: &SearchConfig, obj: &Objective, + baseline: Vec, mut measure: F) -> Result +where F: FnMut(&Knobs, &[Workload]) -> Result> +{ + anyhow::ensure!(!space.is_empty() && !workloads.is_empty(), "calibration needs a knob space and at least one workload"); + let fallback = baseline.iter().find(|m| m.valid()).cloned().unwrap_or_else(|| Measurement { prefill_tok_s: 1.0, decode_tok_s: 1.0, ..Default::default() }); + let mut baselines = baseline.clone(); + while baselines.len() < workloads.len() { baselines.push(fallback.clone()); } + let start = Instant::now(); + let mut trials: Vec = Vec::new(); + let mut used = 0usize; + + let mut evaluate = |knobs: &Knobs, subset: &[Workload]| -> Result { + let t0 = Instant::now(); + let (measurements, error) = match measure(knobs, subset) { + Ok(ms) if ms.iter().any(|m| m.valid()) => (ms, None), + Ok(ms) => (ms, Some("no valid measurement (all rates were zero or non-finite)".to_string())), + Err(e) => (vec![], Some(format!("{e:#}"))), + }; + let score = if error.is_some() { 0.0 } else { aggregate_score(&measurements, &baselines, obj) }; + Ok(Trial { knobs: knobs.clone(), measurements, score, error, elapsed_ms: t0.elapsed().as_millis(), workloads: subset.len() }) + }; + + // One bench child per distinct (knob point, workload set): repeats cost a full model load and consume budget + // without adding information. `seen` is shared by every stage, including all starts. + let mut seen: std::collections::HashSet<(String, usize)> = std::collections::HashSet::new(); + let mut eval_unique = |knobs: &Knobs, subset: &[Workload]| -> Result> { + if !seen.insert((knobs.label(), subset.len())) { return Ok(None); } + evaluate(knobs, subset).map(Some) + }; + + // Stage A: coarse joint sweep, on the cheapest (first) workload. These scores are only used to pick starting + // points for Stage B; they are never compared with full-matrix scores or allowed to win. + let coarse = cfg.coarse.min(cfg.samples / 3).min(16).max(1); + for i in 0..coarse { + let k = quantize(space, &low_discrepancy(i, space.len(), cfg.seed)); + if let Some(trial) = eval_unique(&k, &workloads[..1])? { + used += 1; + trials.push(trial); + } + if used >= cfg.samples { break } + } + + // Stage B: multi-start coordinate descent on the full matrix. + let mut seeds: Vec<(Knobs, f64)> = trials.iter().filter(|t| t.error.is_none()) + .map(|t| (t.knobs.clone(), t.score)).collect(); + seeds.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal)); + seeds.dedup_by(|a, b| a.0 == b.0); + seeds.truncate(cfg.starts.max(1)); + if seeds.is_empty() { seeds.push((default_knobs(space), 0.0)); } + + let mut converged_all = true; + for (cur, _seed_score) in seeds.into_iter() { + let mut stop_reason = "budget".to_string(); + // Re-measure the seed on the full matrix before comparing it with full-matrix candidates. Otherwise a point + // that only wins on the shortest prompt would start with an inflated score and reject real improvements. + let mut cur_trial = if used >= cfg.samples { break } else if let Some(t) = eval_unique(&cur, workloads)? { + used += 1; + trials.push(t.clone()); + t + } else { + trials.iter().find(|t| t.workloads == workloads.len() && t.knobs == cur).cloned() + .unwrap_or_else(|| Trial { knobs: cur.clone(), measurements: vec![], score: 0.0, error: None, + elapsed_ms: 0, workloads: workloads.len() }) + }; + let mut stale = 0; + for _ in 0..cfg.patience.max(1) + 2 { + let mut improved = false; + for s in space { + let original = cur_trial.knobs.get(&s.name); + let mut local_best = cur_trial.clone(); + for &v in &s.values { + if Some(v) == original || used >= cfg.samples { continue } + let mut candidate = cur_trial.knobs.clone(); + candidate.set(&s.name, v); + if let Some(t) = eval_unique(&candidate, workloads)? { + used += 1; + trials.push(t.clone()); + if t.error.is_none() && t.score > local_best.score { local_best = t; } + } + if used >= cfg.samples { break; } + } + match local_best.error.clone() { + None if local_best.score > cur_trial.score => { cur_trial = local_best; improved = true; } + _ => {} + } + if used >= cfg.samples { break; } + } + if !improved { stale += 1; if stale >= cfg.patience.max(1) { stop_reason = "converged".into(); } } + else { stale = 0; } + if used >= cfg.samples || stop_reason == "converged" { break; } + } + if used >= cfg.samples { converged_all = false; break; } + if stop_reason != "converged" { converged_all = false; } + } + + // Stage C: one coordinate pass from the overall winner over the cheap knobs. + let best_so_far = trials.iter().filter(|t| t.error.is_none() && t.workloads == workloads.len()) + .max_by(|a, b| a.score.partial_cmp(&b.score).unwrap_or(std::cmp::Ordering::Equal)).cloned(); + let mut best = best_so_far.unwrap_or_else(|| Trial { + knobs: default_knobs(space), measurements: vec![], score: 0.0, + error: Some("no successful full-matrix measurement".into()), elapsed_ms: 0, workloads: 0, + }); + if used < cfg.samples { + for s in space.iter().filter(|s| !s.reload) { + let original = best.knobs.get(&s.name); + for &v in &s.values { + if Some(v) == original || used >= cfg.samples { continue } + let mut candidate = best.knobs.clone(); + candidate.set(&s.name, v); + if let Some(t) = eval_unique(&candidate, workloads)? { + used += 1; + trials.push(t.clone()); + if t.error.is_none() && t.score > best.score { best = t; } + } + } + } + } + let stop_reason = if used >= cfg.samples || !converged_all { "budget" } else { "converged" }.to_string(); + Ok(SearchResult { + best, baseline, trials, samples_used: used, stop_reason, + elapsed_ms: start.elapsed().as_millis(), seed: cfg.seed, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn space() -> Vec { + vec![KnobSpec::new("chunk", [256.0, 1024.0, 4096.0], false), + KnobSpec::new("mtp", [0.0, 1.0, 2.0], false)] + } + fn workloads() -> Vec { vec![Workload::new(128, 16, "prose"), Workload::new(512, 16, "prose")] } + fn base() -> Measurement { Measurement { prefill_tok_s: 100.0, decode_tok_s: 20.0, ..Default::default() } } + + #[test] + fn objective_is_a_geometric_mean_of_two_signals() { + let o = Objective::balanced(); + assert!((o.score(&base(), &base()) - 1.0).abs() < 1e-9); + let better = Measurement { prefill_tok_s: 200.0, decode_tok_s: 10.0, ..Default::default() }; + assert!((o.score(&better, &base()) - 1.0).abs() < 1e-9, "2x prefill and 0.5x decode cancel"); + let gain = Measurement { prefill_tok_s: 200.0, decode_tok_s: 40.0, ..Default::default() }; + assert!((o.score(&gain, &base()) - 2.0).abs() < 1e-9); + let mixed = Measurement { prefill_tok_s: 1000.0, decode_tok_s: 1.0, ..Default::default() }; + assert!(o.score(&mixed, &base()) < 1.0, "a big regression must not be hidden by one gain"); + } + + #[test] + fn low_discrepancy_is_deterministic_and_spread() { + assert_eq!(low_discrepancy(7, 3, 42), low_discrepancy(7, 3, 42)); + let pts: Vec<_> = (0..16).map(|i| low_discrepancy(i, 2, 1)).collect(); + let xs: std::collections::BTreeSet<_> = pts.iter().map(|p| format!("{:.2}", p[0])).collect(); + assert!(xs.len() >= 8, "coarse points should cover the first dimension: {xs:?}"); + } + + #[test] + fn search_respects_the_sample_budget_and_finds_the_best_region() { + let mut calls = 0; + let cfg = SearchConfig { samples: 12, coarse: 4, starts: 2, patience: 1, seed: 5 }; + let r = search(&space(), &workloads(), &cfg, &Objective::balanced(), vec![base(), base()], |k, _| { + calls += 1; + let boost = if k.i("chunk") == Some(1024) { 2.0 } else { 1.0 } * if k.i("mtp") == Some(1) { 1.5 } else { 1.0 }; + Ok(vec![Measurement { prefill_tok_s: 100.0 * boost, decode_tok_s: 20.0 * boost, ..Default::default() }]) + }).unwrap(); + assert!(calls <= cfg.samples, "used {calls} above budget {}", cfg.samples); + assert_eq!(r.samples_used, calls); + assert_eq!(r.best.knobs.i("chunk"), Some(1024)); + assert_eq!(r.best.knobs.i("mtp"), Some(1)); + assert!(r.best.score > 1.0); + } + + #[test] + fn every_start_gets_a_full_descent_not_one_round() { + // A flat landscape never converges: each of the three starts must run several full rounds. With the old + // stop_reason leak, starts 2 and 3 got a single round after start 1 converged. + // A bigger space gives each start real room to move: scores improve with both knob values, so no start + // converges immediately. (Measured points are memoized, so call-count-based landscapes are not useful.) + let big: Vec = vec![ + KnobSpec::new("chunk", (1..=8).map(|i| i as f64 * 100.0), false), + KnobSpec::new("mtp", (0..8).map(|i| i as f64), false), + ]; + let cfg = SearchConfig { samples: 40, coarse: 3, starts: 3, patience: 2, seed: 9 }; + let r = search(&big, &workloads(), &cfg, &Objective::balanced(), vec![base(), base()], |k, _| { + let boost = 1.0 + k.i("chunk").unwrap() as f64 / 1000.0 + k.i("mtp").unwrap() as f64 / 100.0; + Ok(vec![Measurement { prefill_tok_s: 100.0 * boost, decode_tok_s: 20.0 * boost, ..Default::default() }]) + }).unwrap(); + assert!(r.samples_used > 25, "each start should get several rounds, not one: {}", r.samples_used); + } + + #[test] + fn short_prompt_only_gains_cannot_win_the_search() { + let cfg = SearchConfig { samples: 14, coarse: 6, starts: 3, patience: 1, seed: 3 }; + let r = search(&space(), &workloads(), &cfg, &Objective::balanced(), vec![base(), base()], |k, subset| { + let mtp = k.i("mtp").unwrap(); + Ok(subset.iter().map(|w| { + let boost = if mtp == 1 { if w.pp == 128 { 2.0 } else { 0.25 } } else { 1.0 }; + Measurement { prefill_tok_s: 100.0 * boost, decode_tok_s: 20.0 * boost, ..Default::default() } + }).collect()) + }).unwrap(); + assert_ne!(r.best.knobs.i("mtp"), Some(1), "the short-prompt-only gain must not win"); + assert_eq!(r.best.measurements.len(), 2); + } + + #[test] + fn failed_measurements_are_recorded_and_never_win() { + let cfg = SearchConfig { samples: 8, coarse: 4, starts: 1, patience: 1, seed: 2 }; + let r = search(&space(), &workloads(), &cfg, &Objective::balanced(), vec![base(), base()], |k, _| { + if k.i("mtp") == Some(1) { anyhow::bail!("out of memory") } + Ok(vec![base(), base()]) + }).unwrap(); + assert_ne!(r.best.knobs.i("mtp"), Some(1)); + assert!(r.trials.iter().any(|t| t.error.as_deref().is_some_and(|e| e.contains("out of memory")))); + } + + #[test] + fn an_empty_baseline_still_allows_the_search_to_run() { + let cfg = SearchConfig { samples: 10, coarse: 3, starts: 1, patience: 1, seed: 6 }; + let r = search(&space(), &workloads(), &cfg, &Objective::balanced(), vec![], |_, _| { + Ok(vec![Measurement { prefill_tok_s: 100.0, decode_tok_s: 20.0, ..Default::default() }]) + }).unwrap(); + assert!(r.best.error.is_none()); + assert!(r.samples_used > 0); + } + + #[test] + fn the_same_knob_point_is_never_measured_twice() { + let cfg = SearchConfig { samples: 60, coarse: 6, starts: 3, patience: 2, seed: 7 }; + let r = search(&space(), &workloads(), &cfg, &Objective::balanced(), vec![base(), base()], |k, _| { + let boost = 1.0 + k.i("chunk").unwrap() as f64 / 10000.0 + k.i("mtp").unwrap() as f64 / 10.0; + Ok(vec![Measurement { prefill_tok_s: 100.0 * boost, decode_tok_s: 20.0 * boost, ..Default::default() }]) + }).unwrap(); + let keys: std::collections::HashSet<_> = r.trials.iter() + .map(|t| (t.knobs.label(), t.workloads)).collect(); + assert_eq!(keys.len(), r.trials.len(), "a repeated sample never adds information"); + assert!(r.trials.len() > cfg.coarse, "the search should still do real refinement"); + } + + #[test] + fn every_start_converging_is_recorded_as_converged() { + // A flat landscape: no move ever improves, so all starts stop on patience before the budget is used. + let cfg = SearchConfig { samples: 60, coarse: 3, starts: 2, patience: 2, seed: 4 }; + let r = search(&space(), &workloads(), &cfg, &Objective::balanced(), vec![base(), base()], |_, _| { + Ok(vec![base(), base()]) + }).unwrap(); + assert!(r.samples_used < cfg.samples, "should stop early: {}", r.samples_used); + assert_eq!(r.stop_reason, "converged"); + } + + #[test] + fn aggregate_score_ignores_invalid_workloads() { + let bad = Measurement::default(); + let bases = [base(), base()]; + assert!((aggregate_score(&[base(), bad.clone()], &bases, &Objective::balanced()) - 1.0).abs() < 1e-9); + assert_eq!(aggregate_score(&[bad], &bases, &Objective::balanced()), 0.0); + } +} diff --git a/src/gemma4/mod.rs b/src/gemma4/mod.rs index 25b9bd7d..d3a7458e 100644 --- a/src/gemma4/mod.rs +++ b/src/gemma4/mod.rs @@ -101,7 +101,7 @@ fn strip_thinking(text: &str) -> String { /// GPU on, the weights in 90% of the free VRAM (a fixed 11 GB overcommitted a 12 GB card that other programs /// use, and left a larger card half empty). -fn gpu_defaults() { +pub fn gpu_defaults() { if std::env::var_os("STRATA_G4_CPU").is_some() { return; } for (k, v) in [("STRATA_DS_GPU", "1"), ("STRATA_DS_GPU_FRACTION", "0.9"), ("STRATA_DS_NOEVICT", "1")] { if std::env::var_os(k).is_none() { unsafe { std::env::set_var(k, v) } } diff --git a/src/lib.rs b/src/lib.rs index 2af3bcb9..e654b992 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,5 +1,6 @@ pub mod memory; pub mod term; +pub mod calibrate; /// `--ctx` when it was given on the command line, else 0. The models outside the main engine (Inkling 2, Hy4, GLM, /// DeepSeek, Gemma 4) read it through [`ctx_limit`]. diff --git a/src/main.rs b/src/main.rs index 4c20e0a2..95937bbb 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,6 +1,10 @@ use clap::{Args, Parser, Subcommand}; use anyhow::Context; use rusting_strata::memory; +use rusting_strata::calibrate::{self, KnobSpec, Knobs, Measurement, Objective, SearchConfig, Workload}; +use std::cell::RefCell; +use std::process::{Command, Stdio}; +use std::sync::atomic::AtomicUsize; use rusting_strata::{say, term}; use rusting_strata::model::{Model, State}; use rusting_strata::{backend, gpu_model::GpuModel}; @@ -361,6 +365,28 @@ impl Engine { if self.kv != "f16" && std::env::var_os("STRATA_KV").is_none() { set_kv_env(&self.kv); } } + /// Models on their own code path never call `Engine::runner`, the only place that reads a calibration file. + /// Apply the measured chunk through the environment those engines actually read. Context and threads are not + /// searched (they are memory choices), so this never touches the global CTX: doing that once made an explicit + /// --ctx look implicit to the main engine's runner. + fn own_calib(&self, model: &Path) { + let Ok(g) = Gguf::open(model) else { return }; + let arch = g.get("general.architecture").ok().and_then(|v| v.as_str()).unwrap_or(""); + if !rusting_strata::config::OWN_ARCHS.contains(&arch) { return; } + let path = calibration_path(model, self.backend.as_deref().unwrap_or("cuda"), &self.device); + let (Ok(bytes), Some(&d)) = (std::fs::read(&path), self.device.first()) else { return }; + let Ok(v) = serde_json::from_slice::(&bytes) else { return }; + let gpu = backend::open(self.backend.as_deref(), d).ok().map(|b| b.device().to_string()).unwrap_or_default(); + if !calibration_fits(&v, &gpu) { return; } + if v["bytes"].as_u64().is_some_and(|n| std::fs::metadata(model).is_ok_and(|m| m.len() != n)) { return; } + // GLM reads its own variable, Gemma 4 its own, the others read STRATA_DS_CHUNK. Explicit values win. + if let Some(n) = v["chunk"].as_u64() { + for (k, value) in chunk_env_updates(n as usize, |k| std::env::var_os(k).is_some()) { + unsafe { std::env::set_var(k, value); } + } + } + } + /// Fills settings not given on the command line from the model's calibration file, else built-in defaults. fn ram_cap(&self) -> Option { memory::ram_cap((self.ram_margin as u64) << 20, (self.max_ram as u64) << 20) } /// A copy with the load options of an `/api/load` body applied (`ctx`, `kv`, `cache_ram`, `vram_margin`, `mtp`, @@ -410,7 +436,7 @@ impl Engine { v = serde_json::Value::Null; } if !v.is_null() { say!("calibration: {}", path.display()); } - else if bk.is_some() { say!("warning: not calibrated on this machine, so the prefill chunk, MTP drafts and the short-prompt threshold are defaults: run `rustingstrata calibrate --model {}` (a few minutes, once per model)", model.display()); } + else if bk.is_some() { say!("warning: not calibrated on this machine, so the prefill chunk, MTP drafts and the short-prompt threshold are defaults: run `rustingstrata calibrate --model {}` (once per model; `--samples` bounds the run)", model.display()); } let get = |k: &str| v[k].as_u64().map(|x| x as usize); if let Some(dp) = &self.draft_model { anyhow::ensure!(dp.exists(), "draft model path does not exist: {}", dp.display()); @@ -720,28 +746,22 @@ fn calibrated_split(v: &serde_json::Value, devices: &[usize], gpus: &[String]) - (l.len() == devices.len()).then_some(l) } -/// The splits one move away from `cur` (layers per device): `step` layers moved between two neighbouring devices, -/// each device keeping at least one layer. -fn split_moves(cur: &[usize], step: usize) -> Vec> { - let mut v = vec![]; - for i in 0..cur.len().saturating_sub(1) { - for (a, b) in [(i, i + 1), (i + 1, i)] { - if cur[a] > step { - let mut c = cur.to_vec(); - (c[a], c[b]) = (c[a] - step, c[b] + step); - v.push(c); - } - } - } - v -} - /// Whether calibration file `v` may be used on `gpu` (`Backend::device`). A file names the GPU it was measured on; /// one without a name (written before that was recorded, or the driver gave none) is accepted. fn calibration_fits(v: &serde_json::Value, gpu: &str) -> bool { v["gpu"].as_str().is_none_or(|g| g.is_empty() || gpu.is_empty() || g == gpu) } +/// Values a calibrated chunk may write to the environment. An explicit value set by the user must win, so the +/// caller skips names that are already present. +fn chunk_env_updates(n: usize, present: impl Fn(&str) -> bool) -> Vec<(&'static str, String)> { + if !(1..=(1 << 20)).contains(&n) { return vec![]; } + ["STRATA_DS_CHUNK", "STRATA_GLM_CHUNK", "STRATA_G4_CHUNK"].into_iter() + .filter(|k| !present(k)) + .map(|k| (k, n.to_string())) + .collect() +} + impl Engine { pub fn lora_specs(&self) -> Vec<(String, f32)> { self.lora.iter().map(|s| { @@ -845,6 +865,7 @@ fn bench_record(meta: &BenchMeta, results: &[BenchResult], expert: Option<&Exper "pp": r.pp, "prefill_tok_s": {"mean": r.prefill.mean, "min": r.prefill.min, "max": r.prefill.max}, "decode_tok_s": {"mean": r.decode.mean, "min": r.decode.min, "max": r.decode.max}, + }); if r.bytes_per_token > 0 { o["expert"] = json!({ @@ -945,13 +966,13 @@ enum Cmd { #[command(flatten)] engine: Engine, }, - /// Measure prefill chunk, MTP drafts per step and the short-prompt threshold on this machine (GPU) and write - /// them to the model's calibration file, which later runs read unless flags override. + /// Benchmark a budgeted search over prefill chunk, MTP drafts and the short-prompt threshold on this machine, + /// and write the best point to the model's calibration file, which later runs read unless flags override. Calibrate { /// The GGUF to calibrate, or a folder: every model in it (and its subfolders, as the chat page lists them) - /// is calibrated in turn. + /// is calibrated in turn. With the `spec` subcommand this may be omitted in favour of its own --model. #[arg(long)] - model: PathBuf, + model: Option, /// GPU context length used while measuring and assumed for the results. #[arg(long, default_value_t = 4096)] ctx: usize, @@ -983,6 +1004,44 @@ enum Cmd { /// calibrate the drafts with it. #[arg(long)] draft_model: Option, + + /// Hard cap on benchmark samples: the search stops when this many have been taken, or earlier when it has + /// converged. One sample benchmarks the whole workload matrix (all --pp lengths of one task). + #[arg(long, default_value_t = 24)] + samples: usize, + /// Benchmark repetitions inside each sample; their mean is used and run-to-run spread is reported. + #[arg(long, default_value_t = 3)] + reps: usize, + /// Extra discarded run before each sample (off by default: it loads the model a second time). + #[arg(long, default_value_t = 0)] + warmup: usize, + /// Prompt depths of the workload matrix, comma-separated. + #[arg(long, value_delimiter = ',', default_value = "128,512,2048")] + pp: Vec, + /// Tokens greedily decoded per workload. + #[arg(long, default_value_t = 128)] + tg: usize, + /// Prefill chunk sizes to search, comma-separated. [default: 256,512,1024,2048,4096] + #[arg(long, value_delimiter = ',')] + chunk_values: Option>, + /// Extra task corpus: `user:PATH` (a prompt file), `coding` or `prose`. Repeatable. + #[arg(long)] + task: Vec, + /// Deterministic seed for the low-discrepancy coarse sweep and the search. + #[arg(long, default_value_t = 1)] + seed: u64, + /// Print the derived knob space, workload matrix and sample plan, then exit without benchmarking. + #[arg(long)] + dry_run: bool, + /// Per-sample time limit in seconds (0 = no limit). A timeout is recorded as a failed sample. + #[arg(long, default_value_t = 0)] + timeout: u64, + /// Keep the full benchmark report and sample trace in this directory. + #[arg(long)] + out: Option, + /// Sweep spec-type and draft settings for different tasks instead of tuning the engine knobs. + #[command(subcommand)] + sub: Option, }, /// Check that every Vulkan pipeline this model needs fits the device's `maxComputeSharedMemorySize`, naming the /// kernel, specialization, bytes needed and limit when one does not; exits non-zero on overflow. No model is @@ -1061,6 +1120,60 @@ enum Cmd { }, } +/// `rustingstrata calibrate spec …`: sweep speculative-decoding settings per task. +#[derive(Subcommand, Clone, Debug)] +enum CalibrateSub { + /// Measure every combination of spec type, draft count and n-gram size on each task corpus, and store the best + /// per task in the calibration file. Inkling 2 uses these with (or instead of) a DSpark draft; the main engine + /// combines them with its MTP head. + Spec { + /// The model to sweep (a folder is not accepted: the sweep writes one calibration file). + #[arg(long)] + model: PathBuf, + /// Tasks: `prose`, `coding`, `user:PATH` (a prompt file). Repeatable. + #[arg(long, value_delimiter = ',', default_value = "prose,coding")] + tasks: Vec, + /// Spec types: none, suffix, ngram-simple, ngram-map-k, ngram-map-k4v, ngram-mod, ngram-cache. + #[arg(long, value_delimiter = ',', default_value = "none,ngram-simple,ngram-mod,ngram-cache")] + spec_types: Vec, + /// Maximum drafts verified per step. + #[arg(long, value_delimiter = ',', default_value = "4,8,16")] + draft_max: Vec, + /// N-gram lookup key lengths. + #[arg(long, value_delimiter = ',', default_value = "3,6,12")] + ngram_n: Vec, + /// MTP draft counts to combine with the lookup (main engine only). + #[arg(long, value_delimiter = ',', default_value = "0,2")] + mtp: Vec, + #[arg(long)] + draft_model: Option, + #[arg(long)] + backend: Option, + #[arg(long, value_delimiter = ',', default_value = "0")] + device: Vec, + #[arg(long, default_value_t = 4096)] + ctx: usize, + #[arg(long, default_value = "512")] + vram_margin: Vec, + #[arg(long, value_parser = ["f16", "q8", "q4", "q2"], default_value = "f16")] + kv: String, + #[arg(long, default_value_t = 512)] + pp: usize, + #[arg(long, default_value_t = 128)] + tg: usize, + #[arg(long, default_value_t = 3)] + reps: usize, + #[arg(long, default_value_t = 24)] + samples: usize, + #[arg(long, default_value_t = 1)] + seed: u64, + #[arg(long)] + out: Option, + #[arg(long)] + dry_run: bool, + }, +} + fn main() { if let Err(e) = start() { say!("error: {e:#}"); @@ -1144,6 +1257,7 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { println!("{}", serde_json::json!({"argmax": argmax, "top5": top5})); } Cmd::Generate { model, prompt, n, image, mut engine } => { + engine.own_calib(&model); engine.ds_env(); let g = Gguf::open(&model)?; engine.own_warn(&g); @@ -1276,12 +1390,14 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { engine.own_warn(&g); engine.ctx = engine.ctx.max(pp.iter().max().unwrap_or(&0) + tg); if let Some(arch) = g.get("general.architecture").ok().and_then(|v| v.as_str()) { - if arch == "deepseek41" || arch == "glm5-next" || arch == rusting_strata::hy4::ARCH || rusting_strata::inkling2::is_arch(arch) { + if arch == "deepseek41" || arch == "glm5-next" || arch == "gemma4" || arch == rusting_strata::hy4::ARCH || rusting_strata::inkling2::is_arch(arch) { engine.ds_env(); // A --ctx below the test grows to fit it, as on the main engine. if rusting_strata::CTX.load(std::sync::atomic::Ordering::Relaxed) != 0 { rusting_strata::CTX.store(engine.ctx, std::sync::atomic::Ordering::Relaxed); } return if arch == "deepseek41" { bench_deepseek(&g, &model, &pp, tg, reps, json_out, &mut engine) + } else if arch == "gemma4" { + bench_gemma4(&g, &model, &pp, tg, reps, json_out, &mut engine) } else if arch == rusting_strata::hy4::ARCH { bench_hy4(&g, &model, &pp, tg, reps, json_out, &mut engine) } else if rusting_strata::inkling2::is_arch(arch) { @@ -1346,38 +1462,48 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { std::fs::write(&path, line).with_context(|| format!("writing the JSON record to {}", path.display()))?; } } - Cmd::Calibrate { model, ctx, vram_margin, backend, device, split, kv, lora, gpu: _, mtp_model, draft_model } => { + Cmd::Calibrate { model, ctx, vram_margin, backend, device, split, kv, lora, gpu: _, mtp_model, draft_model, + samples, reps, warmup, pp, tg, chunk_values, task, seed, + dry_run, timeout, out, sub } => { set_kv_env(&kv); // read by Gpu::new and Vk::new if !lora.is_empty() { say!("note: --lora is ignored by calibrate; calibration uses the base model"); } - let margins = vram_margins(&vram_margin, &device)?.into_iter().map(|mb| mb << 20).collect::>(); - let split = split_arg(split.as_deref(), device.len())?; - // The architecture of a file that runs on its own code path, where nothing reads a calibration file. - let own_arch = |p: &std::path::Path| { - let arch = Gguf::open(p).ok()?.get("general.architecture").ok()?.as_str()?.to_string(); - rusting_strata::config::OWN_ARCHS.contains(&arch.as_str()).then_some(arch) - }; - if !model.is_dir() { - if let Some(arch) = own_arch(&model) { - say!("nothing to calibrate: '{arch}' models run on their own code path, which reads no calibration file. Run chat, generate, bench or serve with this model as it is."); - return Ok(()); - } - return calibrate(&model, draft_model.as_deref().or(mtp_model.as_deref()), ctx, &margins, backend.as_deref(), &device, split); + if split.is_some() { say!("note: --split is ignored by calibrate; measurements use the free-VRAM split"); } + + if let Some(CalibrateSub::Spec { model, tasks, spec_types, draft_max, ngram_n, mtp, draft_model, backend, + device, ctx, vram_margin, kv, pp, tg, reps, samples, seed, out, dry_run }) = sub { + let mut s = CalibSettings::new(model); + s.backend = backend; s.device = device; s.vram_margin = vram_margin; s.kv = kv; + s.ctx = ctx; s.tasks = tasks; s.spec_types = spec_types; s.draft_max = draft_max; s.ngram_n = ngram_n; + s.mtp_values = mtp; s.pp = vec![pp]; s.tg = tg; s.reps = reps; s.samples = samples; + s.seed = seed; s.out = out; s.dry_run = dry_run; + s.aux = draft_model.map(|p| ("--draft-model", p)); + ensure_spec_defaults(&mut s); + return calibrate_spec(&s); } - anyhow::ensure!(draft_model.is_none() && mtp_model.is_none(), "--mtp-model and --draft-model belong to one model: give --model a file"); + + let Some(model) = model else { anyhow::bail!("--model PATH is required (or use `calibrate spec --model PATH`)") }; + let mut settings = CalibSettings::new(model.clone()); + settings.backend = backend; + settings.device = device; + settings.vram_margin = vram_margin; + settings.kv = kv; + settings.chunk_values = chunk_values.unwrap_or_else(|| vec![256, 512, 1024, 2048, 4096]); + settings.ctx = ctx; + settings.aux = draft_model.map(|p| ("--draft-model", p)).or_else(|| mtp_model.map(|p| ("--mtp-model", p))); + settings.samples = samples; settings.reps = reps; settings.warmup = warmup; settings.pp = pp; + settings.tg = tg; settings.tasks = task; + settings.seed = seed; settings.dry_run = dry_run; settings.timeout = timeout; settings.out = out; + if settings.pp.is_empty() || settings.pp.iter().any(|&n| n == 0) { anyhow::bail!("--pp needs at least one positive prompt depth"); } + if settings.samples == 0 { anyhow::bail!("--samples must be positive"); } + if !model.is_dir() { return calibrate_v2(&settings); } let list = rusting_strata::serve::list_models(&model); anyhow::ensure!(!list.is_empty(), "no .gguf models in {}", model.display()); + anyhow::ensure!(settings.aux.is_none(), "--mtp-model and --draft-model belong to one model: give --model a file"); let mut failed = vec![]; for (k, (id, path, _)) in list.iter().enumerate() { say!("calibrate {}/{}: {id}", k + 1, list.len()); - if let Some(arch) = own_arch(path) { - say!("calibrate {id}: skipped, calibrate measures the main engine only and '{arch}' models run on their own code path"); - continue; - } - // One model that fails (too big, not a model) does not stop the others. - if let Err(e) = calibrate(path, None, ctx, &margins, backend.as_deref(), &device, split.clone()) { - say!("calibrate {id}: failed: {e:#}"); - failed.push(id.as_str()); - } + settings.model = path.clone(); + if let Err(e) = calibrate_v2(&settings) { say!("calibrate {id}: failed: {e:#}"); failed.push(id.as_str()); } } anyhow::ensure!(failed.is_empty(), "calibration failed for {}", failed.join(", ")); } @@ -1443,6 +1569,7 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { } Cmd::Chat { model, system, n, image, mut engine } => { let think = engine.think_default; + engine.own_calib(&model); engine.ds_env(); let g = Gguf::open(&model)?; engine.own_warn(&g); @@ -1968,6 +2095,54 @@ fn $name(g: &Gguf, model: &Path, pp: &[usize], tg: usize, reps: usize, json_out: } bench_tokenwise!(bench_hy4, rusting_strata::hy4::forward::Hy4Model); +/// `strata bench` for Gemma 4. Its `gpu_defaults` is private to the module, so mirror the three variables its +/// generate/chat paths set; the timing loop is otherwise the shared token-by-token one. +fn bench_gemma4(g: &Gguf, model: &Path, pp: &[usize], tg: usize, reps: usize, json_out: Option, engine: &mut Engine) -> anyhow::Result<()> { + // Use the engine's own defaults so the bench measures the same configuration as chat and generate. + rusting_strata::gemma4::gpu_defaults(); + let tok = Tokenizer::from_gguf(g)?; + let mut m = rusting_strata::gemma4::forward::Gemma4Model::new(g)?; + let eos = tok.eos_ids(); + let mut results = Vec::with_capacity(pp.len()); + for &n in pp { + let ids = prose(&tok, n)?; + let (mut p, mut d) = (Vec::new(), Vec::new()); + for _ in 0..reps { + m.reset(); + let t = Instant::now(); + let logits = m.prefill(&ids); + p.push(n as f64 / t.elapsed().as_secs_f64()); + let t = Instant::now(); + let k = decode_greedy_big(&mut |t| m.step(t), logits, &eos, tg); + d.push(k as f64 / t.elapsed().as_secs_f64()); + } + let (prefill, decode_stat) = (Stat::of(&p), Stat::of(&d)); + println!("pp {n:6}: prefill {} tok/s | tg {tg}: decode {} tok/s", prefill.text(), decode_stat.text()); + results.push(BenchResult { pp: n, prefill, decode: decode_stat, bytes_per_token: 0, decode_median: 0.0 }); + } + let expert = big_expert_stats(m.cfg.n_layer, m.cfg.n_expert); + let backend = rusting_strata::deepseek::mat::dev_info().map_or("cpu", |i| i.0); + let meta = BenchMeta { + backend, + backend_arg: engine.backend.as_deref(), + device: if backend == "cpu" { &[] } else { &engine.device }, + model, + ctx: engine.ctx, + // The chunk bench_sample applied through STRATA_G4_CHUNK, not the old token-at-a-time placeholder. + chunk: gemma_bench_chunk(std::env::var("STRATA_G4_CHUNK").ok().as_deref()), + kv: &engine.kv, + mtp: 0, + tg, + reps, + }; + write_bench_json(json_out, &meta, &results, expert.as_ref()) +} + +/// The Gemma 4 prefill chunk used by this process; 256 is the engine's default. +fn gemma_bench_chunk(v: Option<&str>) -> usize { + v.and_then(|s| s.parse().ok()).unwrap_or(256) +} + /// `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(); @@ -2076,145 +2251,525 @@ fn bench_glm(g: &Gguf, model: &Path, pp: &[usize], tg: usize, reps: usize, json_ write_bench_json(json_out, &meta, &results, expert.as_ref()) } -/// Best (lowest) of three timings of `f`, in seconds. -fn best(f: &mut dyn FnMut() -> anyhow::Result<()>) -> anyhow::Result { - let mut b = f64::INFINITY; - for _ in 0..3 { - let t = Instant::now(); - f()?; - b = b.min(t.elapsed().as_secs_f64()); +/// Settings shared by the v2 calibration workflow and its `spec` subcommand. +#[derive(Clone, Debug)] +struct CalibSettings { + model: PathBuf, + backend: Option, + device: Vec, + vram_margin: Vec, + kv: String, + /// (flag, path): an MTP head or a draft model used for every measurement. + aux: Option<(&'static str, PathBuf)>, + ctx: usize, + samples: usize, + reps: usize, + warmup: usize, + pp: Vec, + tg: usize, + chunk_values: Vec, + tasks: Vec, + seed: u64, + dry_run: bool, + timeout: u64, + out: Option, + /// Only used by the `spec` subcommand. + spec_types: Vec, + draft_max: Vec, + ngram_n: Vec, + mtp_values: Vec, +} + +impl CalibSettings { + fn new(model: PathBuf) -> Self { + Self { + model, backend: None, device: vec![0], vram_margin: vec!["512".into()], kv: "f16".into(), + aux: None, ctx: 4096, samples: 24, reps: 3, warmup: 0, pp: vec![128, 512, 2048], tg: 128, + chunk_values: vec![256, 512, 1024, 2048, 4096], tasks: vec!["prose".into()], + seed: 1, dry_run: false, timeout: 0, out: None, + spec_types: vec![], draft_max: vec![], ngram_n: vec![], mtp_values: vec![], + } } - Ok(b) } -/// With `aux` (`--mtp-model`/`--draft-model`) the drafts are measured with that file, and runs given the same file use -/// the measured draft count. -fn calibrate(model: &Path, aux: Option<&Path>, ctx: usize, margin: &[usize], kind: Option<&str>, device: &[usize], mut split: Option>) -> anyhow::Result<()> { - backend::check_devices(kind, device)?; // before the GGUF is read: a bad --device fails here, not after the load - let g = Gguf::open(model)?; - let aux_g = open_mtp_gguf(aux)?; - let m = Model::load_with_aux(&g, aux_g.as_ref(), &[])?; - // Most drafts per step to measure: a DFlash block, else as many as the runs default to. - let kload = m.cfg.dflash.as_ref().map_or(if m.draft_model.is_some() { 4 } else { 3 }, |d| d.block_size.saturating_sub(1).max(1)); - let tok = Tokenizer::from_gguf(&g)?; - let n_pf = 4096.min(ctx.saturating_sub(256)); - anyhow::ensure!(n_pf >= 512, "--ctx too small to calibrate"); - let pf = prose(&tok, n_pf)?; - let load = |chunk: usize, split: Option<&[f64]>| -> anyhow::Result { - let bk = backend::open_all(kind, device)?; - let mut gm = GpuModel::load_split_margins(&m, bk, ctx, chunk, margin, split, kload, 1).context(LOAD_HINT)?; - gm.adapt_every = 0; // fixed placement: steadier timings - Ok(gm) - }; +fn calib_work_dir() -> anyhow::Result { + let d = rusting_strata::expert_cache::cache_dir().join("calibrate"); + std::fs::create_dir_all(&d)?; + Ok(d) +} - let mut chunk = (0, 0.0); - for c in [512, 1024, 2048, 4096].into_iter().filter(|&c| c <= ctx) { - // A larger chunk's prefill scratch may not fit beside a long --ctx: keep the chunks measured so far. - let mut gm = match load(c, split.as_deref()) { Ok(gm) => gm, Err(e) if chunk.0 > 0 => { say!("chunk {c:5}: {e:#}"); break } Err(e) => return Err(e) }; - let t = best(&mut || { gm.reset()?; gm.prefill(&pf).map(drop) })?; - let tps = n_pf as f64 / t; - say!("chunk {c:5}: prefill {n_pf} tok {tps:.0} tok/s"); - if tps > chunk.1 { chunk = (c, tps); } - } - - let dec = tok.encode("Write a long story about a dragon.")?; - // Several devices and no split given by hand: measure other layer splits and keep the fastest. The split by free - // VRAM does not know a card's speed or its PCIe link; the timings do. A card with fewer layers keeps more of - // their experts in VRAM (fewer uploads over its link in prefill), and the other cards then keep fewer. - if device.len() > 1 && split.is_none() { - // Prefill of the long prompt and decode after the short one, in tok/s, with the layers per device. - let measure = |s: Option<&[f64]>| -> anyhow::Result<(Vec, f64, f64)> { - let mut gm = load(chunk.0, s)?; - gm.k = 1; - let layers = gm.part_layers(); - let mut r = Runner::Gpu(Box::new(gm)); - let tp = best(&mut || { r.reset()?; r.prefill(&pf).map(drop) })?; - let mut toks = 0; - let td = best(&mut || { - r.reset()?; - let l = r.prefill(&dec)?; - toks = decode(&mut r, &tok, false, &mut Sampler::greedy(), l, 64, None, &mut |_| Ok(false))?.0.len(); - Ok(()) - })?; - Ok((layers, n_pf as f64 / tp, toks as f64 / td)) - }; - let (base, mut bp, mut bd) = measure(None)?; - say!("split {base:?} (by free VRAM): prefill {bp:.0} tok/s, decode {bd:.1} tok/s"); - // ponytail: a fixed step of 15% of the layers and three rounds; a finer search if a report shows the best - // split lies between two steps. - let step = (m.cfg.n_layer * 3 / 20).max(1); - let (mut cur, mut seen) = (base.clone(), vec![base.clone()]); - for _ in 0..3 { - let mut better = None; - for c in split_moves(&cur, step) { - if seen.contains(&c) { continue; } - seen.push(c.clone()); - match measure(Some(&c.iter().map(|&x| x as f64).collect::>())) { - Ok((_, p, d)) => { - say!("split {c:?}: prefill {p:.0} tok/s, decode {d:.1} tok/s, prefill x decode {:.3} of the best so far", p * d / (bp * bd)); - // Prefill and decode count the same; 3% over the best so far, above the run-to-run spread. - if p * d > 1.03 * bp * bd { (bp, bd, better) = (p, d, Some(c)); } - } - Err(e) => say!("split {c:?}: {e:#}"), +static CALIB_SEQ: AtomicUsize = AtomicUsize::new(0); + +/// A short, fixed coding corpus for the built-in `coding` task. The prose paragraph routes few experts; real code +/// repeats punctuation and identifiers, which changes both n-gram acceptance and the prefill cost. +const CALIB_CODE: &str = r#"fn parse_config(path: &str) -> Result { + let text = std::fs::read_to_string(path)?; + let mut config = Config::default(); + for (line_no, line) in text.lines().enumerate() { + let line = line.trim(); + if line.is_empty() || line.starts_with('#') { continue; } + let mut parts = line.splitn(2, '='); + let key = parts.next().unwrap().trim(); + let value = parts.next().ok_or(Error::Syntax(line_no))?.trim(); + match key { + "threads" => config.threads = value.parse()?, + "chunk" => config.chunk = value.parse()?, + "kv" => config.kv = value.to_string(), + _ => return Err(Error::UnknownKey(line_no)), + } + } + Ok(config) +} +"#; + +/// Resolve a task label to a prompt file. `None` means the built-in prose (no `--prompt-file`). +fn calib_prompt(task: &str, dir: &Path) -> anyhow::Result> { + match task { + "prose" => Ok(None), + "coding" => { + let p = dir.join("task-coding.txt"); + std::fs::write(&p, CALIB_CODE)?; + Ok(Some(p)) + } + t if t.starts_with("user:") => { + let p = PathBuf::from(&t[5..]); + anyhow::ensure!(p.is_file(), "task prompt file {} does not exist", p.display()); + Ok(Some(p)) + } + other => anyhow::bail!("unknown task {other:?} (expected prose, coding or user:PATH)"), + } +} + +struct BenchSample { + measurements: Vec, + backend: String, +} + +struct CappedOutput { + success: bool, + stdout: String, + stderr: String, +} + +/// Run a child with a time limit. Output goes to files rather than pipes: polling a piped child without draining +/// it can deadlock once the pipe fills, and a bench failure prints a stack trace and a usage block. +fn run_capped(mut c: Command, secs: u64, dir: &Path, id: usize) -> anyhow::Result { + let out = dir.join(format!("calib-{id}-out.txt")); + let err = dir.join(format!("calib-{id}-err.txt")); + c.stdout(Stdio::from(std::fs::File::create(&out)?)).stderr(Stdio::from(std::fs::File::create(&err)?)); + let mut child = c.spawn()?; + if secs > 0 { + let deadline = Instant::now() + Duration::from_secs(secs); + loop { + if child.try_wait()?.is_some() { break; } + if Instant::now() >= deadline { + let _ = child.kill(); + let _ = child.wait(); // reap the child before returning the error + let _ = std::fs::remove_file(&out); + let _ = std::fs::remove_file(&err); + anyhow::bail!("sample timed out after {secs}s"); + } + std::thread::sleep(Duration::from_millis(100)); + } + } + let status = child.wait()?; + let stdout = std::fs::read_to_string(&out).unwrap_or_default(); + let stderr = std::fs::read_to_string(&err).unwrap_or_default(); + let _ = std::fs::remove_file(&out); + let _ = std::fs::remove_file(&err); + Ok(CappedOutput { success: status.success(), stdout, stderr }) +} + +/// Draft counts are in the main engine's bench JSON; the arch-specific benchners print them. Accept both. +fn parse_drafts(v: &serde_json::Value, stdout: &str) -> (usize, usize) { + let made = v["drafts"]["made"].as_u64(); + let accepted = v["drafts"]["accepted"].as_u64(); + if let (Some(a), Some(b)) = (made, accepted) { return (a as usize, b as usize); } + if let Some(pos) = stdout.find("drafts accepted ") { + let rest = &stdout[pos + "drafts accepted ".len()..]; + if let Some(tok) = rest.split_whitespace().next() { + let mut it = tok.split('/'); + if let (Some(a), Some(b)) = (it.next(), it.next()) { + if let (Ok(accepted), Ok(made)) = (a.parse::(), b.parse::()) { + return (made, accepted); } } - match better { Some(c) => cur = c, None => break } - } - if cur != base { - chunk.1 = bp; - split = Some(cur.iter().map(|&x| x as f64).collect()); - } - } - - let mut gm = load(chunk.0, split.as_deref())?; - let mut short = usize::MAX; - for n in [8, 16, 32, 64, 128] { - let p = &pf[..n]; - gm.short = usize::MAX; - let ts = best(&mut || { gm.reset()?; gm.prefill(p).map(drop) })?; - gm.short = 0; - let tb = best(&mut || { gm.reset()?; gm.prefill(p).map(drop) })?; - say!("prompt {n:4}: steps {:.1} ms, batched {:.1} ms", ts * 1e3, tb * 1e3); - if tb < ts && short == usize::MAX { short = n; } - } - if short == usize::MAX { short = 256; } - - let drafts = m.cfg.n_nextn > 0 || m.cfg.dflash.is_some() || m.cfg.eagle3.is_some() || m.draft_model.is_some(); - let kmax = if drafts { gm.k } else { 0 }; - let mut r = Runner::Gpu(Box::new(gm)); - let mut mtp = (0, 0.0); - for k in (0..=kmax).filter(|&k| k <= 4 || k % 2 == 0 || k == kmax) { - if let Runner::Gpu(g) = &mut r { g.k = k.max(1); } - let mut toks = 0; - let t = best(&mut || { - r.reset()?; - let l = r.prefill(&dec)?; - toks = decode(&mut r, &tok, k > 0, &mut Sampler::greedy(), l, 128, None, &mut |_| Ok(false))?.0.len(); - Ok(()) - })?; - // `best` times prefill too; it is the same for every k, so the ranking holds. - let tps = toks as f64 / t; - say!("mtp {k}: decode {toks} tok {tps:.1} tok/s"); - if tps > mtp.1 { mtp = (k, tps); } - } - - let Runner::Gpu(g) = &r else { unreachable!() }; - let path = calibration_path(model, g.gpu.name(), device); - std::fs::create_dir_all(path.parent().unwrap())?; - // The file size tells another file of the same name (another repo or quant source) from this one. - let mut v = json!({"chunk": chunk.0, "mtp": mtp.0, "short": short, "ctx": ctx, "gpu": g.gpu.device(), "bytes": std::fs::metadata(model)?.len(), - "measured": {"prefill_tok_s": chunk.1.round(), "decode_tok_s": (mtp.1 * 10.0).round() / 10.0}}); - if let Some(a) = aux.and_then(|a| a.file_name()) { v["aux"] = a.to_string_lossy().into(); } - // Only a split that was measured as faster, or given by hand: without one, later runs split by the free VRAM - // they find. - if split.is_some() { - v["split"] = json!({"devices": device, "gpus": g.parts().map(|p| p.gpu.device()).collect::>(), "layers": g.part_layers()}); + } } + (0, 0) +} + +/// One measurement sample: run `bench` as a child process with the candidate knobs applied, then read its JSON. +/// Using the public bench command as the measurement channel is what makes calibration work with every architecture: +/// there is one code path that times a prompt and a decode, and calibration never duplicates it. +fn bench_sample(s: &CalibSettings, knobs: &Knobs, task: &str, pps: &[usize]) -> anyhow::Result { + let dir = calib_work_dir()?; + let id = CALIB_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let json = dir.join(format!("bench-{}-{id}.json", std::process::id())); + let prompt = calib_prompt(task, &dir)?; + let exe = std::env::current_exe().context("finding this executable")?; + let chunk = knobs.i("chunk").unwrap_or(4096); + let short = knobs.i("short").unwrap_or(32); + // In a spec sweep the mtp knob holds an index into --mtp; in the main search it is the value itself. + let mtp = if s.mtp_values.is_empty() { knobs.i("mtp").unwrap_or(0) } + else { s.mtp_values[knobs.i("mtp").unwrap_or(0).min(s.mtp_values.len() - 1)] }; + + let build = |reps: usize| { + let mut c = Command::new(&exe); + c.arg("bench") + .arg("--model").arg(&s.model) + .arg("--gpu") + .arg("--pp").arg(pps.iter().map(|n| n.to_string()).collect::>().join(",")) + .arg("--tg").arg(s.tg.to_string()) + .arg("--reps").arg(reps.to_string()) + .arg("--ctx").arg(s.ctx.to_string()) + .arg("--kv").arg(&s.kv) + .arg("--chunk").arg(chunk.to_string()) + .arg("--mtp").arg(mtp.to_string()) + .arg("--short").arg(short.to_string()) + .arg("--device").arg(s.device.iter().map(|d| d.to_string()).collect::>().join(",")) + .arg("--json-out").arg(&json); + if let Some(b) = &s.backend { c.arg("--backend").arg(b); } + if let Some((flag, p)) = &s.aux { c.arg(flag).arg(p); } + if let Some(p) = &prompt { c.arg("--prompt-file").arg(p); } + if !s.vram_margin.is_empty() { c.arg("--vram-margin").arg(s.vram_margin.join(",")); } + // The architectures outside the main engine read their chunk from the environment at prefill time. + c.env("STRATA_DS_CHUNK", chunk.to_string()); + c.env("STRATA_GLM_CHUNK", chunk.to_string()); + c.env("STRATA_G4_CHUNK", chunk.to_string()); + if !s.spec_types.is_empty() { + let ti = knobs.i("spec_type").unwrap_or(0).min(s.spec_types.len() - 1); + let di = knobs.i("draft_max").unwrap_or(0).min(s.draft_max.len() - 1); + let ni = knobs.i("ngram_n").unwrap_or(0).min(s.ngram_n.len() - 1); + c.arg("--spec-type").arg(s.spec_types[ti].clone()); + c.arg("--spec-draft-n-max").arg(s.draft_max[di].to_string()); + c.arg("--spec-ngram-size-n").arg(s.ngram_n[ni].to_string()); + } + c + }; + if s.warmup > 0 { let _ = run_capped(build(1), s.timeout, &dir, id)?; } + let out = run_capped(build(s.reps), s.timeout, &dir, id + 1)?; + if !out.success { + let _ = std::fs::remove_file(&json); + anyhow::bail!("bench failed: {}{}", out.stdout, out.stderr); + } + let text = std::fs::read_to_string(&json).with_context(|| format!("reading {}", json.display()))?; + let v: serde_json::Value = match serde_json::from_str(&text) { + Ok(v) => v, + Err(e) => { let _ = std::fs::remove_file(&json); return Err(e.into()); } + }; + if v["schema"] != "strata.bench.v1" { + let _ = std::fs::remove_file(&json); + anyhow::bail!("bench wrote an unexpected schema"); + } + let rows = v["results"].as_array().context("bench JSON has no results")?; + let (made, accepted) = parse_drafts(&v, &out.stdout); + let mut ms = Vec::with_capacity(pps.len()); + for &pp in pps { + let r = rows.iter().find(|r| r["pp"].as_u64() == Some(pp as u64)) + .with_context(|| format!("bench JSON has no pp {pp}"))?; + let rate = |key: &str| -> anyhow::Result { + r[key]["mean"].as_f64().with_context(|| format!("bench JSON pp {pp} has no {key}.mean")) + }; + ms.push(Measurement { + prefill_tok_s: rate("prefill_tok_s")?, + decode_tok_s: rate("decode_tok_s")?, + drafts_offered: made, + drafts_accepted: accepted, + }); + } + let _ = std::fs::remove_file(&json); + Ok(BenchSample { measurements: ms, backend: v["backend"].as_str().unwrap_or("cuda").to_string() }) +} + +/// Group workloads by task, keeping their order, so one sample can benchmark several prompt depths of a corpus in a +/// single child process while different corpora use different `--prompt-file`s. +fn workload_groups(ws: &[Workload]) -> Vec<(String, Vec<(usize, Workload)>)> { + let mut out: Vec<(String, Vec<(usize, Workload)>)> = Vec::new(); + for (i, w) in ws.iter().enumerate() { + if let Some(g) = out.iter_mut().find(|g| g.0 == w.task) { g.1.push((i, w.clone())); } + else { out.push((w.task.clone(), vec![(i, w.clone())])); } + } + out +} + +fn measure_fn<'a>(s: &'a CalibSettings, backend: &'a RefCell) -> impl FnMut(&Knobs, &[Workload]) -> anyhow::Result> + 'a { + move |knobs, ws| { + let mut out: Vec<(usize, Measurement)> = Vec::with_capacity(ws.len()); + for (task, group) in workload_groups(ws) { + let pps: Vec = group.iter().map(|(_, w)| w.pp).collect(); + let sample = bench_sample(s, knobs, &task, &pps)?; + if backend.borrow().is_empty() { *backend.borrow_mut() = sample.backend.clone(); } + for ((i, _), m) in group.into_iter().zip(sample.measurements) { out.push((i, m)); } + } + // Restore the caller's workload order: the JSON report indexes both arrays by the same position. + out.sort_by_key(|(i, _)| *i); + Ok(out.into_iter().map(|(_, m)| m).collect()) + } +} + +/// A failed baseline (typically OOM at the default chunk) must not abort the run: the search can still find a +/// working point. Returning no baseline makes `search` use its neutral fallback for scoring. +fn baseline_samples(r: anyhow::Result>) -> (Vec, bool) { + match r { Ok(v) => (v, true), Err(_) => (vec![], false) } +} + +/// Whether the model has a draft head: an MTP head in the file, a DFlash/EAGLE3 head, or an auxiliary draft. +fn model_has_mtp(g: &Gguf, aux: bool) -> bool { + if aux { return true; } + let arch = g.get("general.architecture").ok().and_then(|v| v.as_str()).unwrap_or(""); + let nextn = g.get(&format!("{arch}.nextn_predict_layers")).ok().and_then(|v| v.as_u64()).unwrap_or(0); + nextn > 0 || g.meta.keys().any(|k| k.starts_with("dflash.") || k.starts_with("eagle3.")) +} + +/// The search space. Context and KV format are deliberately absent: they are memory choices the user makes, not +/// speed knobs to be silently changed by a calibration. An own-arch model only has its chunk (read from the +/// environment at prefill time); main-engine models also have MTP drafts and the short-prompt threshold. +fn build_space(arch: &str, s: &CalibSettings, has_mtp: bool) -> Vec { + let own = rusting_strata::config::OWN_ARCHS.contains(&arch); + // A chunk larger than the context cannot be used: drop it instead of spending samples on guaranteed failures. + let mut chunks: Vec = s.chunk_values.iter().map(|n| *n as f64).filter(|&c| c <= s.ctx as f64).collect(); + if s.ctx >= 4096 && !chunks.contains(&4096.0) { chunks.push(4096.0); } // today's default is the baseline + if chunks.is_empty() { chunks.push(s.ctx as f64); } + let mut space = vec![KnobSpec::new("chunk", chunks, false)]; + if !own { + let mtp: Vec = if has_mtp { vec![0.0, 1.0, 2.0, 4.0] } else { vec![0.0] }; + let short: Vec = vec![16.0, 32.0, 64.0, 128.0]; + debug_assert!(short.contains(&32.0)); + space.push(KnobSpec::new("mtp", mtp, false)); + space.push(KnobSpec::new("short", short, false)); + } + space +} + +/// A prompt plus its reply must fit the context the measurement will run at; the old calibrate checked this and the +/// diagnostic is much more useful than a run of failed samples ending in "no successful measurement". +fn check_workload_ctx(s: &CalibSettings) -> anyhow::Result<()> { + for &pp in &s.pp { + anyhow::ensure!(pp + s.tg <= s.ctx, "--pp {pp} + --tg {} exceeds --ctx {}; raise --ctx or shorten the workload", s.tg, s.ctx); + } + Ok(()) +} + +/// The baseline must be what a user runs today without a calibration file: chunk 4096, short 32, all the physical +/// cores (left to the engine's own default), and no drafts. Not the first point of the search space. +fn baseline_knobs(space: &[KnobSpec]) -> Knobs { + let mut k = Knobs::default(); + for s in space { + let v = match s.name.as_str() { + "chunk" => 4096.0, + "short" => 32.0, + "mtp" => 0.0, + _ => s.values.first().copied().unwrap_or(0.0), + }; + k.set(&s.name, if s.values.contains(&v) { v } else { s.values[0] }); + } + k +} + +/// Write the small file that later runs read, keeping every key of the v1 format. The full trace is written beside it +/// when `--out` is given, so a calibration can be audited or reproduced from its seed. +/// Readers of the calibration file use the --backend flag, or "cuda" when it is absent. Write under that same name: +/// the backend reported by a bench child (e.g. vulkan) would produce a file no run ever looks for. +fn calib_backend_name(s: &CalibSettings) -> String { + s.backend.clone().unwrap_or_else(|| "cuda".into()) +} + +/// The physical device the search measured on, for the v1 `gpu` compatibility check. +fn calib_gpu_name(s: &CalibSettings) -> String { + s.device.first().and_then(|&d| backend::open(s.backend.as_deref(), d).ok()) + .map(|b| b.device().to_string()).unwrap_or_default() +} + +fn write_report(s: &CalibSettings, result: &calibrate::SearchResult) -> anyhow::Result<()> { + if let Some(out) = &s.out { + std::fs::create_dir_all(out)?; + let stem = s.model.file_stem().and_then(|x| x.to_str()).unwrap_or("model"); + let report = out.join(format!("strata-{stem}-calib-report.json")); + std::fs::write(&report, serde_json::to_string_pretty(result)?)?; + say!("full benchmark report: {}", report.display()); + } + Ok(()) +} + +/// The v2 search does not measure a layer split, so a stale v1 `split` must not survive into the file it rewrites. +fn drop_split(v: &mut serde_json::Value) { + if let Some(o) = v.as_object_mut() { o.remove("split"); } +} + +fn write_calibration(s: &CalibSettings, result: &calibrate::SearchResult, workloads: &[Workload], arch: &str, backend: &str, gpu: &str) -> anyhow::Result { + let path = calibration_path(&s.model, backend, &s.device); + std::fs::create_dir_all(path.parent().unwrap())?; + let mut v: serde_json::Value = std::fs::read(&path).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default(); + drop_split(&mut v); + let best = &result.best; + let first = best.measurements.first().cloned().unwrap_or_default(); + v["schema"] = json!(2); + v["arch"] = json!(arch); + v["chunk"] = json!(best.knobs.i("chunk").unwrap_or(4096)); + v["mtp"] = json!(best.knobs.i("mtp").unwrap_or(0)); + v["short"] = json!(best.knobs.i("short").unwrap_or(32)); + v["ctx"] = json!(s.ctx); // the context the measurement ran at; never a recommendation to apply later + v["gpu"] = json!(gpu); + v["bytes"] = json!(std::fs::metadata(&s.model)?.len()); + v["measured"] = json!({ + "prefill_tok_s": round1(first.prefill_tok_s), + "decode_tok_s": round1(first.decode_tok_s), + }); + v["best"] = serde_json::to_value(&best.knobs)?; + v["search"] = json!({ + "samples_used": result.samples_used, + "score": round1(result.best.score * 1000.0) / 1000.0, + "stop_reason": result.stop_reason, + "elapsed_ms": result.elapsed_ms, + "seed": result.seed, + }); + v["workloads"] = serde_json::to_value(workloads)?; + if let Some(a) = &s.aux { if let Some(name) = a.1.file_name() { v["aux"] = name.to_string_lossy().into(); } } + std::fs::write(&path, serde_json::to_string_pretty(&v)?)?; + write_report(s, result)?; + Ok(path) +} + +/// Pure merge used by a spec sweep: it must not replace the engine knobs measured by a previous run. +fn merge_spec_calibration(mut old: serde_json::Value, spec: &serde_json::Value, arch: &str, gpu: &str, bytes: u64) -> serde_json::Value { + old["schema"] = json!(2); + old["arch"] = json!(arch); + old["gpu"] = json!(gpu); + old["bytes"] = json!(bytes); + old["spec"] = spec.clone(); + old +} + +/// A spec sweep only adds its `spec` section: it must not replace the engine knobs measured by a previous run. +fn write_spec_calibration(s: &CalibSettings, result: &calibrate::SearchResult, arch: &str, backend: &str, gpu: &str, spec: &serde_json::Value) -> anyhow::Result { + let path = calibration_path(&s.model, backend, &s.device); + std::fs::create_dir_all(path.parent().unwrap())?; + let old: serde_json::Value = std::fs::read(&path).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default(); + let mut v = merge_spec_calibration(old, spec, arch, gpu, std::fs::metadata(&s.model)?.len()); + v["spec_search"] = json!({"samples_used": result.samples_used, + "score": round1(result.best.score * 1000.0) / 1000.0, + "stop_reason": result.stop_reason, "seed": result.seed}); std::fs::write(&path, serde_json::to_string_pretty(&v)?)?; - println!("{v}\nwritten to {}", path.display()); + write_report(s, result)?; + Ok(path) +} + +/// The universal calibration workflow. Every supported architecture goes through here; the measurement is delegated +/// to `bench`, so there is no arch-specific timing code to keep in sync. +fn calibrate_v2(s: &CalibSettings) -> anyhow::Result<()> { + check_workload_ctx(s)?; + let g = Gguf::open(&s.model)?; + let arch = g.get("general.architecture").ok().and_then(|v| v.as_str()).unwrap_or("unknown").to_string(); + let has_mtp = model_has_mtp(&g, s.aux.is_some()); + let space = build_space(&arch, s, has_mtp); + let tasks: Vec = if s.tasks.is_empty() { vec!["prose".into()] } else { s.tasks.clone() }; + let workloads: Vec = tasks.iter().flat_map(|task| { + s.pp.iter().map(move |&pp| Workload::new(pp, s.tg, task)) + }).collect(); + say!("calibrate {arch}: {} workloads, {}-sample budget, scoring prefill and decode equally", workloads.len(), s.samples); + for w in &workloads { say!(" {}", w.label()); } + say!("knobs: {}", space.iter().map(|k| format!("{}=[{}]", k.name, k.values.iter().map(|v| format!("{v:.0}")).collect::>().join(","))).collect::>().join(" ")); + say!("baseline (current defaults): {}", baseline_knobs(&space).label()); + if s.dry_run { say!("dry run: no measurements taken"); return Ok(()); } + + let backend = RefCell::new(String::new()); + let mut measure = measure_fn(s, &backend); + let base_knobs = baseline_knobs(&space); + say!("baseline (current defaults): {}", base_knobs.label()); + let (baseline, ok) = baseline_samples(measure(&base_knobs, &workloads)); + if !ok { say!("warning: baseline failed (e.g. OOM at chunk 4096); searching from a neutral reference"); } + let cfg = SearchConfig { samples: s.samples, coarse: (s.samples / 3).min(8), starts: 3, patience: 2, seed: s.seed }; + let result = calibrate::search(&space, &workloads, &cfg, &Objective::balanced(), baseline, &mut measure)?; + anyhow::ensure!(result.best.error.is_none(), "no successful measurement; calibration not written"); + say!("best {}: score {:.3} vs baseline ({:.1} samples, {}, {:.1}s)", result.best.knobs.label(), result.best.score, + result.samples_used, result.stop_reason, result.elapsed_ms as f64 / 1000.0); + let path = write_calibration(s, &result, &workloads, &arch, &calib_backend_name(s), &calib_gpu_name(s))?; + println!("{}\nwritten to {}", serde_json::to_string_pretty(&serde_json::from_str::(&std::fs::read_to_string(&path)?)?)?, path.display()); Ok(()) } +/// Every spec knob is stored as an index into the flag's value list: the search only sees small contiguous ranges +/// and `bench_sample` can index the list directly. +fn spec_space(s: &CalibSettings) -> Vec { + vec![ + KnobSpec::new("spec_type", (0..s.spec_types.len()).map(|i| i as f64), false), + KnobSpec::new("draft_max", (0..s.draft_max.len()).map(|i| i as f64), false), + KnobSpec::new("ngram_n", (0..s.ngram_n.len()).map(|i| i as f64), false), + KnobSpec::new("mtp", (0..s.mtp_values.len()).map(|i| i as f64), false), + ] +} + +/// The baseline can only be the current defaults if those defaults are in the candidate lists. +fn ensure_spec_defaults(s: &mut CalibSettings) { + if !s.spec_types.iter().any(|t| t == "none") { s.spec_types.push("none".into()); } + if !s.draft_max.contains(&16) { s.draft_max.push(16); } + if !s.ngram_n.contains(&12) { s.ngram_n.push(12); } + if !s.mtp_values.contains(&0) { s.mtp_values.push(0); } +} + +/// The spec settings a user gets without a calibration file, expressed as indices into the --lists. +fn spec_baseline(s: &CalibSettings) -> Knobs { + let mut k = Knobs::default(); + k.set("spec_type", s.spec_types.iter().position(|t| t == "none").unwrap_or(0) as f64); + k.set("draft_max", s.draft_max.iter().position(|&n| n == 16).unwrap_or(0) as f64); + k.set("ngram_n", s.ngram_n.iter().position(|&n| n == 12).unwrap_or(0) as f64); + k.set("mtp", s.mtp_values.iter().position(|&n| n == 0).unwrap_or(0) as f64); + k +} + +/// The `spec` subcommand: one task-specific sweep of speculative settings, written under `spec` in the calibration +/// file. It uses the same budgeted search, with each task as its own workload so acceptance can differ by corpus. +fn calibrate_spec(s: &CalibSettings) -> anyhow::Result<()> { + check_workload_ctx(s)?; + let g = Gguf::open(&s.model)?; + let arch = g.get("general.architecture").ok().and_then(|v| v.as_str()).unwrap_or("unknown").to_string(); + let space = spec_space(s); + let workloads: Vec = s.tasks.iter().map(|t| Workload::new(s.pp[0], s.tg, t)).collect(); + say!("spec sweep {arch}: {} tasks x {} types x {} drafts x {} n-grams x {} mtp", workloads.len(), s.spec_types.len(), s.draft_max.len(), s.ngram_n.len(), s.mtp_values.len()); + if s.dry_run { say!("dry run: no measurements taken"); return Ok(()); } + let backend = RefCell::new(String::new()); + let mut measure = measure_fn(s, &backend); + let (baseline, ok) = baseline_samples(measure(&spec_baseline(s), &workloads)); + if !ok { say!("warning: baseline failed; searching from a neutral reference"); } + say!("baseline (current defaults): {}", spec_baseline(s).label()); + let cfg = SearchConfig { samples: s.samples, coarse: (s.samples / 3).min(8), starts: 3, patience: 2, seed: s.seed }; + let result = calibrate::search(&space, &workloads, &cfg, &Objective::balanced(), baseline, &mut measure)?; + anyhow::ensure!(result.best.error.is_none(), "no successful spec measurement; calibration not written"); + let idx = |name: &str, len: usize| result.best.knobs.i(name).unwrap_or(0).min(len.saturating_sub(1)); + let mut spec = serde_json::Map::new(); + for (i, w) in workloads.iter().enumerate() { + let m = result.best.measurements.get(i).cloned().unwrap_or_default(); + let share = if m.drafts_offered > 0 { round1(10000.0 * m.drafts_accepted as f64 / m.drafts_offered as f64) / 100.0 } else { 0.0 }; + spec.insert(w.task.clone(), json!({ + "spec_type": s.spec_types[idx("spec_type", s.spec_types.len())], + "draft_max": s.draft_max[idx("draft_max", s.draft_max.len())], + "ngram_n": s.ngram_n[idx("ngram_n", s.ngram_n.len())], + "mtp": s.mtp_values[idx("mtp", s.mtp_values.len())], + "decode_tok_s": round1(m.decode_tok_s), + "acceptance_pct": share, + })); + } + let path = write_spec_calibration(s, &result, &arch, &calib_backend_name(s), &calib_gpu_name(s), &serde_json::Value::Object(spec))?; + say!("spec sweep written to {}", path.display()); + Ok(()) +} + +/// Compatibility wrapper used by the chat page's calibrate button and by any code calling the old six-argument +/// function. It maps the previous defaults onto the v2 workflow. +fn calibrate(model: &Path, aux: Option<&Path>, ctx: usize, margin: &[usize], kind: Option<&str>, device: &[usize], _split: Option>) -> anyhow::Result<()> { + let mut s = CalibSettings::new(model.to_path_buf()); + s.aux = aux.map(|p| ("--draft-model", p.to_path_buf())); + s.ctx = ctx; + s.backend = kind.map(str::to_string); + s.device = device.to_vec(); + s.vram_margin = margin.iter().map(|m| (m >> 20).to_string()).collect(); + s.samples = 12; + s.pp = vec![512]; + calibrate_v2(&s) +} + + /// Which tokens end a DRY match: those whose text has a newline, colon, double quote or asterisk (llama.cpp's /// default breakers). Built once per model, as decoding the whole vocabulary takes a moment. fn dry_breakers(tok: &Tokenizer, model: &str) -> std::sync::Arc> { @@ -2878,6 +3433,7 @@ fn serve_model(model: &Path, mut engine: Engine, s: &Serving, w: &mut Option, _>(anyhow::anyhow!("out of memory"))); + assert!(!ok); + assert!(ms.is_empty()); + } + + #[test] + fn spec_defaults_are_added_when_the_lists_omit_them() { + let mut s = CalibSettings::new(PathBuf::from("m.gguf")); + s.spec_types = vec!["ngram-simple".into()]; + s.draft_max = vec![4, 8]; + s.ngram_n = vec![3, 6]; + s.mtp_values = vec![2, 0]; + ensure_spec_defaults(&mut s); + assert!(s.spec_types.contains(&"none".to_string())); + assert!(s.draft_max.contains(&16)); + assert!(s.ngram_n.contains(&12)); + let b = spec_baseline(&s); + // The mtp knob is an index: index 1 is the value 0, not the value 1. + assert_eq!(b.i("mtp"), Some(1)); + assert_eq!(s.mtp_values[b.i("mtp").unwrap()], 0); + } + + #[test] + fn the_calibration_file_is_named_like_the_reader_looks_for_it() { + let mut s = CalibSettings::new(PathBuf::from("m.gguf")); + assert_eq!(calib_backend_name(&s), "cuda"); + s.backend = Some("vulkan".into()); + assert_eq!(calib_backend_name(&s), "vulkan"); + } + + #[test] + fn gemma_bench_reports_the_chunk_it_actually_used() { + assert_eq!(gemma_bench_chunk(Some("512")), 512); + assert_eq!(gemma_bench_chunk(Some("nonsense")), 256); + assert_eq!(gemma_bench_chunk(None), 256); + } + + #[test] + fn a_new_calibration_clears_the_stale_v1_split() { + let mut v = serde_json::json!({"chunk": 4096, "split": {"devices": [0, 1], "layers": [12, 28]}, "gpu": "RTX"}); + drop_split(&mut v); + assert!(v.get("split").is_none()); + assert_eq!(v["chunk"], 4096); + assert_eq!(v["gpu"], "RTX"); + } + + #[test] + fn explicit_chunk_environment_variables_are_not_overwritten() { + let all = chunk_env_updates(512, |_| false); + assert_eq!(all.iter().map(|(k, _)| *k).collect::>(), + vec!["STRATA_DS_CHUNK", "STRATA_GLM_CHUNK", "STRATA_G4_CHUNK"]); + assert!(all.iter().all(|(_, v)| v == "512")); + let kept = chunk_env_updates(512, |k| k == "STRATA_DS_CHUNK"); + assert_eq!(kept.iter().map(|(k, _)| *k).collect::>(), + vec!["STRATA_GLM_CHUNK", "STRATA_G4_CHUNK"]); + assert!(chunk_env_updates(512, |_| true).is_empty()); + } + + #[test] + fn workloads_must_fit_the_context_being_measured() { + let mut s = CalibSettings::new(PathBuf::from("m.gguf")); + s.ctx = 2048; s.pp = vec![128, 4096]; s.tg = 16; + let e = check_workload_ctx(&s).unwrap_err(); + assert!(e.to_string().contains("exceeds --ctx 2048"), "{e}"); + s.pp = vec![128, 512]; + assert!(check_workload_ctx(&s).is_ok()); + } + + #[test] + fn cli_parses_the_v2_calibration_flags() { + let cli = Cli::try_parse_from([ + "rustingstrata", "calibrate", "--model", "m.gguf", "--samples", "7", "--reps", "2", + "--pp", "128,512", "--tg", "16", "--chunk-values", "1024,2048", "--task", "user:prompts.txt", + "--seed", "9", "--dry-run", + ]).unwrap(); + match cli.cmd.unwrap() { + Cmd::Calibrate { samples, reps, pp, tg, chunk_values, task, seed, dry_run, sub, .. } => { + assert_eq!((samples, reps, tg, seed), (7, 2, 16, 9)); + assert_eq!(pp, vec![128, 512]); + assert_eq!(chunk_values, Some(vec![1024, 2048])); + assert_eq!(task, vec!["user:prompts.txt"]); + assert!(dry_run); + assert!(sub.is_none()); + } + _other => panic!("wrong command"), + } + } + + #[test] + fn cli_parses_the_spec_subcommand() { + let cli = Cli::try_parse_from([ + "rustingstrata", "calibrate", "spec", "--model", "m.gguf", "--tasks", "prose,coding", + "--spec-types", "none,ngram-simple,ngram-mod", "--draft-max", "4,8", "--ngram-n", "3,6", + "--samples", "5", "--dry-run", + ]).unwrap(); + match cli.cmd.unwrap() { + Cmd::Calibrate { sub: Some(CalibrateSub::Spec { model, tasks, spec_types, draft_max, ngram_n, samples, dry_run, .. }), .. } => { + assert_eq!(model, PathBuf::from("m.gguf")); + assert_eq!(tasks, vec!["prose", "coding"]); + assert_eq!(spec_types, vec!["none", "ngram-simple", "ngram-mod"]); + assert_eq!((draft_max, ngram_n, samples), (vec![4, 8], vec![3, 6], 5)); + assert!(dry_run); + } + _other => panic!("wrong command"), + } + } + + #[test] + fn draft_counts_are_read_from_both_json_and_stdout() { + let v = serde_json::json!({"drafts": {"made": 300, "accepted": 285}}); + assert_eq!(parse_drafts(&v, ""), (300, 285)); + // The arch-specific benchners print "accepted /". + assert_eq!(parse_drafts(&serde_json::Value::Null, "speculative drafts accepted 285/300 (95.0%)"), (300, 285)); + assert_eq!(parse_drafts(&serde_json::Value::Null, "no drafts here"), (0, 0)); + } + + #[test] + fn workload_groups_keep_task_and_depth_order() { + let ws = vec![ + Workload::new(128, 16, "prose"), Workload::new(512, 16, "coding"), + Workload::new(2048, 16, "prose"), Workload::new(96, 16, "coding"), + ]; + let g = workload_groups(&ws); + assert_eq!(g.iter().map(|x| x.0.as_str()).collect::>(), vec!["prose", "coding"]); + assert_eq!(g[0].1.iter().map(|(_, w)| w.pp).collect::>(), vec![128, 2048]); + assert_eq!(g[1].1.iter().map(|(_, w)| w.pp).collect::>(), vec![512, 96]); + assert_eq!(g[0].1[0].0, 0); + assert_eq!(g[0].1[1].0, 2); + } + + #[test] + fn spec_space_stores_indices_not_actual_values() { + let mut s = CalibSettings::new(PathBuf::from("m.gguf")); + s.spec_types = vec!["none".into(), "ngram-simple".into(), "ngram-mod".into(), "ngram-cache".into()]; + s.draft_max = vec![4, 8, 16]; + s.ngram_n = vec![3, 6, 12]; + s.mtp_values = vec![0, 2]; + let space = spec_space(&s); + assert_eq!(space[0].values, vec![0.0, 1.0, 2.0, 3.0]); + assert_eq!(space[1].values, vec![0.0, 1.0, 2.0]); + assert_eq!(space[2].values, vec![0.0, 1.0, 2.0]); + assert_eq!(space[3].values, vec![0.0, 1.0]); + } + + #[test] + fn a_spec_sweep_preserves_the_engine_calibration() { + let old = serde_json::json!({"chunk": 2048, "mtp": 2, "ctx": 8192, "short": 32, "threads": 6, + "measured": {"prefill_tok_s": 100}, "best": {"chunk": 2048}}); + let spec = serde_json::json!({"prose": {"spec_type": "ngram-mod"}}); + let v = merge_spec_calibration(old, &spec, "inkling2_loop", "RTX", 1234); + assert_eq!(v["chunk"], 2048); + assert_eq!(v["mtp"], 2); + assert_eq!(v["ctx"], 8192); + assert_eq!(v["measured"]["prefill_tok_s"], 100); + assert_eq!(v["spec"]["prose"]["spec_type"], "ngram-mod"); + assert_eq!(v["gpu"], "RTX"); + assert_eq!(v["bytes"], 1234); + } + + #[test] + fn knob_space_is_only_chunk_mtp_and_short() { + let s = CalibSettings::new(PathBuf::from("m.gguf")); + let main = build_space("qwen35moe", &s, true); + let names: Vec<_> = main.iter().map(|k| k.name.as_str()).collect(); + assert_eq!(names, vec!["chunk", "mtp", "short"]); + let base = baseline_knobs(&main); + assert_eq!((base.i("chunk"), base.i("mtp"), base.i("short")), (Some(4096), Some(0), Some(32))); + + // No MTP head: don't spend samples on drafts that the engine cannot use. + let no_head = build_space("qwen35moe", &s, false); + assert_eq!(no_head[1].values, vec![0.0]); + + // Own-arch models have only the chunk knob. + let own = build_space("inkling2_loop", &s, false); + assert_eq!(own.iter().map(|k| k.name.as_str()).collect::>(), vec!["chunk"]); + } + + #[test] + fn chunks_larger_than_the_context_are_dropped() { + let mut s = CalibSettings::new(PathBuf::from("m.gguf")); + s.ctx = 2048; + let space = build_space("qwen35moe", &s, true); + let chunks = &space[0].values; + assert!(chunks.iter().all(|&c| c <= 2048.0), "{chunks:?}"); + assert!(!chunks.contains(&4096.0)); + assert!(!chunks.is_empty()); + s.ctx = 4096; + assert!(build_space("qwen35moe", &s, true)[0].values.contains(&4096.0)); + } + + #[test] + fn spec_baseline_uses_current_defaults_not_first_list_values() { + let mut s = CalibSettings::new(PathBuf::from("m.gguf")); + s.spec_types = vec!["ngram-simple".into(), "none".into()]; + s.draft_max = vec![4, 8, 16]; + s.ngram_n = vec![3, 6, 12]; + let b = spec_baseline(&s); + assert_eq!((b.i("spec_type"), b.i("draft_max"), b.i("ngram_n"), b.i("mtp")), + (Some(1), Some(2), Some(2), Some(0))); + } +} From f9dd05aea8d8a53108be01ea43b585634a763121 Mon Sep 17 00:00:00 2001 From: sayampy Date: Tue, 24 Nov 2026 04:14:44 +0530 Subject: [PATCH 049/515] docs: calibration usage guide --- README.md | 4 +- docs/CALIBRATION.md | 173 ++++++++++++++++++++++++++++++++++++++++++++ docs/USAGE.md | 11 +-- 3 files changed, 182 insertions(+), 6 deletions(-) create mode 100644 docs/CALIBRATION.md diff --git a/README.md b/README.md index 4402f59d..70576c11 100644 --- a/README.md +++ b/README.md @@ -66,7 +66,8 @@ With flags: ```sh M=path/to/model.gguf -rustingstrata calibrate --model $M # once per model and machine: best chunk size, MTP drafts +rustingstrata calibrate --model $M --dry-run # preview the workload matrix and knob space +rustingstrata calibrate --model $M # once per model and machine: best chunk, MTP drafts, short threshold rustingstrata chat --model $M --gpu # --think for thinking mode, --temp 0.7 to sample rustingstrata generate --model $M --gpu --prompt "Write a haiku about rivers." -n 128 rustingstrata serve --model $M --gpu --addr 127.0.0.1:8080 @@ -80,6 +81,7 @@ Inkling 2 open the GPU by themselves. - [USAGE.md](docs/USAGE.md): flags, the chat page and MCP tools, the OpenAI and Anthropic APIs, prompt caching, several GPUs. +- [CALIBRATION.md](docs/CALIBRATION.md): the budgeted search, task corpora, the `spec` sweep and the JSON file. - [MODELS.md](docs/MODELS.md): supported architectures and GGUF types, notes and caveats for each model. - [BENCHMARKS.md](docs/BENCHMARKS.md): every model against llama.cpp; older runs are in the [benchmark history](docs/README.md#benchmark-history). diff --git a/docs/CALIBRATION.md b/docs/CALIBRATION.md new file mode 100644 index 00000000..5fc5cf0b --- /dev/null +++ b/docs/CALIBRATION.md @@ -0,0 +1,173 @@ +# Calibration + +`rustingstrata calibrate` measures the settings that make a model fastest on **this** machine and writes them to +`~/.cache/rusting_strata/strata-[-backend][-dev…].json`. Later runs read that file unless a flag overrides the +value. One calibration per model, backend and device combination is enough; re-run after changing GPU, driver, quant, +KV format or a draft file. + +Every architecture the binary supports is measured, including Inkling 2, Hy4, GLM, DeepSeek and Gemma 4, which the +old command skipped because they run on their own code path. Measurement is delegated to the existing `bench` +command (as a child process, reading its `strata.bench.v1` JSON), so there is a single timing implementation to trust. + +## Quick start + +```sh +M=path/to/model.gguf + +# See the derived knob space and workload matrix, without loading weights: +rustingstrata calibrate --model $M --dry-run + +# A normal calibration: 24 samples, prompt depths 128/512/2048: +rustingstrata calibrate --model $M + +# A smaller, explicit search with two real corpora: +rustingstrata calibrate --model $M --chunk-values 512,1024,2048,4096 \ + --task prose --task coding --pp 128,512,2048 --tg 128 --samples 32 \ + --out ./calib-reports + +# Every model in a folder, one after another: +rustingstrata calibrate --model ~/models +``` + +The command prints the workload matrix and knob space, then the baseline and the winner, then the path of the JSON +file. `--out DIR` additionally writes a full trace of every sample as `strata--calib-report.json`. + +## What is optimized + +Two signals are measured per workload: **prefill throughput** (prompt tokens / prefill time) and **decode throughput** +(generated tokens / greedy decode time). Both are divided by their own baseline and combined with a geometric mean: + +``` +score = sqrt((prefill / baseline_prefill) · (decode / baseline_decode)) +``` + +An arithmetic mean would let a huge gain in one signal hide a regression in the other. Ratios are clamped to +`[1e-3, 1e3]` so a failed measurement cannot produce infinities. Time to first token is *not* a separate signal: for +greedy decoding the first token's logits come out of the prefill, so TTFT would just reweight prefill. + +The baseline is what a user gets today **without** a calibration file: chunk 4096, short-prompt threshold 32, all +physical cores and no drafts. The reported score is relative to that, not to the first point of the search space. + +Context length and KV format are deliberately not searched. They are memory choices the user makes; a noisy speed +win must not silently double someone's KV cache. `--ctx` and `--kv` only set the conditions of the measurement. + +## Workloads and tasks + +`--pp` lists prompt depths (default `128,512,2048`); `--tg` sets decoded tokens (default 128). All depths of one task +are measured in a single child process. + +- `prose` (default): the built-in repeated paragraph, a stable machine-level baseline. +- `coding`: a built-in code snippet; real punctuation and identifiers change routing and draft acceptance. +- `user:PATH`: your own prompt file, for RAG documents, long system prompts, etc. + +Repeat `--task` to mix corpora: + +```sh +rustingstrata calibrate --model $M --task prose --task user:prompts.txt --pp 256,2048 +``` + +## Search strategy + +The search is deterministic for a given `--seed` and bounded by `--samples`: + +1. **Baseline** — current defaults, measured on the full workload matrix (not counted in the budget). +2. **Coarse sweep** — up to `min(samples/3, 8)` points from a low-discrepancy (radical-inverse) sequence over the + joint knob space. Their scores only pick starting points; they are never compared with full-matrix scores and + cannot win. +3. **Multi-start coordinate descent** — each start is re-measured on the full matrix, then each knob is tried at + every other value and the best move kept. The walk stops after two rounds without improvement. `stop_reason` is + reset for every start, so all of them get a full descent. +4. **Final polish** — one more pass over the cheap knobs from the overall winner. + +A candidate that fails (OOM, timeout, missing JSON fields) is recorded with its error and never wins; it still counts +against the budget. `--timeout SECS` caps each sample. `--warmup N` adds an extra discarded run per sample; it is off +by default because it loads the model a second time. + +### Knobs + +| knob | values | applies to | +| --- | --- | --- | +| `chunk` | `--chunk-values`, default `256,512,1024,2048,4096` | all architectures | +| `mtp` | `0,1,2,4` | main-engine models with a draft head, otherwise `0` only | +| `short` | `16,32,64,128` | main engine only | + +Inkling 2, Hy4, GLM, DeepSeek and Gemma 4 read their chunk from the environment at prefill time, so `bench_sample` +sets `STRATA_DS_CHUNK`, `STRATA_GLM_CHUNK` and `STRATA_G4_CHUNK` to the candidate value. Their engines apply a +calibrated chunk the same way at load time. The main engine reads `chunk`, `mtp` and `short` from the file in the +usual way. + +Multi-GPU runs (pass `--device 0,1`) use the engine's free-VRAM layer split; the old layer-split sweep is not part of +this workflow and `--split` is ignored with a note. + +## Flags + +| flag | default | meaning | +| --- | --- | --- | +| `--samples N` | 24 | hard cap on benchmark samples | +| `--reps N` | 3 | repetitions per point (their mean is used) | +| `--warmup N` | 0 | extra discarded run before each sample | +| `--pp A,B,C` | `128,512,2048` | prompt depths | +| `--tg N` | 128 | decoded tokens | +| `--chunk-values A,B` | `256,…,4096` | prefill chunks to search | +| `--task LABEL` | `prose` | corpus (repeatable) | +| `--seed N` | 1 | deterministic search seed | +| `--timeout SECS` | 0 (none) | per-sample time limit | +| `--dry-run` | off | print the plan, take no measurements | +| `--out DIR` | — | also write the full sample trace | +| `--mtp-model` / `--draft-model` | — | measure with that draft file loaded | +| `--ctx`, `--kv` | 4096, f16 | conditions of the measurement, not searched | + +`--model` also accepts a folder: every `.gguf` in it and its subfolders is calibrated with the same flags; a model +that fails is reported and the rest go on. `--mtp-model` and `--draft-model` need a single model file. + +## The `spec` subcommand + +`calibrate spec` sweeps speculative settings **per task**: which spec type and how many drafts are best for coding +versus prose on this model. + +```sh +rustingstrata calibrate spec \ + --model ~/Models/Inkling2/Inkling-2-Mini-UD-Q3_K_XL.gguf \ + --draft-model ~/Models/Inkling2/dspark-Inkling-2-Mini-Q8_0.gguf \ + --tasks prose,coding --spec-types ngram-simple,ngram-mod,ngram-cache \ + --draft-max 4,8,16 --ngram-n 3,6,12 --samples 16 +``` + +Knobs: `spec_type` (`none`, `suffix`, `ngram-simple`, `ngram-map-k`, `ngram-map-k4v`, `ngram-mod`, `ngram-cache`), +`draft_max` (drafts verified per step), `ngram_n` (lookup key length), `mtp` (MTP count, main engine only). The search +stores indices into those lists; the JSON report and the child `bench` command both receive the actual values. The +baseline is today's spec defaults (`none`, 16 drafts, n-gram 12, mtp 0). + +The result is written under `spec` in the same calibration file, keyed by task, with decode rate and draft acceptance +percentage of the winner. A spec sweep **only adds that section**: engine knobs measured by a previous `calibrate` +run are left untouched. + +## The calibration file + +The file keeps every v1 key (`chunk`, `mtp`, `short`, `ctx`, `gpu`, `bytes`, `measured`, `aux`, `split`), so older +binaries still read it. v2 adds: + +```json +{ + "schema": 2, + "arch": "qwen35moe", + "chunk": 2048, "mtp": 2, "short": 32, + "ctx": 4096, + "measured": {"prefill_tok_s": 1057.0, "decode_tok_s": 26.7}, + "best": {"chunk": 2048, "mtp": 2, "short": 32}, + "search": {"samples_used": 24, "score": 1.234, "stop_reason": "budget", + "elapsed_ms": 123456, "seed": 1}, + "workloads": [{"pp": 128, "tg": 128, "task": "prose"}], + "spec": {"prose": {"spec_type": "ngram-mod", "draft_max": 8, "ngram_n": 6, + "acceptance_pct": 72.5}} +} +``` + +`ctx` records the context the measurement ran at; it is never a recommendation applied to later runs. There is no +`kv` or `threads` key from v2 — those remain the user's choice. `--out DIR` writes a separate +`strata--calib-report.json` with all trials, their knob points, measurements, errors and timings, useful for +auditing a surprising result or comparing two seeds. + +The filename encodes backend and device order (`-vulkan`, `-dev0-1`), so calibrations for different setups do not +overwrite each other. As before, `XDG_CACHE_HOME` moves the folder, and a file measured on another GPU or another +file of the same name (different size) is ignored with a warning. diff --git a/docs/USAGE.md b/docs/USAGE.md index 32e0375e..b2a48a73 100644 --- a/docs/USAGE.md +++ b/docs/USAGE.md @@ -112,8 +112,9 @@ other MCP clients use, and pass it with `--mcp ` (or `STRATA_MCP`; the def differently from one-token decoding, so greedy output can differ at a near tie. - `--chunk`, `--threads` prefill chunk size and CPU expert threads. On a GPU `--threads` defaults to the physical core count (SMT siblings only add contention; on the 6-core/12-thread reference machine 6 beats 12 by ~20%). - `rustingstrata calibrate` measures the best chunk and later runs read it from - `~/.cache/rusting_strata/strata-.json` unless flags override. + `rustingstrata calibrate` measures the best chunk, draft count and short-prompt threshold and later runs read them + from `~/.cache/rusting_strata/strata-.json` unless flags override. See [CALIBRATION.md](CALIBRATION.md) for + the budgeted search and the `calibrate spec` sweep. `XDG_CACHE_HOME` moves that folder to `$XDG_CACHE_HOME/rusting_strata` (on Windows it is `%LOCALAPPDATA%\rusting_strata`). In a container, set it to a mounted path: `docker run --rm` otherwise discards the file on exit, and the next container runs uncalibrated. The file names the GPU it was measured on, and a file @@ -136,9 +137,9 @@ other MCP clients use, and pass it with `--mcp ` (or `STRATA_MCP`; the def expert placement see the VRAM it takes, and picks the draft count. Runs with the same `--mtp-model` or `--draft-model` file use that count unless `--mtp` is given; runs with another draft file or none do not. - `calibrate --model ~/models` calibrates every model in a folder (and its subfolders, as the chat page lists them), - one after another, with the other flags applied to each. A model that fails is reported and the rest go on; Inkling - 2, Hy4, GLM, DeepSeek and Gemma 4 models are skipped: `calibrate` measures the main engine only, and these models - run on their own code path, which reads no calibration file. `--mtp-model` and `--draft-model` need a single file. + one after another, with the other flags applied to each. A model that fails is reported and the rest go on. All + architectures are included: Inkling 2, Hy4, GLM, DeepSeek and Gemma 4 are measured through their own `bench` path. + `--mtp-model` and `--draft-model` need a single model file. - `--thinking-budget N` (`chat` and `serve`) ends the thinking block after `N` tokens by inserting ``, so the model goes on to the answer (0, the default, is no limit). A request overrides it with `thinking_budget` or `chat_template_kwargs.thinking_budget` (Anthropic: `thinking.budget_tokens`). From df37bb56787dc8e1eda9efbde5cbd5f23bb4f0bc Mon Sep 17 00:00:00 2001 From: sayampy Date: Tue, 24 Nov 2026 23:48:33 +0530 Subject: [PATCH 050/515] calibrate: fix backend file name, baseline, short space, arch chunks and serve env leak --- docs/CALIBRATION.md | 57 +++++++----- docs/MODELS.md | 5 +- docs/USAGE.md | 25 +++--- src/calibrate.rs | 47 +++++++--- src/main.rs | 206 ++++++++++++++++++++++++++++++++++++-------- 5 files changed, 259 insertions(+), 81 deletions(-) diff --git a/docs/CALIBRATION.md b/docs/CALIBRATION.md index 5fc5cf0b..a9da69b3 100644 --- a/docs/CALIBRATION.md +++ b/docs/CALIBRATION.md @@ -42,11 +42,15 @@ score = sqrt((prefill / baseline_prefill) · (decode / baseline_decode)) ``` An arithmetic mean would let a huge gain in one signal hide a regression in the other. Ratios are clamped to -`[1e-3, 1e3]` so a failed measurement cannot produce infinities. Time to first token is *not* a separate signal: for -greedy decoding the first token's logits come out of the prefill, so TTFT would just reweight prefill. +`[1e-3, 1e3]` so a failed measurement cannot produce infinities. Several workloads are combined with a geometric mean, +so every prompt depth counts equally. Time to first token is *not* a separate signal: for greedy decoding the first +token's logits come out of the prefill, so TTFT would just reweight prefill. -The baseline is what a user gets today **without** a calibration file: chunk 4096, short-prompt threshold 32, all -physical cores and no drafts. The reported score is relative to that, not to the first point of the search space. +The baseline is what a user gets today **without** a calibration file: the engine's own chunk — 4096 for the main +engine, 256 (Gemma 4), 512 (GLM), 1024 (Hy4) and 256 (Inkling 2, which clamps its GPU prefill to that size) for the +architectures with their own forward, and no chunk at all for DeepSeek, which prefills one token at a time. Where the +knobs apply, the baseline also uses short-prompt threshold 32, the physical core count and no drafts. The reported +score is relative to that, not to the first point of the search space. Context length and KV format are deliberately not searched. They are memory choices the user makes; a noisy speed win must not silently double someone's KV cache. `--ctx` and `--kv` only set the conditions of the measurement. @@ -70,7 +74,10 @@ rustingstrata calibrate --model $M --task prose --task user:prompts.txt --pp 256 The search is deterministic for a given `--seed` and bounded by `--samples`: -1. **Baseline** — current defaults, measured on the full workload matrix (not counted in the budget). +1. **Baseline** — current defaults, measured on the full workload matrix (not counted in the budget). It is also a + trial in the search, so a candidate that scores below it cannot win. If no candidate beats it, no calibration is + written and the defaults stay in force. A failed baseline warns and scores against a neutral `1x` reference; such a + run writes a file only when a point beats that reference. 2. **Coarse sweep** — up to `min(samples/3, 8)` points from a low-discrepancy (radical-inverse) sequence over the joint knob space. Their scores only pick starting points; they are never compared with full-matrix scores and cannot win. @@ -80,24 +87,32 @@ The search is deterministic for a given `--seed` and bounded by `--samples`: 4. **Final polish** — one more pass over the cheap knobs from the overall winner. A candidate that fails (OOM, timeout, missing JSON fields) is recorded with its error and never wins; it still counts -against the budget. `--timeout SECS` caps each sample. `--warmup N` adds an extra discarded run per sample; it is off -by default because it loads the model a second time. +against the budget. Every stage, including the final polish, draws from `--samples`; the baseline alone is outside the +budget. `--reps N` repetitions happen inside one sample and do not consume extra samples. `--timeout SECS` caps each +sample. `--warmup N` adds an extra discarded run per sample; it is off by default because it loads the model a second +time. ### Knobs | knob | values | applies to | | --- | --- | --- | -| `chunk` | `--chunk-values`, default `256,512,1024,2048,4096` | all architectures | +| `chunk` | `--chunk-values`, default `256,512,1024,2048,4096` | main engine and Gemma 4, GLM, Hy4, Inkling 2 (capped at 256); DeepSeek has no chunk knob | | `mtp` | `0,1,2,4` | main-engine models with a draft head, otherwise `0` only | -| `short` | `16,32,64,128` | main engine only | +| `short` | 32 plus one threshold just above each `--pp` depth (default `32,129,513,2049`) | main engine only | -Inkling 2, Hy4, GLM, DeepSeek and Gemma 4 read their chunk from the environment at prefill time, so `bench_sample` -sets `STRATA_DS_CHUNK`, `STRATA_GLM_CHUNK` and `STRATA_G4_CHUNK` to the candidate value. Their engines apply a -calibrated chunk the same way at load time. The main engine reads `chunk`, `mtp` and `short` from the file in the -usual way. +Each `short` threshold flips exactly one prompt depth into the short-prompt path: a prompt uses token-at-a-time +prefill when it is shorter than the threshold. The old fixed `16/32/64/128` list was below every default workload +depth, so no candidate changed anything and the value written was noise. -Multi-GPU runs (pass `--device 0,1`) use the engine's free-VRAM layer split; the old layer-split sweep is not part of -this workflow and `--split` is ignored with a note. +Inkling 2, Hy4, GLM and Gemma 4 read their chunk from the environment at prefill time, so `bench_sample` sets +`STRATA_DS_CHUNK`, `STRATA_GLM_CHUNK` and `STRATA_G4_CHUNK` to the candidate value. Their engines apply a calibrated +chunk the same way at load time. In `serve`, those variables are restored before a different model is loaded, so a +model without a calibration never inherits the previous model's chunk. DeepSeek prefills one token at a time and +reads no chunk: its calibration records no chunk, MTP count or short threshold. The main engine reads `chunk`, `mtp` +and `short` from the file in the usual way. + +Multi-GPU runs (pass `--device 0,1`) keep the engine's free-VRAM layer split; calibration does not measure or write a +layer split, and `--split` is ignored with a note. ## Flags @@ -144,8 +159,9 @@ run are left untouched. ## The calibration file -The file keeps every v1 key (`chunk`, `mtp`, `short`, `ctx`, `gpu`, `bytes`, `measured`, `aux`, `split`), so older -binaries still read it. v2 adds: +The file keeps the v1 keys the engines read (`chunk`, `mtp`, `short`, `ctx`, `gpu`, `bytes`, `measured`, `aux`), so +older binaries still read it. A stale v1 `split` is deliberately dropped: v2 does not measure a layer split and +nothing writes that key. v2 adds: ```json { @@ -168,6 +184,7 @@ binaries still read it. v2 adds: `strata--calib-report.json` with all trials, their knob points, measurements, errors and timings, useful for auditing a surprising result or comparing two seeds. -The filename encodes backend and device order (`-vulkan`, `-dev0-1`), so calibrations for different setups do not -overwrite each other. As before, `XDG_CACHE_HOME` moves the folder, and a file measured on another GPU or another -file of the same name (different size) is ignored with a warning. +The filename encodes the backend that **actually opened** and the device order (`-vulkan`, `-dev0-1`), so a CUDA +to Vulkan fallback writes the file the runs will look for, and calibrations for different setups do not overwrite +each other. As before, `XDG_CACHE_HOME` moves the folder, and a file measured on another GPU or another file of the +same name (different size) is ignored with a warning. diff --git a/docs/MODELS.md b/docs/MODELS.md index 7fd11009..8da14a13 100644 --- a/docs/MODELS.md +++ b/docs/MODELS.md @@ -21,8 +21,9 @@ The engine picks the code path from `general.architecture` in the file. | [Hy4-flash](#hy4-flash-iq2_siq2_xxs-85-gb) | `hy_v4_flash` | own forward, matvecs and expert cache on CUDA or Vulkan, greedy only | | [Inkling 2 Mini](#inkling-2-mini-iq4_nl-176-gb) | `inkling2_loop`, `inkling2` | own forward, matvecs and expert cache on CUDA or Vulkan | -The models with their own forward open the GPU by themselves (no `--gpu` flag), have nothing to calibrate and load -from the chat page of one server like the others. Image input is in [VISION.md](VISION.md). +The models with their own forward open the GPU by themselves (no `--gpu` flag) and load from the chat page of one +server like the others. `rustingstrata calibrate` measures their prefill chunk too (DeepSeek has no chunk to tune); +they read it from the same calibration file at load time. Image input is in [VISION.md](VISION.md). ## Qwen models diff --git a/docs/USAGE.md b/docs/USAGE.md index b2a48a73..f17ad13e 100644 --- a/docs/USAGE.md +++ b/docs/USAGE.md @@ -113,8 +113,10 @@ other MCP clients use, and pass it with `--mcp ` (or `STRATA_MCP`; the def - `--chunk`, `--threads` prefill chunk size and CPU expert threads. On a GPU `--threads` defaults to the physical core count (SMT siblings only add contention; on the 6-core/12-thread reference machine 6 beats 12 by ~20%). `rustingstrata calibrate` measures the best chunk, draft count and short-prompt threshold and later runs read them - from `~/.cache/rusting_strata/strata-.json` unless flags override. See [CALIBRATION.md](CALIBRATION.md) for - the budgeted search and the `calibrate spec` sweep. + from `~/.cache/rusting_strata/strata-[-backend][-dev…].json` unless flags override. The suffix uses the + backend that actually opened (so a CUDA to Vulkan fallback writes the Vulkan file). The models with their own + forward are calibrated too; see [CALIBRATION.md](CALIBRATION.md) for the budgeted search and the `calibrate spec` + sweep. `XDG_CACHE_HOME` moves that folder to `$XDG_CACHE_HOME/rusting_strata` (on Windows it is `%LOCALAPPDATA%\rusting_strata`). In a container, set it to a mounted path: `docker run --rm` otherwise discards the file on exit, and the next container runs uncalibrated. The file names the GPU it was measured on, and a file @@ -240,19 +242,12 @@ first, which is not the order of `nvidia-smi`), on Vulkan too; the other Vulkan integrated ones. The load prints the card of every index (`cuda device 1: ...` or `vulkan device 1: ...`). The split by free VRAM does not know which card is faster or which sits on a slow PCIe link (x1 riser, x4 slot). -`rustingstrata calibrate --model M.gguf --device 0,1` measures it: it times prefill and decode with the split by free -VRAM, then with layers moved from one card to the other in steps of 15% of the layers, and follows the faster -direction for up to three rounds. A split that is more than 3% faster (prefill tok/s times decode tok/s; each split line prints this product as -a share of the best one so far) is written to the calibration file as layers per card, and later runs with the same -cards in the same `--device` order load with it. -A card with fewer layers keeps more of their experts in VRAM, so fewer are uploaded to it during prefill, and the other -card then keeps fewer of its own: the timings decide. The order of the cards is not searched: to compare, calibrate -`--device 1,0` too. Each order has its own file (`strata--dev0-1.json`, `-dev1-0.json`), and a run uses the -file of the order it is given. - -`--split 30,70` (or `STRATA_SPLIT=30,70`) sets the share of the layers per card by hand, in `--device` order, and -takes precedence over the calibrated split; `calibrate --split 30,70` measures chunk and drafts with that split and -stores it. The load prints each card's layers and its measured host-to-VRAM copy rate. AMD cards clock down in the gaps while the other card works; `echo high > +`--split 30,70` (or `STRATA_SPLIT=30,70`) sets the share of the layers per card by hand, in `--device` order; the load +prints each card's layers and its measured host-to-VRAM copy rate. `rustingstrata calibrate` does not measure or write +a split: it times the chunk, drafts and short-prompt threshold with the split the run will use, and `--split` is +accepted for symmetry but ignored with a note. To compare card orders, calibrate `--device 1,0` too: each order has +its own file (`strata--dev0-1.json`, `-dev1-0.json`), and a run uses the file of the order it is given. +AMD cards clock down in the gaps while the other card works; `echo high > /sys/class/drm/cardN/device/power_dpm_force_performance_level` (as root, per card) took a two-card split from 44 to 57 tok/s in one report. diff --git a/src/calibrate.rs b/src/calibrate.rs index 2cc53f2b..1d7bf327 100644 --- a/src/calibrate.rs +++ b/src/calibrate.rs @@ -73,7 +73,7 @@ pub struct Measurement { } impl Measurement { - fn valid(&self) -> bool { + pub fn valid(&self) -> bool { [self.prefill_tok_s, self.decode_tok_s].iter().all(|v| v.is_finite() && *v > 0.0) } } @@ -203,9 +203,10 @@ fn default_knobs(space: &[KnobSpec]) -> Knobs { /// Run the search. `measure` is called once per sample with the workload matrix; it should apply the knobs, take its /// own repetitions and return one measurement per workload. `baseline` has one measurement per workload, taken with -/// the settings a user gets without a calibration file. +/// `baseline_knobs` (the settings a user gets without a calibration file). The baseline competes in the search: a +/// candidate slower than today's defaults must not be written as the winner. pub fn search(space: &[KnobSpec], workloads: &[Workload], cfg: &SearchConfig, obj: &Objective, - baseline: Vec, mut measure: F) -> Result + baseline_knobs: &Knobs, baseline: Vec, mut measure: F) -> Result where F: FnMut(&Knobs, &[Workload]) -> Result> { anyhow::ensure!(!space.is_empty() && !workloads.is_empty(), "calibration needs a knob space and at least one workload"); @@ -214,6 +215,16 @@ where F: FnMut(&Knobs, &[Workload]) -> Result> while baselines.len() < workloads.len() { baselines.push(fallback.clone()); } let start = Instant::now(); let mut trials: Vec = Vec::new(); + // The baseline is a real trial, measured outside the sample budget. Its ratios against itself are 1.0, so the + // search can never pick a slower point unless the baseline measurement itself failed. + trials.push(Trial { + knobs: baseline_knobs.clone(), + measurements: baseline.clone(), + score: aggregate_score(&baseline, &baselines, obj), + error: if baseline.iter().any(|m| m.valid()) { None } else { Some("baseline measurement failed".to_string()) }, + elapsed_ms: 0, + workloads: workloads.len(), + }); let mut used = 0usize; let mut evaluate = |knobs: &Knobs, subset: &[Workload]| -> Result { @@ -230,6 +241,8 @@ where F: FnMut(&Knobs, &[Workload]) -> Result> // One bench child per distinct (knob point, workload set): repeats cost a full model load and consume budget // without adding information. `seen` is shared by every stage, including all starts. let mut seen: std::collections::HashSet<(String, usize)> = std::collections::HashSet::new(); + // The baseline was measured outside the budget: never spend a sample repeating it. + seen.insert((baseline_knobs.label(), workloads.len())); let mut eval_unique = |knobs: &Knobs, subset: &[Workload]| -> Result> { if !seen.insert((knobs.label(), subset.len())) { return Ok(None); } evaluate(knobs, subset).map(Some) @@ -339,6 +352,7 @@ mod tests { } fn workloads() -> Vec { vec![Workload::new(128, 16, "prose"), Workload::new(512, 16, "prose")] } fn base() -> Measurement { Measurement { prefill_tok_s: 100.0, decode_tok_s: 20.0, ..Default::default() } } + fn baseline_knobs() -> Knobs { let mut k = Knobs::default(); k.set("chunk", 256.0); k.set("mtp", 0.0); k } #[test] fn objective_is_a_geometric_mean_of_two_signals() { @@ -364,7 +378,7 @@ mod tests { fn search_respects_the_sample_budget_and_finds_the_best_region() { let mut calls = 0; let cfg = SearchConfig { samples: 12, coarse: 4, starts: 2, patience: 1, seed: 5 }; - let r = search(&space(), &workloads(), &cfg, &Objective::balanced(), vec![base(), base()], |k, _| { + let r = search(&space(), &workloads(), &cfg, &Objective::balanced(), &baseline_knobs(), vec![base(), base()], |k, _| { calls += 1; let boost = if k.i("chunk") == Some(1024) { 2.0 } else { 1.0 } * if k.i("mtp") == Some(1) { 1.5 } else { 1.0 }; Ok(vec![Measurement { prefill_tok_s: 100.0 * boost, decode_tok_s: 20.0 * boost, ..Default::default() }]) @@ -387,7 +401,7 @@ mod tests { KnobSpec::new("mtp", (0..8).map(|i| i as f64), false), ]; let cfg = SearchConfig { samples: 40, coarse: 3, starts: 3, patience: 2, seed: 9 }; - let r = search(&big, &workloads(), &cfg, &Objective::balanced(), vec![base(), base()], |k, _| { + let r = search(&big, &workloads(), &cfg, &Objective::balanced(), &baseline_knobs(), vec![base(), base()], |k, _| { let boost = 1.0 + k.i("chunk").unwrap() as f64 / 1000.0 + k.i("mtp").unwrap() as f64 / 100.0; Ok(vec![Measurement { prefill_tok_s: 100.0 * boost, decode_tok_s: 20.0 * boost, ..Default::default() }]) }).unwrap(); @@ -397,7 +411,7 @@ mod tests { #[test] fn short_prompt_only_gains_cannot_win_the_search() { let cfg = SearchConfig { samples: 14, coarse: 6, starts: 3, patience: 1, seed: 3 }; - let r = search(&space(), &workloads(), &cfg, &Objective::balanced(), vec![base(), base()], |k, subset| { + let r = search(&space(), &workloads(), &cfg, &Objective::balanced(), &baseline_knobs(), vec![base(), base()], |k, subset| { let mtp = k.i("mtp").unwrap(); Ok(subset.iter().map(|w| { let boost = if mtp == 1 { if w.pp == 128 { 2.0 } else { 0.25 } } else { 1.0 }; @@ -411,7 +425,7 @@ mod tests { #[test] fn failed_measurements_are_recorded_and_never_win() { let cfg = SearchConfig { samples: 8, coarse: 4, starts: 1, patience: 1, seed: 2 }; - let r = search(&space(), &workloads(), &cfg, &Objective::balanced(), vec![base(), base()], |k, _| { + let r = search(&space(), &workloads(), &cfg, &Objective::balanced(), &baseline_knobs(), vec![base(), base()], |k, _| { if k.i("mtp") == Some(1) { anyhow::bail!("out of memory") } Ok(vec![base(), base()]) }).unwrap(); @@ -422,7 +436,7 @@ mod tests { #[test] fn an_empty_baseline_still_allows_the_search_to_run() { let cfg = SearchConfig { samples: 10, coarse: 3, starts: 1, patience: 1, seed: 6 }; - let r = search(&space(), &workloads(), &cfg, &Objective::balanced(), vec![], |_, _| { + let r = search(&space(), &workloads(), &cfg, &Objective::balanced(), &baseline_knobs(), vec![], |_, _| { Ok(vec![Measurement { prefill_tok_s: 100.0, decode_tok_s: 20.0, ..Default::default() }]) }).unwrap(); assert!(r.best.error.is_none()); @@ -432,7 +446,7 @@ mod tests { #[test] fn the_same_knob_point_is_never_measured_twice() { let cfg = SearchConfig { samples: 60, coarse: 6, starts: 3, patience: 2, seed: 7 }; - let r = search(&space(), &workloads(), &cfg, &Objective::balanced(), vec![base(), base()], |k, _| { + let r = search(&space(), &workloads(), &cfg, &Objective::balanced(), &baseline_knobs(), vec![base(), base()], |k, _| { let boost = 1.0 + k.i("chunk").unwrap() as f64 / 10000.0 + k.i("mtp").unwrap() as f64 / 10.0; Ok(vec![Measurement { prefill_tok_s: 100.0 * boost, decode_tok_s: 20.0 * boost, ..Default::default() }]) }).unwrap(); @@ -446,13 +460,26 @@ mod tests { fn every_start_converging_is_recorded_as_converged() { // A flat landscape: no move ever improves, so all starts stop on patience before the budget is used. let cfg = SearchConfig { samples: 60, coarse: 3, starts: 2, patience: 2, seed: 4 }; - let r = search(&space(), &workloads(), &cfg, &Objective::balanced(), vec![base(), base()], |_, _| { + let r = search(&space(), &workloads(), &cfg, &Objective::balanced(), &baseline_knobs(), vec![base(), base()], |_, _| { Ok(vec![base(), base()]) }).unwrap(); assert!(r.samples_used < cfg.samples, "should stop early: {}", r.samples_used); assert_eq!(r.stop_reason, "converged"); } + #[test] + fn a_slower_candidate_can_never_beat_the_baseline() { + let cfg = SearchConfig { samples: 20, coarse: 6, starts: 3, patience: 2, seed: 11 }; + let base_knobs = baseline_knobs(); + let r = search(&space(), &workloads(), &cfg, &Objective::balanced(), &base_knobs, + vec![base(), base()], |_, _| { + Ok(vec![Measurement { prefill_tok_s: 50.0, decode_tok_s: 10.0, ..Default::default() }]) + }).unwrap(); + assert_eq!(r.best.knobs, base_knobs, "a slower point must not be written"); + assert!((r.best.score - 1.0).abs() < 1e-9, "the baseline wins at score 1.0"); + assert!(r.trials.iter().any(|t| t.knobs == base_knobs && t.score == 1.0)); + } + #[test] fn aggregate_score_ignores_invalid_workloads() { let bad = Measurement::default(); diff --git a/src/main.rs b/src/main.rs index 95937bbb..972c7856 100644 --- a/src/main.rs +++ b/src/main.rs @@ -355,6 +355,19 @@ impl Runner<'_> { } } +/// Chunk variables an `own_calib` call set, with the value each had before it. `serve` loads several models in one +/// process; without restoring them, a model with no calibration runs with the previous model's chunk. +static CALIB_ENV: std::sync::Mutex)>> = std::sync::Mutex::new(Vec::new()); + +/// Undo the chunk variables set by the previous `own_calib` call, before a new model applies its own calibration. +fn restore_calib_env() { + let saved = std::mem::take(&mut *CALIB_ENV.lock().unwrap_or_else(|e| e.into_inner())); + for (key, old) in saved { + // SAFETY: called before a model is loaded, before any thread of that model reads these variables. + unsafe { match old { Some(v) => std::env::set_var(key, v), None => std::env::remove_var(key) } } + } +} + impl Engine { /// Hand `--backend`, `--device`, and `--kv` to the DeepSeek, GLM, Gemma 4 and Inkling 2 paths. fn ds_env(&self) { @@ -370,18 +383,25 @@ impl Engine { /// searched (they are memory choices), so this never touches the global CTX: doing that once made an explicit /// --ctx look implicit to the main engine's runner. fn own_calib(&self, model: &Path) { + restore_calib_env(); let Ok(g) = Gguf::open(model) else { return }; let arch = g.get("general.architecture").ok().and_then(|v| v.as_str()).unwrap_or(""); if !rusting_strata::config::OWN_ARCHS.contains(&arch) { return; } - let path = calibration_path(model, self.backend.as_deref().unwrap_or("cuda"), &self.device); - let (Ok(bytes), Some(&d)) = (std::fs::read(&path), self.device.first()) else { return }; + // Like `runner`, look up the file under the backend that really opened: with no --backend, CUDA may fall + // back to Vulkan, and `calibrate` writes the file under that name. + let Some(&d) = self.device.first() else { return }; + let Ok(b) = backend::open(self.backend.as_deref(), d) else { return }; + let path = calibration_path(model, b.name(), &self.device); + let Ok(bytes) = std::fs::read(&path) else { return }; let Ok(v) = serde_json::from_slice::(&bytes) else { return }; - let gpu = backend::open(self.backend.as_deref(), d).ok().map(|b| b.device().to_string()).unwrap_or_default(); + let gpu = b.device(); if !calibration_fits(&v, &gpu) { return; } if v["bytes"].as_u64().is_some_and(|n| std::fs::metadata(model).is_ok_and(|m| m.len() != n)) { return; } // GLM reads its own variable, Gemma 4 its own, the others read STRATA_DS_CHUNK. Explicit values win. if let Some(n) = v["chunk"].as_u64() { + let mut saved = CALIB_ENV.lock().unwrap_or_else(|e| e.into_inner()); for (k, value) in chunk_env_updates(n as usize, |k| std::env::var_os(k).is_some()) { + saved.push((k, std::env::var_os(k))); unsafe { std::env::set_var(k, value); } } } @@ -2522,19 +2542,43 @@ fn model_has_mtp(g: &Gguf, aux: bool) -> bool { nextn > 0 || g.meta.keys().any(|k| k.starts_with("dflash.") || k.starts_with("eagle3.")) } +/// The chunk a user gets without a calibration file. `None`: the engine prefills one token at a time and reads no +/// chunk at all, so there is no chunk to search and none to write. +fn arch_default_chunk(arch: &str) -> Option { + if arch == "gemma4" { Some(256) } + else if arch == "glm5-next" { Some(512) } + else if arch == rusting_strata::hy4::ARCH { Some(1024) } + else if rusting_strata::inkling2::is_arch(arch) { Some(256) } // its GPU prefill clamps to 256 + else if arch == "deepseek41" { None } + else { Some(4096) } +} + /// The search space. Context and KV format are deliberately absent: they are memory choices the user makes, not /// speed knobs to be silently changed by a calibration. An own-arch model only has its chunk (read from the /// environment at prefill time); main-engine models also have MTP drafts and the short-prompt threshold. fn build_space(arch: &str, s: &CalibSettings, has_mtp: bool) -> Vec { let own = rusting_strata::config::OWN_ARCHS.contains(&arch); - // A chunk larger than the context cannot be used: drop it instead of spending samples on guaranteed failures. - let mut chunks: Vec = s.chunk_values.iter().map(|n| *n as f64).filter(|&c| c <= s.ctx as f64).collect(); - if s.ctx >= 4096 && !chunks.contains(&4096.0) { chunks.push(4096.0); } // today's default is the baseline - if chunks.is_empty() { chunks.push(s.ctx as f64); } - let mut space = vec![KnobSpec::new("chunk", chunks, false)]; + let mut space = Vec::new(); + if let Some(default_chunk) = arch_default_chunk(arch) { + // A chunk larger than the context cannot be used: drop it instead of spending samples on guaranteed failures. + let mut chunks: Vec = s.chunk_values.iter().map(|n| *n as f64).filter(|&c| c <= s.ctx as f64).collect(); + // Inkling 2 clamps its GPU chunk to 256: larger values measure the same point under another label. + if rusting_strata::inkling2::is_arch(arch) { chunks.retain(|&c| c <= 256.0); } + // The engine's own default must be in the space; otherwise the baseline would be a point nobody searches. + if default_chunk <= s.ctx && !chunks.contains(&(default_chunk as f64)) { chunks.push(default_chunk as f64); } + if chunks.is_empty() { chunks.push(s.ctx.min(default_chunk) as f64); } + chunks.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)); + space.push(KnobSpec::new("chunk", chunks, false)); + } if !own { let mtp: Vec = if has_mtp { vec![0.0, 1.0, 2.0, 4.0] } else { vec![0.0] }; - let short: Vec = vec![16.0, 32.0, 64.0, 128.0]; + // `short` skips chunked prefill for prompts shorter than the threshold. The old 16/32/64/128 candidates + // never crossed a workload depth (128/512/2048), so every candidate measured the same timings. One + // threshold just above each --pp depth flips exactly that depth into the short path; 32 is the default. + let mut short: Vec = vec![32.0]; + short.extend(s.pp.iter().map(|&pp| pp.saturating_add(1) as f64)); + short.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)); + short.dedup(); debug_assert!(short.contains(&32.0)); space.push(KnobSpec::new("mtp", mtp, false)); space.push(KnobSpec::new("short", short, false)); @@ -2551,13 +2595,15 @@ fn check_workload_ctx(s: &CalibSettings) -> anyhow::Result<()> { Ok(()) } -/// The baseline must be what a user runs today without a calibration file: chunk 4096, short 32, all the physical -/// cores (left to the engine's own default), and no drafts. Not the first point of the search space. -fn baseline_knobs(space: &[KnobSpec]) -> Knobs { +/// The baseline must be what a user runs today without a calibration file: the engine's own chunk (4096 for the +/// main engine, 256/512/1024 for Gemma 4/GLM/Hy4, 256 for Inkling 2, none for DeepSeek), short 32, the physical +/// core count (left to the engine's own default), and no drafts. Not the first point of the search space. +fn baseline_knobs(space: &[KnobSpec], arch: &str) -> Knobs { let mut k = Knobs::default(); + let default_chunk = arch_default_chunk(arch).unwrap_or(4096) as f64; for s in space { let v = match s.name.as_str() { - "chunk" => 4096.0, + "chunk" => default_chunk, "short" => 32.0, "mtp" => 0.0, _ => s.values.first().copied().unwrap_or(0.0), @@ -2567,17 +2613,17 @@ fn baseline_knobs(space: &[KnobSpec]) -> Knobs { k } -/// Write the small file that later runs read, keeping every key of the v1 format. The full trace is written beside it -/// when `--out` is given, so a calibration can be audited or reproduced from its seed. -/// Readers of the calibration file use the --backend flag, or "cuda" when it is absent. Write under that same name: -/// the backend reported by a bench child (e.g. vulkan) would produce a file no run ever looks for. -fn calib_backend_name(s: &CalibSettings) -> String { - s.backend.clone().unwrap_or_else(|| "cuda".into()) +/// The backend a run will look up: the one the bench child really opened, not the `--backend` request. Without a +/// request CUDA falls back to Vulkan on some machines; writing under "cuda" would make every run miss the file. +/// The request is only a fallback when nothing was measured. +fn calib_backend_name(s: &CalibSettings, measured: &RefCell) -> String { + let real = measured.borrow().clone(); + if real.is_empty() { s.backend.clone().unwrap_or_else(|| "cuda".into()) } else { real } } /// The physical device the search measured on, for the v1 `gpu` compatibility check. -fn calib_gpu_name(s: &CalibSettings) -> String { - s.device.first().and_then(|&d| backend::open(s.backend.as_deref(), d).ok()) +fn calib_gpu_name(s: &CalibSettings, backend_name: &str) -> String { + s.device.first().and_then(|&d| backend::open(Some(backend_name), d).ok()) .map(|b| b.device().to_string()).unwrap_or_default() } @@ -2597,6 +2643,30 @@ fn drop_split(v: &mut serde_json::Value) { if let Some(o) = v.as_object_mut() { o.remove("split"); } } +/// An engine with no tunable knobs (DeepSeek reads no chunk) still gets a file: later runs stop warning and a later +/// `calibrate spec` has somewhere to put its result. Only identity and measured rates are recorded; a stale chunk +/// left by an older file of this name must not survive. +fn write_knobless_calibration(s: &CalibSettings, baseline: &[Measurement], workloads: &[Workload], arch: &str, + backend: &str, gpu: &str) -> anyhow::Result { + let path = calibration_path(&s.model, backend, &s.device); + std::fs::create_dir_all(path.parent().unwrap())?; + let mut v: serde_json::Value = std::fs::read(&path).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default(); + drop_split(&mut v); + let first = baseline.iter().find(|m| m.valid()).cloned().unwrap_or_default(); + v["schema"] = json!(2); + v["arch"] = json!(arch); + v["gpu"] = json!(gpu); + v["bytes"] = json!(std::fs::metadata(&s.model)?.len()); + v["measured"] = json!({ + "prefill_tok_s": round1(first.prefill_tok_s), + "decode_tok_s": round1(first.decode_tok_s), + }); + v["workloads"] = serde_json::to_value(workloads)?; + if let Some(o) = v.as_object_mut() { for k in ["chunk", "mtp", "short", "best", "search"] { o.remove(k); } } + std::fs::write(&path, serde_json::to_string_pretty(&v)?)?; + Ok(path) +} + fn write_calibration(s: &CalibSettings, result: &calibrate::SearchResult, workloads: &[Workload], arch: &str, backend: &str, gpu: &str) -> anyhow::Result { let path = calibration_path(&s.model, backend, &s.device); std::fs::create_dir_all(path.parent().unwrap())?; @@ -2670,21 +2740,35 @@ fn calibrate_v2(s: &CalibSettings) -> anyhow::Result<()> { say!("calibrate {arch}: {} workloads, {}-sample budget, scoring prefill and decode equally", workloads.len(), s.samples); for w in &workloads { say!(" {}", w.label()); } say!("knobs: {}", space.iter().map(|k| format!("{}=[{}]", k.name, k.values.iter().map(|v| format!("{v:.0}")).collect::>().join(","))).collect::>().join(" ")); - say!("baseline (current defaults): {}", baseline_knobs(&space).label()); + say!("baseline (current defaults): {}", baseline_knobs(&space, &arch).label()); if s.dry_run { say!("dry run: no measurements taken"); return Ok(()); } let backend = RefCell::new(String::new()); let mut measure = measure_fn(s, &backend); - let base_knobs = baseline_knobs(&space); + let base_knobs = baseline_knobs(&space, &arch); say!("baseline (current defaults): {}", base_knobs.label()); let (baseline, ok) = baseline_samples(measure(&base_knobs, &workloads)); - if !ok { say!("warning: baseline failed (e.g. OOM at chunk 4096); searching from a neutral reference"); } + if !ok { say!("warning: baseline failed (e.g. OOM at the default chunk); searching from a neutral reference"); } + let backend_name = calib_backend_name(s, &backend); + let gpu = calib_gpu_name(s, &backend_name); + if space.is_empty() { + let path = write_knobless_calibration(s, &baseline, &workloads, &arch, &backend_name, &gpu)?; + say!("{arch}: this engine reads no chunk, MTP count or short threshold; nothing to tune"); + say!("written to {}", path.display()); + return Ok(()); + } let cfg = SearchConfig { samples: s.samples, coarse: (s.samples / 3).min(8), starts: 3, patience: 2, seed: s.seed }; - let result = calibrate::search(&space, &workloads, &cfg, &Objective::balanced(), baseline, &mut measure)?; + let result = calibrate::search(&space, &workloads, &cfg, &Objective::balanced(), &base_knobs, baseline, &mut measure)?; anyhow::ensure!(result.best.error.is_none(), "no successful measurement; calibration not written"); + // The baseline competes at score 1.0, so this only happens when the baseline measurement itself failed. Never + // write a setting that cannot be shown to beat the defaults. + if result.best.score < 1.0 { + say!("best score {:.3} is below today's defaults; keeping the defaults and not writing a calibration", result.best.score); + return Ok(()); + } say!("best {}: score {:.3} vs baseline ({:.1} samples, {}, {:.1}s)", result.best.knobs.label(), result.best.score, result.samples_used, result.stop_reason, result.elapsed_ms as f64 / 1000.0); - let path = write_calibration(s, &result, &workloads, &arch, &calib_backend_name(s), &calib_gpu_name(s))?; + let path = write_calibration(s, &result, &workloads, &arch, &backend_name, &gpu)?; println!("{}\nwritten to {}", serde_json::to_string_pretty(&serde_json::from_str::(&std::fs::read_to_string(&path)?)?)?, path.display()); Ok(()) } @@ -2730,12 +2814,17 @@ fn calibrate_spec(s: &CalibSettings) -> anyhow::Result<()> { if s.dry_run { say!("dry run: no measurements taken"); return Ok(()); } let backend = RefCell::new(String::new()); let mut measure = measure_fn(s, &backend); - let (baseline, ok) = baseline_samples(measure(&spec_baseline(s), &workloads)); + let base = spec_baseline(s); + let (baseline, ok) = baseline_samples(measure(&base, &workloads)); if !ok { say!("warning: baseline failed; searching from a neutral reference"); } - say!("baseline (current defaults): {}", spec_baseline(s).label()); + say!("baseline (current defaults): {}", base.label()); let cfg = SearchConfig { samples: s.samples, coarse: (s.samples / 3).min(8), starts: 3, patience: 2, seed: s.seed }; - let result = calibrate::search(&space, &workloads, &cfg, &Objective::balanced(), baseline, &mut measure)?; + let result = calibrate::search(&space, &workloads, &cfg, &Objective::balanced(), &base, baseline, &mut measure)?; anyhow::ensure!(result.best.error.is_none(), "no successful spec measurement; calibration not written"); + if result.best.score < 1.0 { + say!("best spec score {:.3} is below today's defaults; keeping the defaults and not writing a spec section", result.best.score); + return Ok(()); + } let idx = |name: &str, len: usize| result.best.knobs.i(name).unwrap_or(0).min(len.saturating_sub(1)); let mut spec = serde_json::Map::new(); for (i, w) in workloads.iter().enumerate() { @@ -2750,7 +2839,8 @@ fn calibrate_spec(s: &CalibSettings) -> anyhow::Result<()> { "acceptance_pct": share, })); } - let path = write_spec_calibration(s, &result, &arch, &calib_backend_name(s), &calib_gpu_name(s), &serde_json::Value::Object(spec))?; + let backend_name = calib_backend_name(s, &backend); + let path = write_spec_calibration(s, &result, &arch, &backend_name, &calib_gpu_name(s, &backend_name), &serde_json::Value::Object(spec))?; say!("spec sweep written to {}", path.display()); Ok(()) } @@ -4276,9 +4366,13 @@ mod calibrate_cli_tests { #[test] fn the_calibration_file_is_named_like_the_reader_looks_for_it() { let mut s = CalibSettings::new(PathBuf::from("m.gguf")); - assert_eq!(calib_backend_name(&s), "cuda"); - s.backend = Some("vulkan".into()); - assert_eq!(calib_backend_name(&s), "vulkan"); + let measured = RefCell::new(String::new()); + assert_eq!(calib_backend_name(&s, &measured), "cuda"); + // CUDA requested but Vulkan really opened: runs look for the Vulkan file, so that is where we write. + *measured.borrow_mut() = "vulkan".into(); + assert_eq!(calib_backend_name(&s, &measured), "vulkan"); + s.backend = Some("cuda".into()); + assert_eq!(calib_backend_name(&s, &measured), "vulkan"); } #[test] @@ -4309,6 +4403,18 @@ mod calibrate_cli_tests { assert!(chunk_env_updates(512, |_| true).is_empty()); } + #[test] + fn calibration_chunk_environment_is_restored_for_the_next_model() { + const KEY: &str = "STRATA_TEST_CALIB_RESTORE"; + let original = std::env::var_os(KEY); + unsafe { std::env::remove_var(KEY) } + CALIB_ENV.lock().unwrap().push((KEY, original.clone())); + unsafe { std::env::set_var(KEY, "256") } + assert_eq!(std::env::var_os(KEY).as_deref(), Some(std::ffi::OsStr::new("256"))); + restore_calib_env(); + assert_eq!(std::env::var_os(KEY), original, "the next model must not inherit this chunk"); + } + #[test] fn workloads_must_fit_the_context_being_measured() { let mut s = CalibSettings::new(PathBuf::from("m.gguf")); @@ -4416,7 +4522,7 @@ mod calibrate_cli_tests { let main = build_space("qwen35moe", &s, true); let names: Vec<_> = main.iter().map(|k| k.name.as_str()).collect(); assert_eq!(names, vec!["chunk", "mtp", "short"]); - let base = baseline_knobs(&main); + let base = baseline_knobs(&main, "qwen35moe"); assert_eq!((base.i("chunk"), base.i("mtp"), base.i("short")), (Some(4096), Some(0), Some(32))); // No MTP head: don't spend samples on drafts that the engine cannot use. @@ -4441,6 +4547,38 @@ mod calibrate_cli_tests { assert!(build_space("qwen35moe", &s, true)[0].values.contains(&4096.0)); } + #[test] + fn the_baseline_chunk_is_each_engines_own_default() { + let s = CalibSettings::new(PathBuf::from("m.gguf")); + for (arch, want) in [("gemma4", 256), ("glm5-next", 512), ("hy_v4_flash", 1024), + ("inkling2_loop", 256), ("inkling2", 256), ("qwen35moe", 4096)] { + let space = build_space(arch, &s, true); + let base = baseline_knobs(&space, arch); + assert_eq!(base.i("chunk"), Some(want), "{arch}"); + assert!(space[0].values.contains(&(want as f64)), "{arch} baseline must be searchable"); + } + // DeepSeek prefills one token at a time: there is no chunk to search or write. + assert!(build_space("deepseek41", &s, true).is_empty()); + assert_eq!(arch_default_chunk("deepseek41"), None); + } + + #[test] + fn inkling_chunks_larger_than_its_gpu_cap_are_not_searched() { + let s = CalibSettings::new(PathBuf::from("m.gguf")); + let space = build_space("inkling2_loop", &s, false); + assert!(space[0].values.iter().all(|&c| c <= 256.0), "{:?}", space[0].values); + } + + #[test] + fn short_candidates_cross_the_workload_depths() { + let s = CalibSettings::new(PathBuf::from("m.gguf")); + let space = build_space("qwen35moe", &s, true); + let short = &space.last().unwrap().values; + assert_eq!(short, &vec![32.0, 129.0, 513.0, 2049.0]); + // Every threshold above its depth makes that workload take the short path; none is inert. + for &pp in &s.pp { assert!(short.iter().any(|&t| t > pp as f64 && t <= (pp + 1) as f64)); } + } + #[test] fn spec_baseline_uses_current_defaults_not_first_list_values() { let mut s = CalibSettings::new(PathBuf::from("m.gguf")); From c216701a7fdc8102a28605acdb91b7a86df4e8c6 Mon Sep 17 00:00:00 2001 From: sayampy Date: Wed, 25 Nov 2026 00:23:20 +0530 Subject: [PATCH 051/515] calibrate: keep upstream --device validation in the rebased search paths --- src/main.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main.rs b/src/main.rs index 972c7856..498d5305 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2728,6 +2728,7 @@ fn write_spec_calibration(s: &CalibSettings, result: &calibrate::SearchResult, a /// The universal calibration workflow. Every supported architecture goes through here; the measurement is delegated /// to `bench`, so there is no arch-specific timing code to keep in sync. fn calibrate_v2(s: &CalibSettings) -> anyhow::Result<()> { + backend::check_devices(s.backend.as_deref(), &s.device)?; // before the GGUF is read: a bad --device fails here check_workload_ctx(s)?; let g = Gguf::open(&s.model)?; let arch = g.get("general.architecture").ok().and_then(|v| v.as_str()).unwrap_or("unknown").to_string(); @@ -2805,6 +2806,7 @@ fn spec_baseline(s: &CalibSettings) -> Knobs { /// The `spec` subcommand: one task-specific sweep of speculative settings, written under `spec` in the calibration /// file. It uses the same budgeted search, with each task as its own workload so acceptance can differ by corpus. fn calibrate_spec(s: &CalibSettings) -> anyhow::Result<()> { + backend::check_devices(s.backend.as_deref(), &s.device)?; check_workload_ctx(s)?; let g = Gguf::open(&s.model)?; let arch = g.get("general.architecture").ok().and_then(|v| v.as_str()).unwrap_or("unknown").to_string(); From 1023c5cedca9033e7369b44101e0b55b39a9e3b2 Mon Sep 17 00:00:00 2001 From: Wateir Date: Tue, 24 Nov 2026 21:55:32 +0100 Subject: [PATCH 052/515] feat: Add Latex on the webapp --- src/main.rs | 10 +++++++ src/serve.rs | 27 ++++++++++++++++++ src/web/index.html | 26 +++++++++++++++-- src/web/katex/fonts/KaTeX_AMS-Regular.woff2 | Bin 0 -> 28076 bytes .../katex/fonts/KaTeX_Caligraphic-Bold.woff2 | Bin 0 -> 6912 bytes .../fonts/KaTeX_Caligraphic-Regular.woff2 | Bin 0 -> 6908 bytes src/web/katex/fonts/KaTeX_Fraktur-Bold.woff2 | Bin 0 -> 11348 bytes .../katex/fonts/KaTeX_Fraktur-Regular.woff2 | Bin 0 -> 11316 bytes src/web/katex/fonts/KaTeX_Main-Bold.woff2 | Bin 0 -> 25324 bytes .../katex/fonts/KaTeX_Main-BoldItalic.woff2 | Bin 0 -> 16780 bytes src/web/katex/fonts/KaTeX_Main-Italic.woff2 | Bin 0 -> 16988 bytes src/web/katex/fonts/KaTeX_Main-Regular.woff2 | Bin 0 -> 26272 bytes .../katex/fonts/KaTeX_Math-BoldItalic.woff2 | Bin 0 -> 16400 bytes src/web/katex/fonts/KaTeX_Math-Italic.woff2 | Bin 0 -> 16440 bytes .../katex/fonts/KaTeX_SansSerif-Bold.woff2 | Bin 0 -> 12216 bytes .../katex/fonts/KaTeX_SansSerif-Italic.woff2 | Bin 0 -> 12028 bytes .../katex/fonts/KaTeX_SansSerif-Regular.woff2 | Bin 0 -> 10344 bytes .../katex/fonts/KaTeX_Script-Regular.woff2 | Bin 0 -> 9644 bytes src/web/katex/fonts/KaTeX_Size1-Regular.woff2 | Bin 0 -> 5468 bytes src/web/katex/fonts/KaTeX_Size2-Regular.woff2 | Bin 0 -> 5208 bytes src/web/katex/fonts/KaTeX_Size3-Regular.woff2 | Bin 0 -> 3624 bytes src/web/katex/fonts/KaTeX_Size4-Regular.woff2 | Bin 0 -> 4928 bytes .../fonts/KaTeX_Typewriter-Regular.woff2 | Bin 0 -> 13568 bytes src/web/katex/katex.min.css | 1 + src/web/katex/katex.min.js | 1 + 25 files changed, 63 insertions(+), 2 deletions(-) create mode 100644 src/web/katex/fonts/KaTeX_AMS-Regular.woff2 create mode 100644 src/web/katex/fonts/KaTeX_Caligraphic-Bold.woff2 create mode 100644 src/web/katex/fonts/KaTeX_Caligraphic-Regular.woff2 create mode 100644 src/web/katex/fonts/KaTeX_Fraktur-Bold.woff2 create mode 100644 src/web/katex/fonts/KaTeX_Fraktur-Regular.woff2 create mode 100644 src/web/katex/fonts/KaTeX_Main-Bold.woff2 create mode 100644 src/web/katex/fonts/KaTeX_Main-BoldItalic.woff2 create mode 100644 src/web/katex/fonts/KaTeX_Main-Italic.woff2 create mode 100644 src/web/katex/fonts/KaTeX_Main-Regular.woff2 create mode 100644 src/web/katex/fonts/KaTeX_Math-BoldItalic.woff2 create mode 100644 src/web/katex/fonts/KaTeX_Math-Italic.woff2 create mode 100644 src/web/katex/fonts/KaTeX_SansSerif-Bold.woff2 create mode 100644 src/web/katex/fonts/KaTeX_SansSerif-Italic.woff2 create mode 100644 src/web/katex/fonts/KaTeX_SansSerif-Regular.woff2 create mode 100644 src/web/katex/fonts/KaTeX_Script-Regular.woff2 create mode 100644 src/web/katex/fonts/KaTeX_Size1-Regular.woff2 create mode 100644 src/web/katex/fonts/KaTeX_Size2-Regular.woff2 create mode 100644 src/web/katex/fonts/KaTeX_Size3-Regular.woff2 create mode 100644 src/web/katex/fonts/KaTeX_Size4-Regular.woff2 create mode 100644 src/web/katex/fonts/KaTeX_Typewriter-Regular.woff2 create mode 100644 src/web/katex/katex.min.css create mode 100644 src/web/katex/katex.min.js diff --git a/src/main.rs b/src/main.rs index 4c20e0a2..e2d39f42 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1704,6 +1704,16 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { oc.fetch_sub(1, Relaxed); return; } + // The KaTeX files of the page (math in replies), under /katex/ with the same checks as the page. + // The files never change with the server running, so the browser may keep them. + Ok(r) if r.method == "GET" && (k.read().unwrap().any() || serve::host_ok(&r.host, &a, &allowed)) + && let Some(file) = r.path.strip_prefix("/katex/") + && let Some((_, ty, b)) = serve::KATEX.iter().find(|&(n, _, _)| n == file) => { + let _ = write!(&c, "HTTP/1.1 200 OK\r\nContent-Type: {ty}\r\nCache-Control: max-age=31536000, immutable\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", b.len()); + let _ = c.write_all(b); + oc.fetch_sub(1, Relaxed); + return; + } Ok(_) if who.is_none() => return reply(json!({"error": {"message": "missing or wrong API key", "type": "invalid_api_key"}}), "401 Unauthorized"), // Clients list the models often; a model still loading is listed, as its chats wait for the load. diff --git a/src/serve.rs b/src/serve.rs index e72706b9..595d82f3 100644 --- a/src/serve.rs +++ b/src/serve.rs @@ -132,6 +132,33 @@ pub fn held(c: &mut impl std::io::Write, last: &mut std::time::Instant) -> bool /// The chat page of `serve`. pub const PAGE: &str = include_str!("web/index.html"); +/// The KaTeX files the chat page needs to show math in replies, by the path they are served at. Embedded like the +/// page itself, so the server stays one file that works without the network. +pub const KATEX: &[(&str, &str, &[u8])] = &[ + ("katex.min.js", "application/javascript; charset=utf-8", include_bytes!("web/katex/katex.min.js")), + ("katex.min.css", "text/css; charset=utf-8", include_bytes!("web/katex/katex.min.css")), + ("fonts/KaTeX_AMS-Regular.woff2", "font/woff2", include_bytes!("web/katex/fonts/KaTeX_AMS-Regular.woff2")), + ("fonts/KaTeX_Caligraphic-Bold.woff2", "font/woff2", include_bytes!("web/katex/fonts/KaTeX_Caligraphic-Bold.woff2")), + ("fonts/KaTeX_Caligraphic-Regular.woff2", "font/woff2", include_bytes!("web/katex/fonts/KaTeX_Caligraphic-Regular.woff2")), + ("fonts/KaTeX_Fraktur-Bold.woff2", "font/woff2", include_bytes!("web/katex/fonts/KaTeX_Fraktur-Bold.woff2")), + ("fonts/KaTeX_Fraktur-Regular.woff2", "font/woff2", include_bytes!("web/katex/fonts/KaTeX_Fraktur-Regular.woff2")), + ("fonts/KaTeX_Main-Bold.woff2", "font/woff2", include_bytes!("web/katex/fonts/KaTeX_Main-Bold.woff2")), + ("fonts/KaTeX_Main-BoldItalic.woff2", "font/woff2", include_bytes!("web/katex/fonts/KaTeX_Main-BoldItalic.woff2")), + ("fonts/KaTeX_Main-Italic.woff2", "font/woff2", include_bytes!("web/katex/fonts/KaTeX_Main-Italic.woff2")), + ("fonts/KaTeX_Main-Regular.woff2", "font/woff2", include_bytes!("web/katex/fonts/KaTeX_Main-Regular.woff2")), + ("fonts/KaTeX_Math-BoldItalic.woff2", "font/woff2", include_bytes!("web/katex/fonts/KaTeX_Math-BoldItalic.woff2")), + ("fonts/KaTeX_Math-Italic.woff2", "font/woff2", include_bytes!("web/katex/fonts/KaTeX_Math-Italic.woff2")), + ("fonts/KaTeX_SansSerif-Bold.woff2", "font/woff2", include_bytes!("web/katex/fonts/KaTeX_SansSerif-Bold.woff2")), + ("fonts/KaTeX_SansSerif-Italic.woff2", "font/woff2", include_bytes!("web/katex/fonts/KaTeX_SansSerif-Italic.woff2")), + ("fonts/KaTeX_SansSerif-Regular.woff2", "font/woff2", include_bytes!("web/katex/fonts/KaTeX_SansSerif-Regular.woff2")), + ("fonts/KaTeX_Script-Regular.woff2", "font/woff2", include_bytes!("web/katex/fonts/KaTeX_Script-Regular.woff2")), + ("fonts/KaTeX_Size1-Regular.woff2", "font/woff2", include_bytes!("web/katex/fonts/KaTeX_Size1-Regular.woff2")), + ("fonts/KaTeX_Size2-Regular.woff2", "font/woff2", include_bytes!("web/katex/fonts/KaTeX_Size2-Regular.woff2")), + ("fonts/KaTeX_Size3-Regular.woff2", "font/woff2", include_bytes!("web/katex/fonts/KaTeX_Size3-Regular.woff2")), + ("fonts/KaTeX_Size4-Regular.woff2", "font/woff2", include_bytes!("web/katex/fonts/KaTeX_Size4-Regular.woff2")), + ("fonts/KaTeX_Typewriter-Regular.woff2", "font/woff2", include_bytes!("web/katex/fonts/KaTeX_Typewriter-Regular.woff2")), +]; + /// What a chat of a model outside the main engine did, for the server's log and statistics. pub struct Done { pub prompt: usize, pub cached: usize, pub completion: usize, pub prefill_s: f64, pub finish: &'static str } diff --git a/src/web/index.html b/src/web/index.html index aa836c79..1797ca5f 100644 --- a/src/web/index.html +++ b/src/web/index.html @@ -5,6 +5,8 @@ RustingStrata + +