From 1d4c5721ceb653e1639aa105b6fbb0c943f3ab33 Mon Sep 17 00:00:00 2001 From: SubgridAI Date: Sun, 6 Dec 2026 07:34:19 +0000 Subject: [PATCH 1/6] prefill: pipeline the chunks of a prompt over the parts of a --device split A --device split ran prefill chunk by chunk through every part in turn, so with N cards each was busy about 1/N of the time. Now each part runs on its own thread and starts chunk k + 1 as soon as it has handed chunk k on, so the cards work on different chunks at once. Each part reads only its own layers' state from the chunks before, and takes the chunks in order, so the result is the sequential loop's. Taken for one request (--parallel 1), a text prompt of two or more chunks, no STRATA_PF_ADAPT, no DFlash draft. STRATA_PF_PIPE=0 keeps the sequential loop. Co-Authored-By: Claude Opus 5.5 --- src/gpu_model/prefill.rs | 92 +++++++++++++++++++++++++++++++++++++--- 1 file changed, 87 insertions(+), 5 deletions(-) diff --git a/src/gpu_model/prefill.rs b/src/gpu_model/prefill.rs index 89ca4587..8c9a5b02 100644 --- a/src/gpu_model/prefill.rs +++ b/src/gpu_model/prefill.rs @@ -210,11 +210,15 @@ impl GpuModel<'_> { // so the later chunks run with the placement the first ones showed (0 = off, the default; untested on real hardware). let every = std::env::var("STRATA_PF_ADAPT").ok().and_then(|v| v.parse::().ok()).unwrap_or(0); let nchunks = tokens.len().div_ceil(chunk); - for (i, ch) in tokens.chunks(chunk).enumerate() { - if i > 0 { let cur = self.cur; between(self)?; self.use_slot(cur); } - self.prefill_chunk(ch, None, None)?; - crate::term::prefilled(ch.len()); - if every > 0 && (i + 1) % every == 0 && i + 1 < nchunks { self.adapt_experts()?; } + if self.pipe_ok(every, nchunks) { + self.prefill_pipelined(tokens, chunk)?; + } else { + for (i, ch) in tokens.chunks(chunk).enumerate() { + if i > 0 { let cur = self.cur; between(self)?; self.use_slot(cur); } + self.prefill_chunk(ch, None, None)?; + crate::term::prefilled(ch.len()); + if every > 0 && (i + 1) % every == 0 && i + 1 < nchunks { self.adapt_experts()?; } + } } // The prompt's routing predicts the reply's: place its hot experts now instead of 64 per adapt during decode. self.adapt_experts()?; @@ -232,6 +236,73 @@ impl GpuModel<'_> { g.get::(&s.logits, 0, s.m.cfg.n_vocab) } + /// Whether `prefill_with` may pipeline this prompt over the parts of a `--device` split: one request + /// (`--parallel 1`, so `between` has no other slot to decode), a text prompt of two or more chunks, no + /// `STRATA_PF_ADAPT`, no DFlash draft. `STRATA_PF_PIPE=0` turns it off. + fn pipe_ok(&self, every: usize, nchunks: usize) -> bool { + self.next.is_some() && nchunks > 1 && every == 0 && self.slots() == 1 && self.pf_mrope.is_none() + && self.parts().all(|p| p.dflash.is_none() && p.pf.is_some()) + && std::env::var("STRATA_PF_PIPE").map_or(true, |v| v != "0") + } + + /// Pipelined prefill over a `--device` split: each part runs on its own thread, and a part starts chunk k + 1 + /// as soon as it has handed chunk k to the next part, so the devices compute different chunks at the same time + /// instead of taking turns. Each part reads only its own layers' state (KV, recurrent state) from the chunks + /// before, and it takes the chunks in order, so the result is the same as the sequential loop's. + fn prefill_pipelined(&mut self, tokens: &[u32], chunk: usize) -> anyhow::Result<()> { + use std::sync::mpsc::sync_channel; + type Hand = (usize, Vec, Vec); + // Detach the parts after this one, so that each can be lent to its own thread; reattached below. + let ro = self.rope_offset; + let mut rest: Vec> = Vec::new(); + let mut nx = self.next.take(); + while let Some(mut b) = nx { nx = b.next.take(); b.rope_offset = ro; rest.push(b); } + let n = rest.len(); + let res = std::thread::scope(|sc| -> anyhow::Result<()> { + let (mut txs, mut rxs) = (Vec::with_capacity(n), Vec::with_capacity(n)); + for _ in 0..n { let (tx, rx) = sync_channel::(1); txs.push(Some(tx)); rxs.push(Some(rx)); } + let head_tx = txs[0].take().unwrap(); + let mut handles = Vec::with_capacity(n); + for (i, part) in rest.iter_mut().enumerate() { + let rx = rxs[i].take().unwrap(); + let tx = txs.get_mut(i + 1).and_then(Option::take); + handles.push(sc.spawn(move || -> anyhow::Result<()> { + for (ci, xs, pe) in rx { + let ch = &tokens[ci * chunk..((ci + 1) * chunk).min(tokens.len())]; + match &tx { + Some(tx) => { + let mut out = (Vec::new(), Vec::new()); + part.prefill_chunk_to(ch, Some((&xs, &pe)), None, Some(&mut out))?; + if tx.send((ci, out.0, out.1)).is_err() { break; } + } + None => { + part.prefill_chunk_to(ch, Some((&xs, &pe)), None, None)?; + crate::term::prefilled(ch.len()); + } + } + } + Ok(()) + })); + } + let mut r = Ok(()); + for (ci, ch) in tokens.chunks(chunk).enumerate() { + let mut out = (Vec::new(), Vec::new()); + if let Err(e) = self.prefill_chunk_to(ch, None, None, Some(&mut out)) { r = Err(e); break; } + if head_tx.send((ci, out.0, out.1)).is_err() { break; } + } + drop(head_tx); + for h in handles { + let hr = h.join().unwrap_or_else(|_| Err(anyhow::anyhow!("prefill pipeline: a device thread panicked"))); + if r.is_ok() { r = hr; } + } + r + }); + let mut acc = None; + for mut b in rest.into_iter().rev() { b.next = acc; acc = Some(b); } + self.next = acc; + res + } + /// Image rows of a prompt in one batched forward, up to a chunk. Returns how many rows it ran: 0 when this model /// has no batched prefill for them, and never `ids`' last row (the caller takes that row's logits from /// `step_embed`). @@ -461,6 +532,13 @@ impl GpuModel<'_> { /// slot, and the attention splits. Row r runs at the position in `Batch::step` on its own slot's state, the KV /// through `Batch::kvt`; the hidden rows are left in the slab, and no position moves. fn prefill_chunk(&mut self, toks: &[u32], input: Option<(&[f32], &[f32])>, rows: Option<(&[usize], usize)>) -> anyhow::Result<()> { + self.prefill_chunk_to(toks, input, rows, None) + } + + /// `prefill_chunk` on this part only. With `out`, the hidden rows and PLE input this part leaves for the next + /// part are returned there instead of being handed to `next` (the pipelined prefill hands them on itself). + fn prefill_chunk_to(&mut self, toks: &[u32], input: Option<(&[f32], &[f32])>, rows: Option<(&[usize], usize)>, + out: Option<&mut (Vec, Vec)>) -> anyhow::Result<()> { self.dflash_commit_ctx()?; if let Some((_, first)) = &self.pf_mrope { if self.pf_mrope_buf.is_none() { self.pf_mrope_buf = Some(self.gpu.zeros::(8 * self.pf.as_ref().unwrap().chunk)?); } @@ -1234,6 +1312,10 @@ impl GpuModel<'_> { df.pend_ctx = 0; } self.pos += toks.len(); + if let Some(o) = out { + *o = (self.gpu.get::(&self.pf.as_ref().unwrap().slab, 0, toks.len() * d)?, pe.to_vec()); + return Ok(()); + } let Some(nx) = self.next.as_deref_mut() else { return Ok(()) }; (nx.rope_offset, nx.pf_mrope) = (self.rope_offset, self.pf_mrope.clone()); let xs = self.gpu.get::(&self.pf.as_ref().unwrap().slab, 0, toks.len() * d)?; From 8c5c9692ae138c883ba56d6a6c12e0f0ce8be9f1 Mon Sep 17 00:00:00 2001 From: SubgridAI Date: Sun, 6 Dec 2026 07:34:19 +0000 Subject: [PATCH 2/6] STRATA_PF_PROF=1: per-part prefill component timing One line per part per chunk: total and in / pre / delta / attn_proj / qsa_idx / qsa_sel (score) / attn / post / moe / tail / out, and the pipeline waits for the part before and after. Each mark syncs the part's streams, so it removes the overlap inside a part (not between parts); profiling runs come out a few percent slower. Off: no syncs, no cost. Co-Authored-By: Claude Opus 5.5 --- src/cuda/mod.rs | 4 ++ src/gpu_model.rs | 1 + src/gpu_model/pf_prof.rs | 91 ++++++++++++++++++++++++++++++++++++++++ src/gpu_model/prefill.rs | 31 ++++++++++++-- 4 files changed, 124 insertions(+), 3 deletions(-) create mode 100644 src/gpu_model/pf_prof.rs diff --git a/src/cuda/mod.rs b/src/cuda/mod.rs index 989c3f11..c9275885 100644 --- a/src/cuda/mod.rs +++ b/src/cuda/mod.rs @@ -2055,7 +2055,11 @@ impl Backend for Gpu { } 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<()> { + let prof = crate::gpu_model::pf_prof::active(); + if prof { self.wait()?; } + let t0 = std::time::Instant::now(); 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); + if prof { self.wait()?; crate::gpu_model::pf_prof::add_score(t0.elapsed().as_secs_f64()); } 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(()) } diff --git a/src/gpu_model.rs b/src/gpu_model.rs index 8df4c0fd..6d199f42 100644 --- a/src/gpu_model.rs +++ b/src/gpu_model.rs @@ -39,6 +39,7 @@ fn gq_min(pos: usize, nt: usize) -> i32 { mod host_share; mod prefill; +pub mod pf_prof; use host_share::{HOST_BLOCKS, HostShare}; diff --git a/src/gpu_model/pf_prof.rs b/src/gpu_model/pf_prof.rs new file mode 100644 index 00000000..843dfe05 --- /dev/null +++ b/src/gpu_model/pf_prof.rs @@ -0,0 +1,91 @@ +//! `STRATA_PF_PROF=1`: per-part prefill timing for profiling builds. Each `mark` waits for every stream of the part's +//! GPU and books the wall time since the previous mark to one component, so the components add up to the part's +//! chunk time (the waits remove the overlap inside a part, not between parts). One line per part per chunk. +//! Off (the default) it costs one cached env check per call. + +use std::cell::Cell; +use std::sync::LazyLock; +use std::time::Instant; + +static ON: LazyLock = LazyLock::new(|| std::env::var("STRATA_PF_PROF").is_ok_and(|v| !v.is_empty() && v != "0")); + +pub fn on() -> bool { *ON } + +/// Whether this thread is inside a profiled prefill chunk (decode may be under graph capture: no waits there). +pub fn active() -> bool { ACTIVE.with(|c| c.get()) } + +thread_local! { + static ACTIVE: Cell = const { Cell::new(false) }; + static SCORE: Cell = const { Cell::new(0.0) }; + static WAIT_IN: Cell = const { Cell::new(0.0) }; + static WAIT_OUT: Cell = const { Cell::new(0.0) }; +} + +/// `qsa_score` time inside `qsa_select` (the CUDA backend books it here). +pub fn add_score(s: f64) { SCORE.with(|c| c.set(c.get() + s)); } +/// Pipeline waits of this thread: for the part before (`recv`) and for the part after (`send`). +pub fn add_wait(recv: f64, send: f64) { + WAIT_IN.with(|c| c.set(c.get() + recv)); + WAIT_OUT.with(|c| c.set(c.get() + send)); +} + +pub const IN: usize = 0; +pub const PRE: usize = 1; +pub const DELTA: usize = 2; +pub const ATTN_PROJ: usize = 3; +pub const QSA_IDX: usize = 4; +pub const QSA_SEL: usize = 5; +pub const ATTN: usize = 6; +pub const POST: usize = 7; +pub const MOE: usize = 8; +pub const TAIL: usize = 9; +pub const OUT: usize = 10; +const N: usize = 11; +const NAMES: [&str; N] = ["in", "pre", "delta", "attn_proj", "qsa_idx", "qsa_sel", "attn", "post", "moe", "tail", "out"]; + +pub struct Pp { + on: bool, + start: Instant, + last: Instant, + acc: [f64; N], +} + +impl Drop for Pp { + fn drop(&mut self) { if self.on { ACTIVE.with(|c| c.set(false)); } } +} + +impl Pp { + pub fn new(g: &dyn crate::backend::Backend) -> anyhow::Result { + let on = on(); + if on { + g.sync_freed()?; + SCORE.with(|c| c.set(0.0)); + ACTIVE.with(|c| c.set(true)); + } + let now = Instant::now(); + Ok(Pp { on, start: now, last: now, acc: [0.0; N] }) + } + + pub fn mark(&mut self, g: &dyn crate::backend::Backend, cat: usize) -> anyhow::Result<()> { + if !self.on { return Ok(()); } + g.sync_freed()?; + let now = Instant::now(); + self.acc[cat] += (now - self.last).as_secs_f64(); + self.last = now; + Ok(()) + } + + /// Print the chunk's line: part (first layer), chunk start position, tokens, total and each component in ms. + pub fn report(&self, first: usize, pos: usize, t: usize) { + if !self.on { return; } + let score = SCORE.with(|c| c.replace(0.0)); + let (wi, wo) = (WAIT_IN.with(|c| c.replace(0.0)), WAIT_OUT.with(|c| c.replace(0.0))); + let mut s = format!("pf_prof part L{first} pos {pos} t {t} total {:.1}", (self.last - self.start).as_secs_f64() * 1e3); + for (i, name) in NAMES.iter().enumerate() { + s += &format!(" {name} {:.1}", self.acc[i] * 1e3); + if i == QSA_SEL { s += &format!(" (score {:.1})", score * 1e3); } + } + s += &format!(" | wait_prev {:.1} wait_next {:.1}", wi * 1e3, wo * 1e3); + crate::say!("{s}"); + } +} diff --git a/src/gpu_model/prefill.rs b/src/gpu_model/prefill.rs index 8c9a5b02..94f2953c 100644 --- a/src/gpu_model/prefill.rs +++ b/src/gpu_model/prefill.rs @@ -8,6 +8,7 @@ use crate::backend::{BATCHED, Backend, Buf, GEMM_BM, MOE_GATE_X, SAME_X}; use crate::expert_cache::{ExpertCache, MATS}; use crate::model::Model; use crate::weights::Prefetch; +use super::pf_prof::{self, Pp}; /// Experts staged per group when a layer routes to experts outside the cache. Staging holds three groups. const STAGE: usize = 16; @@ -267,13 +268,19 @@ impl GpuModel<'_> { let rx = rxs[i].take().unwrap(); let tx = txs.get_mut(i + 1).and_then(Option::take); handles.push(sc.spawn(move || -> anyhow::Result<()> { - for (ci, xs, pe) in rx { + let mut rx = rx.into_iter(); + loop { + let tw = std::time::Instant::now(); + let Some((ci, xs, pe)) = rx.next() else { break }; + pf_prof::add_wait(tw.elapsed().as_secs_f64(), 0.0); let ch = &tokens[ci * chunk..((ci + 1) * chunk).min(tokens.len())]; match &tx { Some(tx) => { let mut out = (Vec::new(), Vec::new()); part.prefill_chunk_to(ch, Some((&xs, &pe)), None, Some(&mut out))?; + let tw = std::time::Instant::now(); if tx.send((ci, out.0, out.1)).is_err() { break; } + pf_prof::add_wait(0.0, tw.elapsed().as_secs_f64()); } None => { part.prefill_chunk_to(ch, Some((&xs, &pe)), None, None)?; @@ -288,7 +295,9 @@ impl GpuModel<'_> { for (ci, ch) in tokens.chunks(chunk).enumerate() { let mut out = (Vec::new(), Vec::new()); if let Err(e) = self.prefill_chunk_to(ch, None, None, Some(&mut out)) { r = Err(e); break; } + let tw = std::time::Instant::now(); if head_tx.send((ci, out.0, out.1)).is_err() { break; } + pf_prof::add_wait(0.0, tw.elapsed().as_secs_f64()); } drop(head_tx); for h in handles { @@ -561,6 +570,8 @@ impl GpuModel<'_> { let pf = self.pf.as_ref().unwrap(); let (g, mut t, n, eps, ne) = (&self.gpu, toks.len(), pf.chunk, c.eps, c.n_embd); let d = c.hc_n.max(1) * ne; + let mut pp = Pp::new(&**g)?; + let pos0 = self.pos; g.put(emb, &pf.slab, 0)?; if !pe.is_empty() { g.put(pe, &pf.slab, pf.lay.emb)?; } g.put(&[self.pos as i32, 0], &self.step_buf, 0)?; @@ -568,6 +579,7 @@ impl GpuModel<'_> { let mut step = self.step_buf.addr(); let mut rope = self.rope_buf.addr(); if rows.is_some() { step = self.bt.as_ref().unwrap().step.addr(); } + pp.mark(&**g, pf_prof::IN)?; let base = pf.slab.addr(); let at = |o: usize| base + 4 * o as u64; let l = &pf.lay; @@ -740,6 +752,7 @@ impl GpuModel<'_> { } } if dense.is_some() { rot(h, ne, 0, t)?; } + pp.mark(&**g, pf_prof::PRE)?; match &ly.mixer { Mixer::Delta { qkv, gate, beta, alpha, dt_bias, a, conv_w, norm, out, conv, s, .. } => { let (eb, eg) = (at(l.e), at(l.e + n * nv)); @@ -803,6 +816,7 @@ impl GpuModel<'_> { if ly.hc.is_some() { g.norm_gate_sig(at(l.d), norm.ptr, at(l.b), dv, t * nv, eps, 0)?; } else { g.norm_gate(at(l.d), norm.ptr, at(l.b), dv, t * nv, eps)?; } let perm = self.bufs.get("hperm").map_or(0, |b| b.addr()); g.gemm_dense(out, t, rot(at(l.d), c.ssm_d_inner, perm, t)?, c.ssm_d_inner, mx, ne, mact | bf)?; + pp.mark(&**g, pf_prof::DELTA)?; } Mixer::Attn { q, k, v, qn, kn, o, sink, .. } if let Some((_, splits)) = rows => { // As `batch_rows` on a dense model: each row reads and extends its own slot's KV. @@ -831,6 +845,7 @@ impl GpuModel<'_> { g.rms_norm(kraw, hd, kn.ptr, kk, hd, hd, t * nkv, eps)?; if use_rope { self.rope_chunk(kk, hd, t, nkv, rope)?; } g.kv_store(kk, vv, kc[self.cur].addr(), vc[self.cur].addr(), kv, t, step, hd)?; + pp.mark(&**g, pf_prof::ATTN_PROJ)?; // QSA: region c (free after kv_store) holds the raw indexer keys, raw queries and normed queries. let (qm, mw) = match (qsa, &self.qsa) { (Some(a), Some(b)) => { @@ -843,12 +858,14 @@ impl GpuModel<'_> { if self.pos + t >= super::QSA_POOL * (b.top + 1) { g.rms_norm(iq, dq, a.qn.ptr, iqn, dq, dq, t * super::QSA_H, eps)?; g.rope_neox(iqn, dq, t * super::QSA_H, super::QSA_H, c.n_rot, rope, c.rope_base)?; + pp.mark(&**g, pf_prof::QSA_IDX)?; for r0 in (0..t).step_by(super::QSA_ROWS) { g.qsa_select(iqn + (4 * r0 * nq) as u64, a.pool[self.cur].addr(), b.score.addr(), 0, b.mask.addr() + (4 * r0 * b.mw) as u64, step, r0, super::QSA_ROWS.min(t - r0), b.nbs, b.top, 0, b.mw)?; } + pp.mark(&**g, pf_prof::QSA_SEL)?; (b.mask.addr(), b.mw) - } else { (0, 0) } + } else { pp.mark(&**g, pf_prof::QSA_IDX)?; (0, 0) } } _ => (0, 0), }; @@ -869,6 +886,7 @@ impl GpuModel<'_> { probe(&mut tr, "v", &pf.slab, vv, kv, t)?; probe(&mut tr, "attn", &pf.slab, at(l.d), nh * hd, t)?; g.gemm_dense(o, t, rot(at(l.d), nh * hd, 0, t)?, nh * hd, mx, ne, mact)?; + pp.mark(&**g, pf_prof::ATTN)?; } } probe(&mut tr, "| mixer", &pf.slab, x, d, t)?; @@ -896,6 +914,7 @@ impl GpuModel<'_> { } } if dense.is_some() { rot(h, ne, 0, t)?; } + pp.mark(&**g, pf_prof::POST)?; match &ly.ffn { Ffn::Dense { gate, up, down } => { g.gemm_dense(gate, t, hm, ne, at(l.ge), c.n_ff, bf)?; @@ -1207,6 +1226,7 @@ impl GpuModel<'_> { if ly.hc.is_some() { g.hc_write(x, fx, at(l.inj), ne, c.hc_n, t, true)?; } } } + pp.mark(&**g, pf_prof::MOE)?; probe(&mut tr, "| ffn", &pf.slab, x, d, t)?; if trace { crate::say!("nan-trace pos {} layer {il}:{tr}", self.pos); tr.clear(); } if il < c.n_layer { @@ -1312,13 +1332,18 @@ impl GpuModel<'_> { df.pend_ctx = 0; } self.pos += toks.len(); + pp.mark(&*self.gpu, pf_prof::TAIL)?; if let Some(o) = out { *o = (self.gpu.get::(&self.pf.as_ref().unwrap().slab, 0, toks.len() * d)?, pe.to_vec()); + pp.mark(&*self.gpu, pf_prof::OUT)?; + pp.report(self.first, pos0, toks.len()); return Ok(()); } - let Some(nx) = self.next.as_deref_mut() else { return Ok(()) }; + let Some(nx) = self.next.as_deref_mut() else { pp.report(self.first, pos0, toks.len()); return Ok(()) }; (nx.rope_offset, nx.pf_mrope) = (self.rope_offset, self.pf_mrope.clone()); let xs = self.gpu.get::(&self.pf.as_ref().unwrap().slab, 0, toks.len() * d)?; + pp.mark(&*self.gpu, pf_prof::OUT)?; + pp.report(self.first, pos0, toks.len()); let r = nx.prefill_chunk(toks, Some((&xs, pe)), None); nx.pf_mrope = None; r From 06825432ea6b0460070f2926984152b7b5fe349c Mon Sep 17 00:00:00 2001 From: SubgridAI Date: Sun, 6 Dec 2026 07:34:19 +0000 Subject: [PATCH 3/6] prefill pipeline: hand the rows over in reused portable pinned buffers (STRATA_PF_PINNED=0: Vecs) Each hop's hidden rows went device -> fresh Vec -> device, both copies through the pageable path. Two portable pinned buffers per hop, owned by the receiving part and passed back once its upload is done, make both copies direct DMA (Backend::alloc_shared_host; host_is_pinned sees them on every device). 4x RTX 3060 (two PLX switches): 980K prefill 2227 -> 2339 tok/s, same answer. Co-Authored-By: Claude Opus 5.5 --- src/backend.rs | 9 ++++ src/cuda/mod.rs | 23 ++++++++- src/gpu_model.rs | 5 +- src/gpu_model/prefill.rs | 107 ++++++++++++++++++++++++++++++--------- 4 files changed, 118 insertions(+), 26 deletions(-) diff --git a/src/backend.rs b/src/backend.rs index efbacad0..e4986bd3 100644 --- a/src/backend.rs +++ b/src/backend.rs @@ -158,6 +158,12 @@ pub trait PrefillRead { fn rows(&self) -> anyhow::Result<&[f32]>; } +/// Page-locked host memory that every device may copy from and to directly (the prefill hand-off between the parts +/// of a `--device` split). Freed on drop. +pub trait SharedHost: Send { + fn f32s(&mut self) -> &mut [f32]; +} + pub trait DeviceTimer { fn stop(&mut self) -> anyhow::Result<()>; fn elapsed(&self) -> anyhow::Result; @@ -717,6 +723,9 @@ pub trait Backend: Send { /// under it; None otherwise (CUDA, Vulkan, or bytes outside every registered range). fn host_ptr(&self, _data: &[u8]) -> Option { None } + /// `n` f32 of `SharedHost` memory, or None where the backend has none (the hand-off then copies through `Vec`s). + fn alloc_shared_host(&self, _n: usize) -> anyhow::Result>> { Ok(None) } + fn moe_mailbox_optional(&self) -> bool { false } /// Whether `moe_prefetch` does anything here (CUDA: yes; Vulkan: no kernel, the knob is ignored). diff --git a/src/cuda/mod.rs b/src/cuda/mod.rs index c9275885..2e362940 100644 --- a/src/cuda/mod.rs +++ b/src/cuda/mod.rs @@ -2173,7 +2173,15 @@ impl Backend for Gpu { fn host_is_pinned(&self, data: &[u8]) -> bool { let start = data.as_ptr() as usize; - self.pinned.lock().unwrap().iter().any(|&(p, n)| start >= p && start + data.len() <= p + n) + let inside = |&(p, n): &(usize, usize)| start >= p && start + data.len() <= p + n; + self.pinned.lock().unwrap().iter().any(inside) || SHARED_HOST.lock().unwrap().iter().any(inside) + } + + fn alloc_shared_host(&self, n: usize) -> anyhow::Result>> { + let Ok(mut s) = (unsafe { self.ctx.alloc_pinned_with_flags::(n, sys::CU_MEMHOSTALLOC_PORTABLE) }) else { return Ok(None) }; + let p = s.as_mut_ptr()? as usize; + SHARED_HOST.lock().unwrap().push((p, 4 * n)); + Ok(Some(Box::new(CudaSharedHost(s, p)))) } fn host_register(&self, p: usize, len: usize) -> anyhow::Result> { @@ -2818,6 +2826,19 @@ mod tests { } } +/// Ranges of every live `CudaSharedHost`: portable pinned memory, so every device's `htod` may DMA from it directly. +static SHARED_HOST: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + +struct CudaSharedHost(PinnedHostSlice, usize); + +impl crate::backend::SharedHost for CudaSharedHost { + fn f32s(&mut self) -> &mut [f32] { self.0.as_mut_slice().expect("pinned host slice") } +} + +impl Drop for CudaSharedHost { + fn drop(&mut self) { SHARED_HOST.lock().unwrap().retain(|&(p, _)| p != self.1); } +} + impl Drop for Gpu { fn drop(&mut self) { let pinned = std::mem::take(&mut *self.pinned.lock().unwrap()); diff --git a/src/gpu_model.rs b/src/gpu_model.rs index 6d199f42..f154f960 100644 --- a/src/gpu_model.rs +++ b/src/gpu_model.rs @@ -609,6 +609,9 @@ pub struct GpuModel<'a> { cpu_frac: f64, /// Eligible MoE layers since the last CPU timing sample. cpu_unsampled: usize, + /// Pinned host buffers the part before this one hands its prefill rows over in (`prefill_pipelined`), reused. + /// Declared after `gpu`, so they are freed after it. + hand: Vec>, } /// Layer shares of `--split`: one positive number per device, such as `60,40`. @@ -1292,7 +1295,7 @@ impl<'a> GpuModel<'a> { let _ = &mut ext_draft; crate::weights::trim_working_set(); Ok(GpuModel { m, gpu, layers, output_norm, output_hc, output, ple_ring, qsa, ple_prev: [-1, -1], saved_ple_prev: [-1, -1], ple_undo: ([-1, -1], vec![]), bufs, x, worker, logits, amax, ids, slots, step_buf, rope_buf, rope_offset: 0, hada, mrope: false, mrope_buf: gpu_mrope, pf_mrope: None, pf_mrope_buf: None, ctx, pos: 0, saved, saved_pos: 0, saved_ids: vec![], sys: None, parked: vec![], owner: 0, saved_owner: 0, sys_owner: 0, cache_ram: 0, cache, adapt_every, adapt_swaps, keep_decode_set, hits: 0, misses: 0, tokens: 0, mailbox_writes: Default::default(), mailbox_reads: Default::default(), pids, host_exp, hc_defer: Default::default(), hc_pend: Default::default(), hc_cnt, cpu_time: Duration::ZERO, resumed: Default::default(), lora_applied: Default::default(), drafts: (0, 0), split_time: Default::default(), k, nsnap, short: 32, pf, prompt_cache_path: None, bt, mtp, dflash, ext_draft, ext_draft_pend: Vec::new(), mhc_ones, graph_tag: 0, ngram: None, first: range.start, next: None, vram_margin, - cur: 0, seqs, kv_cap: if grow { vec![kv0; ns] } else { vec![] }, kv0, rows: vec![], row_tokens: 0, cpu_frac: 0.5, cpu_unsampled: 0, kv_stage }) + cur: 0, seqs, kv_cap: if grow { vec![kv0; ns] } else { vec![] }, kv0, rows: vec![], row_tokens: 0, cpu_frac: 0.5, cpu_unsampled: 0, kv_stage, hand: Vec::new() }) } /// Clear KV and recurrent state (and forget the `prefill_cached` prefix, whose KV this zeroes). diff --git a/src/gpu_model/prefill.rs b/src/gpu_model/prefill.rs index 94f2953c..92ab8c63 100644 --- a/src/gpu_model/prefill.rs +++ b/src/gpu_model/prefill.rs @@ -10,6 +10,16 @@ use crate::model::Model; use crate::weights::Prefetch; use super::pf_prof::{self, Pp}; +/// What one part of a pipelined prefill hands the next: the chunk's `n` hidden-row values in `buf` (pinned, reused) +/// or else in `xs`, and the PLE input. +#[derive(Default)] +pub(super) struct HandOut { + buf: Option>, + xs: Vec, + pe: Vec, + n: usize, +} + /// Experts staged per group when a layer routes to experts outside the cache. Staging holds three groups. const STAGE: usize = 16; @@ -251,61 +261,101 @@ impl GpuModel<'_> { /// instead of taking turns. Each part reads only its own layers' state (KV, recurrent state) from the chunks /// before, and it takes the chunks in order, so the result is the same as the sequential loop's. fn prefill_pipelined(&mut self, tokens: &[u32], chunk: usize) -> anyhow::Result<()> { - use std::sync::mpsc::sync_channel; - type Hand = (usize, Vec, Vec); + use std::sync::mpsc::{Receiver, SyncSender, sync_channel}; + type Hand = (usize, HandOut); + type Pool = Box; // Detach the parts after this one, so that each can be lent to its own thread; reattached below. let ro = self.rope_offset; let mut rest: Vec> = Vec::new(); let mut nx = self.next.take(); while let Some(mut b) = nx { nx = b.next.take(); b.rope_offset = ro; rest.push(b); } let n = rest.len(); + // Two pinned hand-off buffers per hop, kept on the receiving part and reused (`STRATA_PF_PINNED=0`: Vecs). + // A sender takes a free one from the hop's return channel, the receiver gives it back once its upload is done. + let cap = self.pf.as_ref().unwrap().chunk * self.m.cfg.hc_n.max(1) * self.m.cfg.n_embd; + let pinned = std::env::var("STRATA_PF_PINNED").map_or(true, |v| v != "0"); + let mut pools: Vec<(Option>, Option>)> = Vec::with_capacity(n); + for part in rest.iter_mut() { + while pinned && part.hand.len() < 2 { + let Some(b) = part.gpu.alloc_shared_host(cap)? else { break }; + part.hand.push(b); + } + if part.hand.is_empty() { pools.push((None, None)); continue; } + let (rtx, rrx) = sync_channel::(part.hand.len()); + for b in part.hand.drain(..) { rtx.send(b).expect("hand-off pool"); } + pools.push((Some(rtx), Some(rrx))); + } + // A sender: run the chunk, waiting first for a free buffer of the hop after it (when it has a pool). + fn send_chunk anyhow::Result<()>>(run: P, ci: usize, free: Option<&Receiver>, tx: &SyncSender) + -> anyhow::Result { + let tw = std::time::Instant::now(); + let mut out = HandOut { buf: free.and_then(|r| r.recv().ok()), ..Default::default() }; + pf_prof::add_wait(0.0, tw.elapsed().as_secs_f64()); + run(&mut out)?; + let tw = std::time::Instant::now(); + let ok = tx.send((ci, out)).is_ok(); + pf_prof::add_wait(0.0, tw.elapsed().as_secs_f64()); + Ok(ok) + } + let mut leftovers: Vec<(usize, Receiver)> = Vec::new(); let res = std::thread::scope(|sc| -> anyhow::Result<()> { let (mut txs, mut rxs) = (Vec::with_capacity(n), Vec::with_capacity(n)); for _ in 0..n { let (tx, rx) = sync_channel::(1); txs.push(Some(tx)); rxs.push(Some(rx)); } let head_tx = txs[0].take().unwrap(); + let mut frees: Vec>> = pools.iter_mut().map(|p| p.1.take()).collect(); + let head_free = frees[0].take(); let mut handles = Vec::with_capacity(n); for (i, part) in rest.iter_mut().enumerate() { let rx = rxs[i].take().unwrap(); let tx = txs.get_mut(i + 1).and_then(Option::take); - handles.push(sc.spawn(move || -> anyhow::Result<()> { + let back = pools[i].0.take(); + let free = frees.get_mut(i + 1).and_then(Option::take); + handles.push(sc.spawn(move || -> anyhow::Result)>> { let mut rx = rx.into_iter(); loop { let tw = std::time::Instant::now(); - let Some((ci, xs, pe)) = rx.next() else { break }; + let Some((ci, mut hin)) = rx.next() else { break }; pf_prof::add_wait(tw.elapsed().as_secs_f64(), 0.0); let ch = &tokens[ci * chunk..((ci + 1) * chunk).min(tokens.len())]; - match &tx { - Some(tx) => { - let mut out = (Vec::new(), Vec::new()); - part.prefill_chunk_to(ch, Some((&xs, &pe)), None, Some(&mut out))?; - let tw = std::time::Instant::now(); - if tx.send((ci, out.0, out.1)).is_err() { break; } - pf_prof::add_wait(0.0, tw.elapsed().as_secs_f64()); - } + let pe = std::mem::take(&mut hin.pe); + let nrow = hin.n; + let xs: &[f32] = match hin.buf.as_mut() { Some(b) => &b.f32s()[..nrow], None => &hin.xs }; + let go = match &tx { + Some(tx) => send_chunk(|out| part.prefill_chunk_to(ch, Some((xs, &pe)), None, Some(out)), ci, free.as_ref(), tx)?, None => { - part.prefill_chunk_to(ch, Some((&xs, &pe)), None, None)?; + part.prefill_chunk_to(ch, Some((xs, &pe)), None, None)?; + // The upload from the buffer is asynchronous: done before the buffer goes back. + if hin.buf.is_some() { part.gpu.sync()?; } crate::term::prefilled(ch.len()); + true } - } + }; + if let (Some(b), Some(back)) = (hin.buf.take(), &back) { let _ = back.send(b); } + if !go { break; } } - Ok(()) + Ok(free.map(|f| (i + 1, f))) })); } let mut r = Ok(()); for (ci, ch) in tokens.chunks(chunk).enumerate() { - let mut out = (Vec::new(), Vec::new()); - if let Err(e) = self.prefill_chunk_to(ch, None, None, Some(&mut out)) { r = Err(e); break; } - let tw = std::time::Instant::now(); - if head_tx.send((ci, out.0, out.1)).is_err() { break; } - pf_prof::add_wait(0.0, tw.elapsed().as_secs_f64()); + match send_chunk(|out| self.prefill_chunk_to(ch, None, None, Some(out)), ci, head_free.as_ref(), &head_tx) { + Err(e) => { r = Err(e); break; } + Ok(false) => break, + Ok(true) => {} + } } drop(head_tx); + if let Some(f) = head_free { leftovers.push((0, f)); } for h in handles { - let hr = h.join().unwrap_or_else(|_| Err(anyhow::anyhow!("prefill pipeline: a device thread panicked"))); - if r.is_ok() { r = hr; } + match h.join().unwrap_or_else(|_| Err(anyhow::anyhow!("prefill pipeline: a device thread panicked"))) { + Ok(f) => leftovers.extend(f), + Err(e) => if r.is_ok() { r = Err(e) }, + } } r }); + // Every buffer is back in its hop's return channel (or lost with an error, then allocated again next time). + for (i, rrx) in leftovers { rest[i].hand.extend(rrx.try_iter()); } let mut acc = None; for mut b in rest.into_iter().rev() { b.next = acc; acc = Some(b); } self.next = acc; @@ -547,7 +597,7 @@ impl GpuModel<'_> { /// `prefill_chunk` on this part only. With `out`, the hidden rows and PLE input this part leaves for the next /// part are returned there instead of being handed to `next` (the pipelined prefill hands them on itself). fn prefill_chunk_to(&mut self, toks: &[u32], input: Option<(&[f32], &[f32])>, rows: Option<(&[usize], usize)>, - out: Option<&mut (Vec, Vec)>) -> anyhow::Result<()> { + out: Option<&mut HandOut>) -> anyhow::Result<()> { self.dflash_commit_ctx()?; if let Some((_, first)) = &self.pf_mrope { if self.pf_mrope_buf.is_none() { self.pf_mrope_buf = Some(self.gpu.zeros::(8 * self.pf.as_ref().unwrap().chunk)?); } @@ -1334,7 +1384,16 @@ impl GpuModel<'_> { self.pos += toks.len(); pp.mark(&*self.gpu, pf_prof::TAIL)?; if let Some(o) = out { - *o = (self.gpu.get::(&self.pf.as_ref().unwrap().slab, 0, toks.len() * d)?, pe.to_vec()); + let nrow = toks.len() * d; + let slab = &self.pf.as_ref().unwrap().slab; + match o.buf.as_mut() { + Some(b) => { + let s = &mut b.f32s()[..nrow]; + self.gpu.dtoh(slab, 0, unsafe { std::slice::from_raw_parts_mut(s.as_mut_ptr().cast::(), 4 * nrow) })?; + } + None => o.xs = self.gpu.get::(slab, 0, nrow)?, + } + (o.n, o.pe) = (nrow, pe.to_vec()); pp.mark(&*self.gpu, pf_prof::OUT)?; pp.report(self.first, pos0, toks.len()); return Ok(()); From c6e55e3e74862da7a849ec7c968bbd2419989300 Mon Sep 17 00:00:00 2001 From: SubgridAI Date: Sun, 6 Dec 2026 07:34:19 +0000 Subject: [PATCH 4/6] pf_prof: report each chunk's gap and lead (setup, embed) gap: the time since the part's previous chunk line, i.e. the waits plus any work outside the timed window; lead: the setup and input embedding before it. Unaccounted gap on a part with no waits is work that paces the pipeline unseen. Co-Authored-By: Claude Opus 5.5 --- src/gpu_model/pf_prof.rs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/gpu_model/pf_prof.rs b/src/gpu_model/pf_prof.rs index 843dfe05..a1f8e580 100644 --- a/src/gpu_model/pf_prof.rs +++ b/src/gpu_model/pf_prof.rs @@ -19,6 +19,9 @@ thread_local! { static SCORE: Cell = const { Cell::new(0.0) }; static WAIT_IN: Cell = const { Cell::new(0.0) }; static WAIT_OUT: Cell = const { Cell::new(0.0) }; + /// When this thread printed its last chunk line: the time from there to the next chunk's start is that chunk's + /// `gap` (work outside the profiled window, such as the head's embedding, plus the pipeline waits). + static LAST: Cell> = const { Cell::new(None) }; } /// `qsa_score` time inside `qsa_select` (the CUDA backend books it here). @@ -47,6 +50,7 @@ pub struct Pp { on: bool, start: Instant, last: Instant, + gap: f64, acc: [f64; N], } @@ -63,7 +67,8 @@ impl Pp { ACTIVE.with(|c| c.set(true)); } let now = Instant::now(); - Ok(Pp { on, start: now, last: now, acc: [0.0; N] }) + let gap = LAST.with(|c| c.get()).map_or(0.0, |l| (now - l).as_secs_f64()); + Ok(Pp { on, start: now, last: now, gap, acc: [0.0; N] }) } pub fn mark(&mut self, g: &dyn crate::backend::Backend, cat: usize) -> anyhow::Result<()> { @@ -85,7 +90,8 @@ impl Pp { s += &format!(" {name} {:.1}", self.acc[i] * 1e3); if i == QSA_SEL { s += &format!(" (score {:.1})", score * 1e3); } } - s += &format!(" | wait_prev {:.1} wait_next {:.1}", wi * 1e3, wo * 1e3); + s += &format!(" | wait_prev {:.1} wait_next {:.1} gap {:.1}", wi * 1e3, wo * 1e3, self.gap * 1e3); crate::say!("{s}"); + LAST.with(|c| c.set(Some(Instant::now()))); } } From 05afbc7da09dcbc989989e7dcfcb722f821f7b89 Mon Sep 17 00:00:00 2001 From: SubgridAI Date: Sun, 6 Dec 2026 07:34:20 +0000 Subject: [PATCH 5/6] prefill: embed the head part's chunk on the rayon pool One thread dequantized (and un-rotated) each 4096-token chunk's embedding rows in ~300 ms before the head part's GPU work: the head's cycle was 1046 ms of GPU work + ~300 ms of this, which paced every part of the pipeline (the others showed it as waits). Now ~68 ms. 4x RTX 3060, Qwen4-35B-A3B UD-Q5_K_M, ctx 1M: 194K prefill 2939 -> 3124 tok/s, 3/3 needles, decode unchanged. Co-Authored-By: Claude Opus 5.5 --- src/gpu_model/pf_prof.rs | 7 ++++++- src/gpu_model/prefill.rs | 15 ++++++++++++++- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/src/gpu_model/pf_prof.rs b/src/gpu_model/pf_prof.rs index a1f8e580..a2c73c6c 100644 --- a/src/gpu_model/pf_prof.rs +++ b/src/gpu_model/pf_prof.rs @@ -22,8 +22,12 @@ thread_local! { /// When this thread printed its last chunk line: the time from there to the next chunk's start is that chunk's /// `gap` (work outside the profiled window, such as the head's embedding, plus the pipeline waits). static LAST: Cell> = const { Cell::new(None) }; + /// This chunk's work before its window: setup (dflash commit, prefetch start) and the input embedding. + static LEAD: Cell<(f64, f64)> = const { Cell::new((0.0, 0.0)) }; } +pub fn lead(setup: f64, embed: f64) { LEAD.with(|c| c.set((setup, embed))); } + /// `qsa_score` time inside `qsa_select` (the CUDA backend books it here). pub fn add_score(s: f64) { SCORE.with(|c| c.set(c.get() + s)); } /// Pipeline waits of this thread: for the part before (`recv`) and for the part after (`send`). @@ -90,7 +94,8 @@ impl Pp { s += &format!(" {name} {:.1}", self.acc[i] * 1e3); if i == QSA_SEL { s += &format!(" (score {:.1})", score * 1e3); } } - s += &format!(" | wait_prev {:.1} wait_next {:.1} gap {:.1}", wi * 1e3, wo * 1e3, self.gap * 1e3); + s += &format!(" | wait_prev {:.1} wait_next {:.1} gap {:.1} setup {:.1} embed {:.1}", wi * 1e3, wo * 1e3, self.gap * 1e3, + LEAD.with(|c| c.get()).0 * 1e3, LEAD.with(|c| c.get()).1 * 1e3); crate::say!("{s}"); LAST.with(|c| c.set(Some(Instant::now()))); } diff --git a/src/gpu_model/prefill.rs b/src/gpu_model/prefill.rs index 92ab8c63..d69bc4dc 100644 --- a/src/gpu_model/prefill.rs +++ b/src/gpu_model/prefill.rs @@ -598,6 +598,7 @@ impl GpuModel<'_> { /// part are returned there instead of being handed to `next` (the pipelined prefill hands them on itself). fn prefill_chunk_to(&mut self, toks: &[u32], input: Option<(&[f32], &[f32])>, rows: Option<(&[usize], usize)>, out: Option<&mut HandOut>) -> anyhow::Result<()> { + let tl0 = std::time::Instant::now(); self.dflash_commit_ctx()?; if let Some((_, first)) = &self.pf_mrope { if self.pf_mrope_buf.is_none() { self.pf_mrope_buf = Some(self.gpu.zeros::(8 * self.pf.as_ref().unwrap().chunk)?); } @@ -606,13 +607,23 @@ impl GpuModel<'_> { // Missed experts are read from the mapped weights in the order the staging copies take them. let pre = (self.cache.is_some() && !(crate::weights::fits_ram() && crate::weights::preloaded())).then(Prefetch::start); let anon = pre.as_ref().map(|_| self.m.w.g.anon_spans()).unwrap_or_default(); + let tl1 = std::time::Instant::now(); let owned: (Vec, Vec); let (emb, pe): (&[f32], &[f32]) = match input { Some(v) => v, None => { let hcn = self.m.cfg.hc_n.max(1); let pe = if self.ple_ring.is_some() { toks.iter().flat_map(|&tk| self.m.ple_embed(&mut self.ple_prev, tk)).collect() } else { vec![] }; - owned = (toks.iter().flat_map(|&tk| self.m.embed(tk).repeat(hcn)).collect(), pe); + // Rows dequantized (and un-rotated) on the rayon pool: one thread took ~300 ms a 4096-token chunk on + // the head part, outside its GPU work, and set the whole pipeline's pace. + use rayon::prelude::*; + let (m, ne) = (&self.m, self.m.cfg.n_embd); + let mut e = vec![0f32; toks.len() * ne * hcn]; + e.par_chunks_mut(ne * hcn).zip(toks.par_iter()).for_each(|(o, &tk)| { + let x = m.embed(tk); + for h in o.chunks_mut(ne) { h.copy_from_slice(&x); } + }); + owned = (e, pe); (&owned.0, &owned.1) } }; @@ -620,7 +631,9 @@ impl GpuModel<'_> { let pf = self.pf.as_ref().unwrap(); let (g, mut t, n, eps, ne) = (&self.gpu, toks.len(), pf.chunk, c.eps, c.n_embd); let d = c.hc_n.max(1) * ne; + let tl2 = std::time::Instant::now(); let mut pp = Pp::new(&**g)?; + pf_prof::lead((tl1 - tl0).as_secs_f64(), (tl2 - tl1).as_secs_f64()); let pos0 = self.pos; g.put(emb, &pf.slab, 0)?; if !pe.is_empty() { g.put(pe, &pf.slab, pf.lay.emb)?; } From 3ad0ff0898325cf3416ed9399abfb1efaefd5077 Mon Sep 17 00:00:00 2001 From: SubgridAI Date: Sun, 6 Dec 2026 08:30:52 +0000 Subject: [PATCH 6/6] prefill pipeline: keep the parts attached on an allocation error or a head panic - A failed alloc_shared_host falls back to Vecs for that hop instead of returning before the detached parts are reattached. - The scope runs under catch_unwind: the server catches a request's panic and keeps the model, so the parts are reattached before the panic resumes. - pf_prof: a chunk that fails before its line clears its score and pipeline waits, so they don't land on the next chunk's line. - Comment: a part with a next part ends prefill_chunk_to with a blocking dtoh, so its upload from the hand-off buffer is done before the buffer goes back. Co-Authored-By: Claude Opus 5.5 --- src/gpu_model/pf_prof.rs | 15 +++++++++++++-- src/gpu_model/prefill.rs | 13 +++++++++---- 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/src/gpu_model/pf_prof.rs b/src/gpu_model/pf_prof.rs index a2c73c6c..7456b230 100644 --- a/src/gpu_model/pf_prof.rs +++ b/src/gpu_model/pf_prof.rs @@ -56,10 +56,20 @@ pub struct Pp { last: Instant, gap: f64, acc: [f64; N], + reported: Cell, } impl Drop for Pp { - fn drop(&mut self) { if self.on { ACTIVE.with(|c| c.set(false)); } } + fn drop(&mut self) { + if !self.on { return; } + ACTIVE.with(|c| c.set(false)); + // A chunk that failed before `report`: its score and waits must not land on the next chunk's line. + if !self.reported.get() { + SCORE.with(|c| c.set(0.0)); + WAIT_IN.with(|c| c.set(0.0)); + WAIT_OUT.with(|c| c.set(0.0)); + } + } } impl Pp { @@ -72,7 +82,7 @@ impl Pp { } let now = Instant::now(); let gap = LAST.with(|c| c.get()).map_or(0.0, |l| (now - l).as_secs_f64()); - Ok(Pp { on, start: now, last: now, gap, acc: [0.0; N] }) + Ok(Pp { on, start: now, last: now, gap, acc: [0.0; N], reported: Cell::new(false) }) } pub fn mark(&mut self, g: &dyn crate::backend::Backend, cat: usize) -> anyhow::Result<()> { @@ -87,6 +97,7 @@ impl Pp { /// Print the chunk's line: part (first layer), chunk start position, tokens, total and each component in ms. pub fn report(&self, first: usize, pos: usize, t: usize) { if !self.on { return; } + self.reported.set(true); let score = SCORE.with(|c| c.replace(0.0)); let (wi, wo) = (WAIT_IN.with(|c| c.replace(0.0)), WAIT_OUT.with(|c| c.replace(0.0))); let mut s = format!("pf_prof part L{first} pos {pos} t {t} total {:.1}", (self.last - self.start).as_secs_f64() * 1e3); diff --git a/src/gpu_model/prefill.rs b/src/gpu_model/prefill.rs index d69bc4dc..0cfc298c 100644 --- a/src/gpu_model/prefill.rs +++ b/src/gpu_model/prefill.rs @@ -276,8 +276,9 @@ impl GpuModel<'_> { let pinned = std::env::var("STRATA_PF_PINNED").map_or(true, |v| v != "0"); let mut pools: Vec<(Option>, Option>)> = Vec::with_capacity(n); for part in rest.iter_mut() { + // A failed allocation falls back to Vecs for this hop: an early return here would lose the detached parts. while pinned && part.hand.len() < 2 { - let Some(b) = part.gpu.alloc_shared_host(cap)? else { break }; + let Ok(Some(b)) = part.gpu.alloc_shared_host(cap) else { break }; part.hand.push(b); } if part.hand.is_empty() { pools.push((None, None)); continue; } @@ -298,7 +299,9 @@ impl GpuModel<'_> { Ok(ok) } let mut leftovers: Vec<(usize, Receiver)> = Vec::new(); - let res = std::thread::scope(|sc| -> anyhow::Result<()> { + // A panic on this (the head's) thread must not skip the reattachment below: the server catches a request's + // panic and keeps the model, which would be left without its later parts. + let res = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| std::thread::scope(|sc| -> anyhow::Result<()> { let (mut txs, mut rxs) = (Vec::with_capacity(n), Vec::with_capacity(n)); for _ in 0..n { let (tx, rx) = sync_channel::(1); txs.push(Some(tx)); rxs.push(Some(rx)); } let head_tx = txs[0].take().unwrap(); @@ -330,6 +333,8 @@ impl GpuModel<'_> { true } }; + // A part with a next part ends `prefill_chunk_to` with a blocking `dtoh` on the stream that ran + // the upload, so that upload is done here too; only the last part needed the `sync` above. if let (Some(b), Some(back)) = (hin.buf.take(), &back) { let _ = back.send(b); } if !go { break; } } @@ -353,13 +358,13 @@ impl GpuModel<'_> { } } r - }); + }))); // Every buffer is back in its hop's return channel (or lost with an error, then allocated again next time). for (i, rrx) in leftovers { rest[i].hand.extend(rrx.try_iter()); } let mut acc = None; for mut b in rest.into_iter().rev() { b.next = acc; acc = Some(b); } self.next = acc; - res + res.unwrap_or_else(|p| std::panic::resume_unwind(p)) } /// Image rows of a prompt in one batched forward, up to a chunk. Returns how many rows it ran: 0 when this model