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 989c3f11..2e362940 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(()) } @@ -2169,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> { @@ -2814,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 8df4c0fd..f154f960 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}; @@ -608,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`. @@ -1291,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/pf_prof.rs b/src/gpu_model/pf_prof.rs new file mode 100644 index 00000000..7456b230 --- /dev/null +++ b/src/gpu_model/pf_prof.rs @@ -0,0 +1,113 @@ +//! `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) }; + /// 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`). +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, + gap: f64, + acc: [f64; N], + reported: Cell, +} + +impl Drop for Pp { + 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 { + 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(); + 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], reported: Cell::new(false) }) + } + + 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; } + 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); + 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} 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 89ca4587..0cfc298c 100644 --- a/src/gpu_model/prefill.rs +++ b/src/gpu_model/prefill.rs @@ -8,6 +8,17 @@ 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}; + +/// 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; @@ -210,11 +221,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 +247,126 @@ 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::{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() { + // 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 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; } + 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(); + // 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(); + 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); + 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, 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())]; + 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)?; + // 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 + } + }; + // 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; } + } + Ok(free.map(|f| (i + 1, f))) + })); + } + let mut r = Ok(()); + for (ci, ch) in tokens.chunks(chunk).enumerate() { + 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 { + 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; + 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 /// has no batched prefill for them, and never `ids`' last row (the caller takes that row's logits from /// `step_embed`). @@ -461,6 +596,14 @@ 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 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)?); } @@ -469,13 +612,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) } }; @@ -483,6 +636,10 @@ 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)?; } g.put(&[self.pos as i32, 0], &self.step_buf, 0)?; @@ -490,6 +647,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; @@ -662,6 +820,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)); @@ -725,6 +884,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. @@ -753,6 +913,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)) => { @@ -765,12 +926,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), }; @@ -791,6 +954,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)?; @@ -818,6 +982,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)?; @@ -1129,6 +1294,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 { @@ -1234,9 +1400,27 @@ impl GpuModel<'_> { df.pend_ctx = 0; } self.pos += toks.len(); - let Some(nx) = self.next.as_deref_mut() else { return Ok(()) }; + pp.mark(&*self.gpu, pf_prof::TAIL)?; + if let Some(o) = out { + 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(()); + } + 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