Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions src/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<std::time::Duration>;
Expand Down Expand Up @@ -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<u64> { 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<Option<Box<dyn SharedHost>>> { Ok(None) }

fn moe_mailbox_optional(&self) -> bool { false }

/// Whether `moe_prefetch` does anything here (CUDA: yes; Vulkan: no kernel, the knob is ignored).
Expand Down
27 changes: 26 additions & 1 deletion src/cuda/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(())
}
Expand Down Expand Up @@ -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<Option<Box<dyn crate::backend::SharedHost>>> {
let Ok(mut s) = (unsafe { self.ctx.alloc_pinned_with_flags::<f32>(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<Option<u64>> {
Expand Down Expand Up @@ -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<Vec<(usize, usize)>> = std::sync::Mutex::new(Vec::new());

struct CudaSharedHost(PinnedHostSlice<f32>, 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());
Expand Down
6 changes: 5 additions & 1 deletion src/gpu_model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};

Expand Down Expand Up @@ -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<Box<dyn crate::backend::SharedHost>>,
}

/// Layer shares of `--split`: one positive number per device, such as `60,40`.
Expand Down Expand Up @@ -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).
Expand Down
113 changes: 113 additions & 0 deletions src/gpu_model/pf_prof.rs
Original file line number Diff line number Diff line change
@@ -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<bool> = 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<bool> = const { Cell::new(false) };
static SCORE: Cell<f64> = const { Cell::new(0.0) };
static WAIT_IN: Cell<f64> = const { Cell::new(0.0) };
static WAIT_OUT: Cell<f64> = 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<Option<Instant>> = 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<bool>,
}

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<Self> {
let on = on();
if on {
g.sync_freed()?;
SCORE.with(|c| c.set(0.0));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Correctness · 4 of 4

Pp error paths skip report, leaving WAIT_IN/WAIT_OUT stale for next chunk Pp::new resets SCORE but not WAIT_IN/WAIT_OUT; report() is the only place that clears them. Any ? error inside prefill_chunk_to drops Pp without report, so the next chunk's line includes the failed chunk's pipeline waits, and LAST is not updated so gap is also wrong.

Prompt for your AI agent
File: src/gpu_model/pf_prof.rs
Line: 70
Issue: Pp error paths skip report, leaving WAIT_IN/WAIT_OUT stale for next chunk Pp::new resets SCORE but not WAIT_IN/WAIT_OUT; report() is the only place that clears them. Any ? error inside prefill_chunk_to drops Pp without report, so the next chunk's line includes the failed chunk's pipeline waits, and LAST is not updated so gap is also wrong.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

4 of 4 (Medium): Pp error path leaves WAIT_IN/WAIT_OUT stale — FIXED

Fixed. If a chunk drops its Pp without reporting, it clears its score and pipeline waits, so they no longer land on the next chunk's line. This only affects the STRATA_PF_PROF=1 output.

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())));
}
}
Loading