diff --git a/examples/host_attn_bench.rs b/examples/host_attn_bench.rs new file mode 100644 index 00000000..dd98a2eb --- /dev/null +++ b/examples/host_attn_bench.rs @@ -0,0 +1,27 @@ +//! cargo run --release --example host_attn_bench -- [positions]: one CPU decode-attention call over a q4 cache. +use rusting_strata::host_attn::{HostAttn, run}; +fn main() { + let n: usize = std::env::args().nth(1).map_or(52_000, |s| s.parse().unwrap()); + let (nh, nkv, hd) = (24, 4, 256); + let rb = hd / 2 + hd / 16; + let mut seed = 1u32; + let mut rnd = || { seed = seed.wrapping_mul(1664525).wrapping_add(1013904223); seed }; + let mut kc = vec![0u8; n * nkv * rb]; + let mut vc = vec![0u8; n * nkv * rb]; + for (k, v) in kc.iter_mut().zip(vc.iter_mut()) { *k = rnd() as u8; *v = rnd() as u8; } + for r in 0..n * nkv { for b in 0..hd / 32 { let o = r * rb + hd / 2 + 2 * b; let d = half::f16::from_f32(0.05).to_le_bytes(); kc[o..o + 2].copy_from_slice(&d); vc[o..o + 2].copy_from_slice(&d); } } + let nt: usize = std::env::args().nth(2).map_or(1, |s| s.parse().unwrap()); + let q1: Vec = (0..nh * hd).map(|_| (rnd() % 1000) as f32 / 1000.0 - 0.5).collect(); + let q: Vec = (0..nt).flat_map(|_| q1.clone()).collect(); + let step: Vec = (0..nt).flat_map(|t| [(n - nt + t) as i32, 0]).collect(); + let mut part = vec![0f32; nt * nh * (hd + 2)]; + let a = HostAttn { q: q.as_ptr() as usize, step: step.as_ptr() as usize, part: part.as_mut_ptr() as usize, kc: kc.as_ptr() as usize, vc: vc.as_ptr() as usize, nh, nkv, hd, nt, scale: 1.0 / 16.0, mode: 2 }; + run(&a); + let t = std::time::Instant::now(); + let gap: u64 = std::env::var("GAP_US").ok().map_or(0, |s| s.parse().unwrap()); + let mut busy = 0.0; + for _ in 0..20 { if gap > 0 { std::thread::sleep(std::time::Duration::from_micros(gap)); } let t1 = std::time::Instant::now(); run(&a); busy += t1.elapsed().as_secs_f64(); } + let _ = t; let ms = busy * 1e3 / 20.0; + let gb = (2 * n * nkv * rb) as f64 / 1e9; + println!("{n} positions: {ms:.2} ms/call, {:.1} GB/s, x16 layers = {:.1} ms/token; check {:.6} {:.6}", gb / ms * 1e3, ms * 16.0, part[(nt - 1) * nh * (hd + 2)], part[(nt - 1) * nh * (hd + 2) + hd + 1]); +} diff --git a/src/backend.rs b/src/backend.rs index 82405787..954e4987 100644 --- a/src/backend.rs +++ b/src/backend.rs @@ -127,6 +127,12 @@ pub trait Backend: Send { } /// Zeroed buffer of `bytes` (at least 1). fn alloc(&self, bytes: usize) -> anyhow::Result; + /// Zeroed buffer of `bytes` in host RAM the device reads over PCIe (CUDA: mapped pinned memory). Backends + /// without it fall back to device memory. + fn alloc_host(&self, bytes: usize) -> anyhow::Result { self.alloc(bytes) } + /// Decode attention of `nt` tokens over a host-RAM cache (`alloc_host`) computed on the CPU, written to `out` + /// with the output gate `qg` applied. Ok(false): not supported here, use `attn_decode_q`. + fn attn_host(&self, _q: u64, _kc: u64, _vc: u64, _qg: u64, _out: u64, _step: u64, _nh: usize, _nkv: usize, _hd: usize, _scale: f32, _nt: usize) -> anyhow::Result { Ok(false) } fn htod(&self, src: &[u8], dst: &Buf, off: usize) -> anyhow::Result<()>; fn dtoh(&self, src: &Buf, off: usize, dst: &mut [u8]) -> anyhow::Result<()>; fn dtod(&self, src: &Buf, src_off: usize, dst: &Buf, dst_off: usize, bytes: usize) -> anyhow::Result<()>; diff --git a/src/cuda/kernels.cu b/src/cuda/kernels.cu index 51ef225f..93efd5cc 100644 --- a/src/cuda/kernels.cu +++ b/src/cuda/kernels.cu @@ -4178,3 +4178,30 @@ extern "C" __global__ void __launch_bounds__(1024) qsa_select(const float* score if (tid == 0) sel[0] = 4 * top + pos + 1 - 4 * nb; } } + +// ---- CPU decode attention over a host-RAM KV cache (src/host_attn.rs), through a mapped mailbox ---- +// ha_post copies the queries and positions into mapped memory, then raises the request (word 0) with a fresh +// sequence number and the layer's context address (words 4-5). The CPU worker spins on it, computes, writes the +// partials and raises done (word 16). ha_wait holds the stream until then, so the next launch reads the partials. +extern "C" __global__ void ha_post(const float* q, const int* step, float* mq, int* ms, int nq, int ns, + unsigned int* mb, unsigned int* seq, unsigned long long ctx) { + for (int i = threadIdx.x; i < nq; i += blockDim.x) mq[i] = q[i]; + for (int i = threadIdx.x; i < ns; i += blockDim.x) ms[i] = step[i]; + __threadfence_system(); + __syncthreads(); + if (threadIdx.x == 0) { + unsigned int s = seq[0] + 1; + seq[0] = s; + *(volatile unsigned long long*)(mb + 4) = ctx; + __threadfence_system(); + *(volatile unsigned int*)mb = s; + } +} +extern "C" __global__ void ha_wait(const unsigned int* mb, const unsigned int* seq) { + unsigned int s = seq[0], spins = 0; + while (((volatile const unsigned int*)mb)[16] != s) { + __nanosleep(64); + if (++spins == (1u << 28)) __trap(); // tens of seconds: the CPU worker is gone + } + __threadfence_system(); +} diff --git a/src/cuda/mod.rs b/src/cuda/mod.rs index 5362d9df..d8c6f5a1 100644 --- a/src/cuda/mod.rs +++ b/src/cuda/mod.rs @@ -17,9 +17,9 @@ pub(crate) 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] }; -pub(crate) const KERNELS: [&str; 58] = [ +pub(crate) 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", + "kv_store", "attn_merge", "ha_post", "ha_wait", "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", @@ -440,6 +440,14 @@ pub fn cfg(grid: (u32, u32), block: u32, smem: u32) -> LaunchConfig { /// otherwise) names the kernel that raised it. Debugging only: no graphs, and every launch pays a stream sync. static SYNC_EACH: std::sync::LazyLock = std::sync::LazyLock::new(|| std::env::var_os("STRATA_CUDA_SYNC").is_some()); +/// `attn_host`: tokens and floats a token (nh * (hd + 2)) its mapped staging holds; queries, partials and positions, +/// shared by all layers (the stream runs them in turn), never freed since captured graphs keep their addresses. +const HA_T: usize = 64; +const HA_W: usize = 64 * 514; +/// Queries, partials, positions, the mailbox (mapped) and the sequence counter (device). +static HA_STAGE: std::sync::Mutex> = std::sync::Mutex::new(None); +static CTX: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + macro_rules! launch { ($g:expr, $name:expr, $cfg:expr, $($a:expr),* $(,)?) => {{ let f = $g.f($name); @@ -928,6 +936,81 @@ impl Backend for Gpu { Ok(()) } + fn alloc_host(&self, bytes: usize) -> anyhow::Result { + // Anonymous memory on 2 MB huge pages (the CPU attention walks it all each token: 4 KB pages cost ~30% in + // TLB misses), then pinned and mapped into the device with cuMemHostRegister. + struct Reg(#[allow(dead_code)] memmap2::MmapMut, usize); + impl Drop for Reg { fn drop(&mut self) { unsafe { let _ = sys::cuMemHostUnregister(self.1 as *mut _); } } } + const HP: usize = 2 << 20; + let len = bytes.max(1).next_multiple_of(HP); + let mut m = memmap2::MmapMut::map_anon(len + HP)?; + #[cfg(target_os = "linux")] + let _ = m.advise(memmap2::Advice::HugePage); + let base = m.as_mut_ptr() as usize; + let h = base.next_multiple_of(HP); + unsafe { std::ptr::write_bytes(h as *mut u8, 0, len) }; + self.ctx.bind_to_thread()?; + let r = unsafe { sys::cuMemHostRegister_v2(h as *mut _, len, sys::CU_MEMHOSTREGISTER_DEVICEMAP | sys::CU_MEMHOSTREGISTER_PORTABLE) }; + anyhow::ensure!(r == sys::CUresult::CUDA_SUCCESS, "cuMemHostRegister: {r:?}"); + // From here a failure drops `reg`, which unregisters the range before the mapping goes. + let reg = Reg(m, h); + let mut dev = 0; + let r = unsafe { sys::cuMemHostGetDevicePointer_v2(&mut dev, h as *mut _, 0) }; + anyhow::ensure!(r == sys::CUresult::CUDA_SUCCESS, "cuMemHostGetDevicePointer: {r:?}"); + anyhow::ensure!(dev == h as u64, "mapped host memory has a device address other than its host one (no UVA)"); + let b = Buf::new(dev, bytes, reg); + // The staging of `attn_host`, made here at load time: allocating inside a graph capture breaks it. + let mut st = HA_STAGE.lock().unwrap(); + if st.is_none() { + let raw = |n: usize| -> anyhow::Result { let (b, _) = self.host_mailbox(n.div_ceil(4))?; Ok(b) }; + let (mb, host) = self.host_mailbox(64)?; + *st = Some((raw(4 * HA_T * HA_W)?, raw(4 * HA_T * HA_W)?, raw(8 * HA_T)?, mb, self.alloc(64)?)); + if std::env::var_os("STRATA_HA_MAILBOX").is_some() { crate::host_attn::start_worker(host as usize); } + } + Ok(b) + } + + fn attn_host(&self, q: u64, kc: u64, vc: u64, qg: u64, out: u64, step: u64, nh: usize, nkv: usize, hd: usize, scale: f32, nt: usize) -> anyhow::Result { + if self.kv_mode > 2 || nt > HA_T || hd % 32 != 0 || nh % nkv != 0 || nh * (hd + 2) > HA_W { return Ok(false); } + let st = HA_STAGE.lock().unwrap(); + let Some((bq, bp, bs, mb, seq)) = st.as_ref() else { return Ok(false) }; + let (bq, bp, bs, mb, seq) = (bq.addr(), bp.addr(), bs.addr(), mb.addr(), seq.addr()); + drop(st); + let ctx = { + let mut c = CTX.lock().unwrap(); + // Keyed by every field: a model loaded later can reuse a freed cache's addresses with other shapes. + let same = |a: &crate::host_attn::HostAttn| a.kc == kc as usize && a.vc == vc as usize && a.nt == nt && a.nh == nh + && a.nkv == nkv && a.hd == hd && a.mode == self.kv_mode as u32 && a.scale.to_bits() == scale.to_bits(); + match c.iter().find(|e| same(unsafe { &*(e.3 as *const crate::host_attn::HostAttn) })) { + Some(e) => e.3, + None => { + let a = Box::leak(Box::new(crate::host_attn::HostAttn { q: bq as usize, step: bs as usize, part: bp as usize, + kc: kc as usize, vc: vc as usize, nh, nkv, hd, nt, scale, mode: self.kv_mode as u32 })) as *mut _ as usize; + c.push((kc, vc, nt, a)); + a + } + } + }; + // A stream host function by default; `STRATA_HA_MAILBOX` spins on a mapped flag instead (measured the same, + // 14.6 vs 14.7 tok/s at 52K, and a dead worker would trap the GPU). + if std::env::var_os("STRATA_HA_MAILBOX").is_none() { + self.ctx.bind_to_thread()?; + let cs = self.st().cu_stream(); + unsafe { + result::memcpy_dtod_async(bq, q, 4 * nt * nh * hd, cs)?; + result::memcpy_dtod_async(bs, step, 8 * nt, cs)?; + let r = sys::cuLaunchHostFunc(cs, Some(crate::host_attn::callback), ctx as *mut _); + anyhow::ensure!(r == sys::CUresult::CUDA_SUCCESS, "cuLaunchHostFunc: {r:?}"); + } + } else { + launch!(self, "ha_post", cfg((1, 1), 256, 0), q, step, bq, bs, (nt * nh * hd) as i32, (2 * nt) as i32, mb, seq, ctx as u64); + launch!(self, "ha_wait", cfg((1, 1), 32, 0), mb, seq); + } + launch!(self, "attn_merge", LaunchConfig { grid_dim: (nh as u32, 1, nt as u32), block_dim: (256, 1, 1), shared_mem_bytes: 0 }, + bp, qg, out, hd as i32, 1i32, step, 1i32, 0i32, 0u64, 0u64); + Ok(true) + } + /// Pinned host memory mapped into the device address space. fn host_mailbox(&self, words: usize) -> anyhow::Result<(Buf, *mut u32)> { let n = words.max(1); @@ -1535,12 +1618,12 @@ mod tests { } /// M1-T5, CPU-only: the loaded name list drops `gemmi_*`/`gemmis_*` only on a device where kernels.cu compiles - /// them out. 397 names today (sm_80); 23 non-float types x 3 fewer names = 328 on sm_70. + /// them out. 399 names today (sm_80); 23 non-float types x 3 fewer names = 330 on sm_70. #[test] fn kernel_names() { let (sm70, sm80) = (super::kernel_names(false), super::kernel_names(true)); - assert_eq!(sm80.len(), 397); - assert_eq!(sm70.len(), 328); + assert_eq!(sm80.len(), 399); + assert_eq!(sm70.len(), 330); 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::>()); diff --git a/src/gpu_model.rs b/src/gpu_model.rs index ed91a3ae..9c96dacb 100644 --- a/src/gpu_model.rs +++ b/src/gpu_model.rs @@ -442,6 +442,8 @@ pub const SNAP_STRIDE: usize = 4; pub struct GpuModel<'a> { m: &'a Model<'a>, + /// `STRATA_KV_HOST` prefill: VRAM copies of one host layer's K and V cache (see `load_part`). + kv_stage: Option<(Buf, Buf)>, pub gpu: Box, layers: Vec, output_norm: Option, @@ -742,8 +744,8 @@ impl<'a> GpuModel<'a> { q: lt(il, "attn_q.weight")?, k: lt(il, "attn_k.weight")?, v: lt(il, "attn_v.weight")?, qn: lt(il, "attn_q_norm.weight")?, kn: lt(il, "attn_k_norm.weight")?, o: lt(il, "attn_output.weight")?, sink: if c.attn_sinks { Some(lt(il, "attn_sinks.weight")?) } else { None }, - kc: (0..ns).map(|_| gpu.zeros::(gpu.kv_words(ctx * kv))).collect::>()?, - vc: (0..ns).map(|_| gpu.zeros::(gpu.kv_words(ctx * kv))).collect::>()?, + kc: (0..ns).map(|_| kv_alloc(gpu.as_ref(), il, gpu.kv_words(ctx * kv) * 2)).collect::>()?, + vc: (0..ns).map(|_| kv_alloc(gpu.as_ref(), il, gpu.kv_words(ctx * kv) * 2)).collect::>()?, qsa: if qsa_on && il < c.n_layer && m.w.layer(il, "indexer.k_proj.weight").is_ok() { Some(Qsa { kp: lt(il, "indexer.k_proj.weight")?, qp: lt(il, "indexer.q_proj.weight")?, @@ -904,8 +906,8 @@ impl<'a> GpuModel<'a> { qn: lt(il, "nextn.enorm.weight")?, kn: lt(il, "nextn.hnorm.weight")?, o: lt(il, "attn_output.weight")?, - kc: (0..ns).map(|_| gpu.zeros::(gpu.kv_words(ctx * eg_kv))).collect::>()?, - vc: (0..ns).map(|_| gpu.zeros::(gpu.kv_words(ctx * eg_kv))).collect::>()?, + kc: (0..ns).map(|_| kv_alloc(gpu.as_ref(), il, gpu.kv_words(ctx * eg_kv) * 2)).collect::>()?, + vc: (0..ns).map(|_| kv_alloc(gpu.as_ref(), il, gpu.kv_words(ctx * eg_kv) * 2)).collect::>()?, qsa: None, sink: None, }, @@ -1074,6 +1076,16 @@ impl<'a> GpuModel<'a> { } else { None }; + // STRATA_KV_HOST: one layer's cache-sized VRAM buffer pair. Prefill copies a host layer's cache prefix into it + // (a DMA copy, ~10x what the attention kernel reads from mapped memory) and runs the usual kernel on it. + let kv_stage = match layers.iter().enumerate().filter(|(il, _)| crate::host_attn::on_host(*il)) + .filter_map(|(_, l)| match &l.mixer { Mixer::Attn { kc, .. } => kc.first().map(|b| b.len()), _ => None }).max() { + Some(b) if std::env::var_os("STRATA_HA_NO_STAGE").is_none() => match (gpu.alloc(b), gpu.alloc(b)) { + (Ok(k), Ok(v)) => Some((k, v)), + _ => { crate::say!("host KV: no VRAM for the {} MB prefill staging, prefill reads the cache over PCIe", 2 * b >> 20); None } + }, + _ => None, + }; let (free1, _) = gpu.mem_info()?; // Past the budget the driver spills buffers to system memory: RADV then runs a long prefill slowly enough to // hit amdgpu's job timeout and lose the device. A margin above 512 MB only leaves fewer expert slots. @@ -1130,7 +1142,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, 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, reset_counts_after_prefill, hits: 0, misses: 0, tokens: 0, mailbox_writes: Default::default(), mailbox_reads: Default::default(), pids, 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, - cur: 0, seqs, rows: vec![], row_tokens: 0 }) + cur: 0, seqs, rows: vec![], row_tokens: 0, kv_stage }) } /// Clear KV and recurrent state (and forget the `prefill_cached` prefix, whose KV this zeroes). @@ -3008,8 +3020,11 @@ impl<'a> GpuModel<'a> { g.rope_neox(eg.k.addr(), hd, nt * nkv, nkv, ec.n_rot, h.step_buf.addr(), ec.rope_base) })?; g.kv_store(eg.k.addr(), eg.v.addr(), kc[self.cur].addr(), vc[self.cur].addr(), kv, nt, h.step_buf.addr(), hd)?; - g.attn_decode_q(eg.q.addr(), kc[self.cur].addr(), vc[self.cur].addr(), 0, eg.att.addr(), - eg.attp.addr(), h.step_buf.addr(), nh, nkv, hd, 1.0 / (hd as f32).sqrt(), gq, nt, 0, 0, 0, 0, 0)?; + if !(crate::host_attn::on_host(self.m.cfg.n_layer) + && g.attn_host(eg.q.addr(), kc[self.cur].addr(), vc[self.cur].addr(), 0, eg.att.addr(), h.step_buf.addr(), nh, nkv, hd, 1.0 / (hd as f32).sqrt(), nt)?) { + g.attn_decode_q(eg.q.addr(), kc[self.cur].addr(), vc[self.cur].addr(), 0, eg.att.addr(), + eg.attp.addr(), h.step_buf.addr(), nh, nkv, hd, 1.0 / (hd as f32).sqrt(), gq, nt, 0, 0, 0, 0, 0)?; + } self.mv(o, eg.att.addr(), nh * hd, self.bufs["mix"].addr(), ne, nt)?; g.rms_norm_q(x, ne, h.layer.post_norm.as_ref().unwrap().ptr, hp, ne, ne, nt, eps, 0, self.bufs["mix"].addr())?; g.batch(&mut || { @@ -3265,8 +3280,10 @@ impl<'a> GpuModel<'a> { _ => (0, 0), }; let out_gemm = vg && (nh * hd) % 64 == 0; - let aq = g.attn_decode_q(p("q"), kc[self.cur].addr(), vc[self.cur].addr(), if c.q_gate { p("qg") } else { 0 }, p("att"), p("attp"), step, nh, nkv, hd, - 1.0 / (hd as f32).sqrt(), gq, nt, if out_gemm { 0 } else { p("attq") }, sel, sst, sink_addr, win)?; + let host = sel == 0 && sink_addr == 0 && win == 0 && crate::host_attn::on_host(il) + && g.attn_host(p("q"), kc[self.cur].addr(), vc[self.cur].addr(), if c.q_gate { p("qg") } else { 0 }, p("att"), step, nh, nkv, hd, 1.0 / (hd as f32).sqrt(), nt)?; + let aq = if host { 0 } else { g.attn_decode_q(p("q"), kc[self.cur].addr(), vc[self.cur].addr(), if c.q_gate { p("qg") } else { 0 }, p("att"), p("attp"), step, nh, nkv, hd, + 1.0 / (hd as f32).sqrt(), gq, nt, if out_gemm { 0 } else { p("attq") }, sel, sst, sink_addr, win)? }; if out_gemm { g.gemm_dense(o, nt, p("att"), nh * hd, p("mix"), ne, 0)?; } else if aq != 0 { @@ -3641,3 +3658,9 @@ mod tests { fn _uses(g: &GpuModel) -> (bool, usize) { (g.expert_fast_path(), g.expert_bytes_per_token()) } } } + +/// `STRATA_KV_HOST=N`: the KV cache of the attention layers from block N on lives in host RAM (mapped pinned +/// memory the GPU reads over PCIe), freeing VRAM for a longer context. `all` = every layer. +fn kv_alloc(gpu: &dyn Backend, il: usize, bytes: usize) -> anyhow::Result { + if crate::host_attn::on_host(il) { gpu.alloc_host(bytes) } else { gpu.alloc(bytes) } +} diff --git a/src/gpu_model/prefill.rs b/src/gpu_model/prefill.rs index 838dd90f..263afb23 100644 --- a/src/gpu_model/prefill.rs +++ b/src/gpu_model/prefill.rs @@ -482,7 +482,16 @@ impl GpuModel<'_> { }; let sink_addr = sink.as_ref().map_or(0, |s| s.ptr); let win = c.swa.get(il).copied().unwrap_or(false).then_some(c.n_swa).unwrap_or(0); - g.attn_prefill_m(at(l.b), kc[self.cur].addr(), vc[self.cur].addr(), if c.q_gate { at(l.a) } else { 0 }, at(l.d), step, t, nh, nkv, hd, 1.0 / (hd as f32).sqrt(), qm, mw, sink_addr, win)?; + let (kca, vca) = match &self.kv_stage { + Some((sk, sv)) if crate::host_attn::on_host(il) => { + let bytes = (g.kv_words((self.pos + t) * kv) * 2).min(sk.len()); + g.dtod(&kc[self.cur], 0, sk, 0, bytes)?; + g.dtod(&vc[self.cur], 0, sv, 0, bytes)?; + (sk.addr(), sv.addr()) + } + _ => (kc[self.cur].addr(), vc[self.cur].addr()), + }; + g.attn_prefill_m(at(l.b), kca, vca, if c.q_gate { at(l.a) } else { 0 }, at(l.d), step, t, nh, nkv, hd, 1.0 / (hd as f32).sqrt(), qm, mw, sink_addr, win)?; probe(&mut tr, "q", &pf.slab, at(l.a), nh * qs, t)?; probe(&mut tr, "k", &pf.slab, kk, kv, t)?; probe(&mut tr, "v", &pf.slab, vv, kv, t)?; diff --git a/src/host_attn.rs b/src/host_attn.rs new file mode 100644 index 00000000..e00ef5c8 --- /dev/null +++ b/src/host_attn.rs @@ -0,0 +1,379 @@ +//! Decode attention on the CPU for KV caches in host RAM (`STRATA_KV_HOST`). The GPU copies the queries and +//! positions into mapped pinned memory, a stream host function runs this over the cache rows (the CPU reads RAM +//! far faster than the GPU does over PCIe), and `attn_merge` turns the one split per head into the output. +use rayon::prelude::*; + +/// Pointers are host addresses of mapped pinned memory (the same as their device addresses under UVA). +pub struct HostAttn { + pub q: usize, pub step: usize, pub part: usize, pub kc: usize, pub vc: usize, + pub nh: usize, pub nkv: usize, pub hd: usize, pub nt: usize, pub scale: f32, pub mode: u32, +} + +const CHUNK: usize = 1024; + +fn row_bytes(mode: u32, hd: usize) -> usize { + match mode { 0 => 2 * hd, 1 => hd + hd / 16, _ => hd / 2 + hd / 16 } +} + +/// Dequantize a cache row. q4 comes out permuted inside each 32-value block (the 16 low nibbles, then the 16 +/// high ones: values 0 2 4 .. 30, then 1 3 .. 31), which keeps the unpacking contiguous; `perm` maps a value index +/// to its place, and the queries and outputs use the same order. +#[inline(always)] +fn deq(mode: u32, r: &[u8], hd: usize, out: &mut [f32]) { + match mode { + 0 => for (o, c) in out[..hd].iter_mut().zip(r.chunks_exact(2)) { *o = half::f16::from_le_bytes([c[0], c[1]]).to_f32(); }, + 1 => for b in 0..hd / 32 { + let d = half::f16::from_le_bytes([r[hd + 2 * b], r[hd + 2 * b + 1]]).to_f32(); + let src: &[u8; 32] = r[b * 32..b * 32 + 32].try_into().unwrap(); + let dst: &mut [f32; 32] = (&mut out[b * 32..b * 32 + 32]).try_into().unwrap(); + for i in 0..32 { dst[i] = (src[i] as i8) as f32 * d; } + }, + _ => for b in 0..hd / 32 { + let d = half::f16::from_le_bytes([r[hd / 2 + 2 * b], r[hd / 2 + 2 * b + 1]]).to_f32(); + let src: &[u8; 16] = r[b * 16..b * 16 + 16].try_into().unwrap(); + let dst: &mut [f32; 32] = (&mut out[b * 32..b * 32 + 32]).try_into().unwrap(); + for i in 0..16 { + dst[i] = ((src[i] & 15) as f32 - 8.0) * d; + dst[16 + i] = ((src[i] >> 4) as f32 - 8.0) * d; + } + }, + } +} + +#[inline(always)] +fn perm(mode: u32, i: usize) -> usize { + if mode == 2 { let (b, w) = (i / 32, i % 32); b * 32 + if w % 2 == 0 { w / 2 } else { 16 + w / 2 } } else { i } +} + +#[inline(always)] +fn dot(a: &[f32], b: &[f32]) -> f32 { + // 64 lanes: four independent AVX-512 accumulators, so the FMAs do not wait on each other. + let mut s = [0f32; 16]; + for (x, y) in a.chunks_exact(16).zip(b.chunks_exact(16)) { for i in 0..16 { s[i] += x[i] * y[i]; } } + s.iter().sum() +} + +/// e^x for x <= 0 (softmax weights), ~1e-7 relative error, branch-free so loops over it vectorize. +#[inline(always)] +fn fexp(x: f32) -> f32 { + let x = x.max(-87.0); + let t = x * std::f32::consts::LOG2_E; + let fi = t.floor(); + let f = t - fi; + let p = 1.0 + f * (0.693_147_2 + f * (0.240_226_5 + f * (0.055_504_11 + f * (0.009_618_129 + f * (0.001_333_355_8 + f * 0.000_154_035_3))))); + f32::from_bits(((fi as i32 + 127) << 23) as u32) * p +} + +/// (max, sum, acc[nh * hd] in `perm` order) of positions `p0..p1` for one token; `q` is in `perm` order. +/// All `nt` tokens at once (each cache row is read once for all of them): `q` is [token][head][hd], token t sees +/// positions up to `lim[t]`; results are [token][head]. +fn chunk(a: &HostAttn, q: &[f32], lim: &[usize], p0: usize, p1: usize) -> (Vec, Vec, Vec) { + #[cfg(target_arch = "x86_64")] + if a.mode == 2 && a.hd % 32 == 0 && std::is_x86_feature_detected!("avx512f") && std::is_x86_feature_detected!("avx512bw") { + let grp = a.nh / a.nkv; + macro_rules! go { ($($g:literal),*; $($t:literal),*) => { go!(@g [$($g),*] [$($t),*]) }; + (@g [$($g:literal),*] $ts:tt) => { match grp { $( $g => go!(@t $g $ts), )* _ => None } }; + (@t $g:literal [$($t:literal),*]) => { match lim.len() { $( $t => Some(unsafe { avx512::chunk_q4::<$g, $t>(a, q, lim, p0, p1) }), )* _ => None } }; + } + if let Some(r) = go!(1, 2, 4, 6, 8; 1, 2, 3, 4) { return r; } + } + chunk_generic(a, q, lim, p0, p1) +} + +fn softmax_rows(sc: &mut [f32], nh: usize, n: usize) -> (Vec, Vec) { + let mut m = vec![f32::NEG_INFINITY; nh]; + let mut l = vec![0f32; nh]; + for h in 0..nh { + let s = &mut sc[h * n..(h + 1) * n]; + m[h] = s.iter().cloned().fold(f32::NEG_INFINITY, f32::max); + let mh = m[h]; + if mh == f32::NEG_INFINITY { s.fill(0.0); continue; } + let mut sum = 0.0; + for x in s.iter_mut() { *x = fexp(*x - mh); sum += *x; } + l[h] = sum; + } + (m, l) +} + +#[cfg(target_arch = "x86_64")] +mod avx512 { + use super::*; + use std::arch::x86_64::*; + + /// The 32 values of q4 block `b` of row `r`, scaled: (low nibbles = even values, high = odd), as `perm` orders them. + #[inline(always)] + unsafe fn blk(r: *const u8, hd: usize, b: usize) -> (__m512, __m512) { + unsafe { + let d = _mm512_set1_ps(half::f16::from_bits((r.add(hd / 2 + 2 * b) as *const u16).read_unaligned()).to_f32()); + let x = _mm512_cvtepu8_epi32(_mm_loadu_si128(r.add(16 * b) as *const __m128i)); + let e = _mm512_set1_ps(8.0); + let lo = _mm512_sub_ps(_mm512_cvtepi32_ps(_mm512_and_si512(x, _mm512_set1_epi32(15))), e); + let hi = _mm512_sub_ps(_mm512_cvtepi32_ps(_mm512_srli_epi32::<4>(x)), e); + (_mm512_mul_ps(lo, d), _mm512_mul_ps(hi, d)) + } + } + + /// K scores with int8 dot products (VNNI `vpdpbusd`, 64 products an instruction): the queries quantized to int8 + /// per 32-value block (as llama.cpp's q8_0 activations), the cache nibbles as unsigned bytes, and the -8 offset + /// folded in through each block's query sum. head_dim 256 (8 blocks: 4 vectors of 2 blocks, 8 f16 scales). + #[target_feature(enable = "avx512f,avx512bw,avx512vnni,f16c,avx2")] + unsafe fn kscores_vnni(a: &HostAttn, q: &[f32], lim: &[usize], p0: usize, p1: usize, sc: &mut [f32]) { + let (nh, nkv, hd) = (a.nh, a.nkv, a.hd); + let (rb, n, rows) = (hd / 2 + hd / 16, p1 - p0, T * nh); + let mut qq = vec![0i8; rows * hd]; + let mut qs = vec![0f32; rows * 64]; // per row, 4 vectors of 16 lanes: the block scale of each lane + let mut cl = vec![0f32; rows * 64]; // the scale times the block's int8 sum + for r in 0..rows { + for b in 0..8 { + let x = &q[r * hd + 32 * b..r * hd + 32 * b + 32]; + let mx = x.iter().fold(0f32, |m, v| m.max(v.abs())); + let d = mx / 127.0; + let id = if d > 0.0 { 1.0 / d } else { 0.0 }; + let mut sum = 0i32; + for i in 0..32 { let v = (x[i] * id).round() as i32; qq[r * hd + 32 * b + i] = v as i8; sum += v; } + for k in 0..8 { qs[r * 64 + 8 * b + k] = d; cl[r * 64 + 8 * b + k] = d * sum as f32; } + } + } + unsafe { + let m4 = _mm256_set1_epi8(15); + let order = _mm512_setr_epi64(0, 1, 4, 5, 2, 3, 6, 7); + let sidx: [__m512i; 4] = std::array::from_fn(|j| _mm512_setr_epi32( + 2 * j as i32, 2 * j as i32, 2 * j as i32, 2 * j as i32, 2 * j as i32, 2 * j as i32, 2 * j as i32, 2 * j as i32, + 2 * j as i32 + 1, 2 * j as i32 + 1, 2 * j as i32 + 1, 2 * j as i32 + 1, 2 * j as i32 + 1, 2 * j as i32 + 1, 2 * j as i32 + 1, 2 * j as i32 + 1)); + let kc = a.kc as *const u8; + let (qqp, qsp, clp) = (qq.as_ptr(), qs.as_ptr(), cl.as_ptr()); + for p in p0..p1 { + for g in 0..nkv { + let r = kc.add((p * nkv + g) * rb); + let d8 = _mm512_castps256_ps512(_mm256_cvtph_ps(_mm_loadu_si128(r.add(hd / 2) as *const __m128i))); + let mut z = [_mm512_setzero_si512(); 4]; + let mut dk = [_mm512_setzero_ps(); 4]; + for j in 0..4 { + let x = _mm256_loadu_si256(r.add(32 * j) as *const __m256i); + let lo = _mm256_and_si256(x, m4); + let hi = _mm256_and_si256(_mm256_srli_epi16::<4>(x), m4); + z[j] = _mm512_permutexvar_epi64(order, _mm512_inserti64x4::<1>(_mm512_castsi256_si512(lo), hi)); + dk[j] = _mm512_permutexvar_ps(sidx[j], d8); + } + for t in 0..T { + if p > lim[t] { continue; } + for h in 0..G { + let row = t * nh + g * G + h; + let mut acc = _mm512_setzero_ps(); + for j in 0..4 { + let dot = _mm512_dpbusd_epi32(_mm512_setzero_si512(), z[j], _mm512_loadu_si512(qqp.add(row * hd + 64 * j) as *const _)); + let v = _mm512_fmsub_ps(_mm512_cvtepi32_ps(dot), _mm512_loadu_ps(qsp.add(row * 64 + 16 * j)), _mm512_loadu_ps(clp.add(row * 64 + 16 * j))); + acc = _mm512_fmadd_ps(v, dk[j], acc); + } + *sc.get_unchecked_mut(row * n + p - p0) = _mm512_reduce_add_ps(acc) * a.scale; + } + } + } + } + } + } + + #[target_feature(enable = "avx512f,avx512bw,f16c")] + pub unsafe fn chunk_q4(a: &HostAttn, q: &[f32], lim: &[usize], p0: usize, p1: usize) -> (Vec, Vec, Vec) { + let (nh, nkv, hd, nt) = (a.nh, a.nkv, a.hd, T); + let (rb, nb, n) = (hd / 2 + hd / 16, hd / 32, p1 - p0); + let (kc, vc) = (a.kc as *const u8, a.vc as *const u8); + let rows = nt * nh; + let mut sc = vec![f32::NEG_INFINITY; rows * n]; + let qp = q.as_ptr(); + unsafe { + if nb == 8 && std::is_x86_feature_detected!("avx512vnni") { + kscores_vnni::(a, q, lim, p0, p1, &mut sc); + } else { + for p in p0..p1 { + for g in 0..nkv { + let r = kc.add((p * nkv + g) * rb); + for t in 0..T { + if p > lim[t] { continue; } + let mut acc = [_mm512_setzero_ps(); G]; + for b in 0..nb { + let (lo, hi) = blk(r, hd, b); + for h in 0..G { + let qh = qp.add((t * nh + g * G + h) * hd + 32 * b); + acc[h] = _mm512_fmadd_ps(lo, _mm512_loadu_ps(qh), acc[h]); + acc[h] = _mm512_fmadd_ps(hi, _mm512_loadu_ps(qh.add(16)), acc[h]); + } + } + for h in 0..G { sc[(t * nh + g * G + h) * n + p - p0] = _mm512_reduce_add_ps(acc[h]) * a.scale; } + } + } + } + } + let (m, l) = softmax_rows(&mut sc, rows, n); + let mut out = vec![0f32; rows * hd]; + // V by 32-value block: the accumulators of the G heads of each token stay in registers (or L1) over all positions. + for g in 0..nkv { + for b in 0..nb { + // One token at a time: 2 G accumulators stay in registers (all T tokens' would spill). + for t in 0..T { + let mut al = [_mm512_setzero_ps(); G]; + let mut ah = [_mm512_setzero_ps(); G]; + let pe = p1.min(lim[t] + 1); + for p in p0..pe { + let (lo, hi) = blk(vc.add((p * nkv + g) * rb), hd, b); + for h in 0..G { + let w = _mm512_set1_ps(*sc.get_unchecked((t * nh + g * G + h) * n + p - p0)); + al[h] = _mm512_fmadd_ps(w, lo, al[h]); + ah[h] = _mm512_fmadd_ps(w, hi, ah[h]); + } + } + for h in 0..G { + let o = out.as_mut_ptr().add((t * nh + g * G + h) * hd + 32 * b); + _mm512_storeu_ps(o, al[h]); + _mm512_storeu_ps(o.add(16), ah[h]); + } + } + } + } + (m, l, out) + } + } +} + +fn chunk_generic(a: &HostAttn, q: &[f32], lim: &[usize], p0: usize, p1: usize) -> (Vec, Vec, Vec) { + let w = a.nh * a.hd; + let (mut m, mut l, mut acc) = (vec![], vec![], vec![]); + for (t, <) in lim.iter().enumerate() { + let e = (lt + 1).min(p1).max(p0); + let (mt, lt, at) = if e > p0 { chunk1(a, &q[t * w..(t + 1) * w], p0, e) } else { (vec![f32::NEG_INFINITY; a.nh], vec![0.0; a.nh], vec![0.0; w]) }; + m.extend(mt); l.extend(lt); acc.extend(at); + } + (m, l, acc) +} + +fn chunk1(a: &HostAttn, q: &[f32], p0: usize, p1: usize) -> (Vec, Vec, Vec) { + let (nh, nkv, hd) = (a.nh, a.nkv, a.hd); + let grp = nh / nkv; + let rb = row_bytes(a.mode, hd); + let kc = unsafe { std::slice::from_raw_parts(a.kc as *const u8, p1 * nkv * rb) }; + let vc = unsafe { std::slice::from_raw_parts(a.vc as *const u8, p1 * nkv * rb) }; + let n = p1 - p0; + let mut sc = vec![0f32; nh * n]; + let mut row = vec![0f32; hd]; + for p in p0..p1 { + for g in 0..nkv { + let r = (p * nkv + g) * rb; + deq(a.mode, &kc[r..r + rb], hd, &mut row); + for h in g * grp..(g + 1) * grp { sc[h * n + p - p0] = dot(&q[h * hd..(h + 1) * hd], &row) * a.scale; } + } + } + let mut m = vec![f32::NEG_INFINITY; nh]; + let mut l = vec![0f32; nh]; + for h in 0..nh { + let s = &mut sc[h * n..(h + 1) * n]; + m[h] = s.iter().cloned().fold(f32::NEG_INFINITY, f32::max); + let mh = m[h]; + if mh == f32::NEG_INFINITY { s.fill(0.0); continue; } + let mut sum = 0.0; + for x in s.iter_mut() { *x = fexp(*x - mh); sum += *x; } + l[h] = sum; + } + let mut acc = vec![0f32; nh * hd]; + for p in p0..p1 { + for g in 0..nkv { + let r = (p * nkv + g) * rb; + deq(a.mode, &vc[r..r + rb], hd, &mut row); + for h in g * grp..(g + 1) * grp { + let w = sc[h * n + p - p0]; + for (o, v) in acc[h * hd..(h + 1) * hd].iter_mut().zip(&row) { *o += w * v; } + } + } + } + (m, l, acc) +} + +static PROF: std::sync::Mutex<(u32, f64, usize, f64)> = std::sync::Mutex::new((0, 0.0, 0, 0.0)); + +pub fn run(a: &HostAttn) { + let t0 = std::time::Instant::now(); + run_inner(a); + if std::env::var_os("STRATA_HA_PROF").is_some() { + let mut p = PROF.lock().unwrap(); + p.0 += 1; p.1 += t0.elapsed().as_secs_f64(); p.2 += a.nt; + if p.0 % 320 == 0 { + let pos = unsafe { *(a.step as *const i32) }; + eprintln!("host_attn window: {:.2} ms/call, {:.2} tokens/call, pos {pos}", 1e3 * p.1 / p.0 as f64, p.2 as f64 / p.0 as f64); + *p = (0, 0.0, 0, 0.0); + } + } +} + +/// Its own pool on every logical core (`STRATA_HA_THREADS` overrides): the global one has one thread a physical +/// core for the memory-bound GPU expert work, while this int8/f32 math gains from SMT (2.8 to 2.2 ms a layer at 52K). +fn pool() -> &'static rayon::ThreadPool { + static P: std::sync::OnceLock = std::sync::OnceLock::new(); + P.get_or_init(|| { + let n = std::env::var("STRATA_HA_THREADS").ok().and_then(|v| v.parse().ok()) + .unwrap_or_else(|| std::thread::available_parallelism().map_or(8, |n| n.get())); + rayon::ThreadPoolBuilder::new().num_threads(n).thread_name(|i| format!("host-attn-{i}")).build().unwrap() + }) +} + +fn run_inner(a: &HostAttn) { + let (nh, hd, nt) = (a.nh, a.hd, a.nt); + let lim: Vec = (0..nt).map(|t| unsafe { *(a.step as *const i32).add(2 * t) } as usize).collect(); + let q0 = unsafe { std::slice::from_raw_parts(a.q as *const f32, nt * nh * hd) }; + let mut q = vec![0f32; nt * nh * hd]; + for r in 0..nt * nh { for i in 0..hd { q[r * hd + perm(a.mode, i)] = q0[r * hd + i]; } } + let n = lim.iter().max().unwrap() + 1; + let parts: Vec<_> = pool().install(|| (0..n.div_ceil(CHUNK)).into_par_iter().map(|c| chunk(a, &q, &lim, c * CHUNK, ((c + 1) * CHUNK).min(n))).collect()); + let part = unsafe { std::slice::from_raw_parts_mut(a.part as *mut f32, nt * nh * (hd + 2)) }; + for r in 0..nt * nh { + let mm = parts.iter().map(|p| p.0[r]).fold(f32::NEG_INFINITY, f32::max); + let o = &mut part[r * (hd + 2)..(r + 1) * (hd + 2)]; + o.fill(0.0); + let mut l = 0.0; + for p in &parts { + if p.0[r] == f32::NEG_INFINITY { continue; } + let w = (p.0[r] - mm).exp(); + l += p.1[r] * w; + for i in 0..hd { o[i] += p.2[r * hd + perm(a.mode, i)] * w; } + } + o[hd] = mm; + o[hd + 1] = l; + } +} + +pub unsafe extern "C" fn callback(user: *mut std::ffi::c_void) { + run(unsafe { &*(user as *const HostAttn) }); +} + +/// Whether block `il`'s KV cache lives in host RAM (`STRATA_KV_HOST=N`: blocks N and up, `all`: every one). +pub fn on_host(il: usize) -> bool { + match std::env::var("STRATA_KV_HOST").ok().as_deref() { + None | Some("") => false, + Some("all") => true, + Some(v) => v.parse::().is_ok_and(|n| il >= n), + } +} + +/// The CPU side of the `ha_post`/`ha_wait` mailbox at host address `mb` (u32 words: request at 0, context pointer +/// at 4-5, done at 16). Spins while requests come, naps after 2 ms without one. +pub fn start_worker(mb: usize) { + std::thread::Builder::new().name("host-attn".into()).spawn(move || { + let w = mb as *mut u32; + let mut last = 0u32; + let mut idle = std::time::Instant::now(); + loop { + let r = unsafe { std::ptr::read_volatile(w) }; + if r != last { + std::sync::atomic::fence(std::sync::atomic::Ordering::Acquire); + let ctx = unsafe { std::ptr::read_volatile(w.add(4) as *const u64) } as usize; + run(unsafe { &*(ctx as *const HostAttn) }); + std::sync::atomic::fence(std::sync::atomic::Ordering::SeqCst); + unsafe { std::ptr::write_volatile(w.add(16), r) }; + last = r; + idle = std::time::Instant::now(); + } else if idle.elapsed() > std::time::Duration::from_millis(2) { + std::thread::sleep(std::time::Duration::from_micros(50)); + } else { + std::hint::spin_loop(); + } + } + }).expect("host-attn thread"); +} diff --git a/src/lib.rs b/src/lib.rs index ed64b867..bc792c0d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,4 +1,5 @@ pub mod memory; +pub mod host_attn; pub mod term; pub mod calibrate;