diff --git a/src/backend.rs b/src/backend.rs index efbacad0..5d2152a5 100644 --- a/src/backend.rs +++ b/src/backend.rs @@ -205,6 +205,9 @@ pub trait Backend: Send { /// Page-lock `data` (host memory that outlives this backend, such as the mapped model file), so `htod` from it /// is a DMA without a copy through a staging buffer. False when the backend does not do that. fn pin_host(&self, _data: &[u8]) -> anyhow::Result { Ok(false) } + /// Whether `pin_host` should be given only the experts that can stage (layers with experts outside the slots): + /// true where registering may copy the pages into RAM (CUDA's fallback for a read-only mapping). + fn pin_cold_only(&self) -> bool { false } fn side_mark(&self) -> anyhow::Result { Ok(0) } fn main_waits(&self, _side_mark: usize) -> anyhow::Result<()> { Ok(()) } fn main_mark(&self) -> anyhow::Result { Ok(0) } diff --git a/src/cuda/mod.rs b/src/cuda/mod.rs index 989c3f11..8fb5b062 100644 --- a/src/cuda/mod.rs +++ b/src/cuda/mod.rs @@ -768,7 +768,9 @@ impl Gpu { let ring = std::sync::Mutex::new((unsafe { ctx.alloc_pinned::(RING)? }, 0, VecDeque::new())); let done = ctx.new_event(None)?; let sms = ctx.attribute(sys::CUdevice_attribute::CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT)? as usize; - Ok(Gpu { ctx, side: stream.fork()?, copy: stream.fork()?, in_copy: Default::default(), copy_ev: Default::default(), stream, nb: AtomicUsize::new(usize::MAX), fns, i8_gemm, dp4a_gemm, q8, prefill_input: Default::default(), moe_gate_q8: Default::default(), gd: Default::default(), sk: Default::default(), xh: Default::default(), xk: Default::default(), skc: Default::default(), sms, kv_mode: if kv_k_mode == kv_v_mode { kv_k_mode } else { 10 }, kv_k_mode, kv_v_mode, flags, int8_mma, turing, max_smem: max_optin, am, graphs: Default::default(), ring, marks: Default::default(), done, lag: Default::default(), fr: Default::default(), cs: Default::default(), mla_part: Default::default(), pinned: Default::default() }) + let g = Gpu { ctx, side: stream.fork()?, copy: stream.fork()?, in_copy: Default::default(), copy_ev: Default::default(), stream, nb: AtomicUsize::new(usize::MAX), fns, i8_gemm, dp4a_gemm, q8, prefill_input: Default::default(), moe_gate_q8: Default::default(), gd: Default::default(), sk: Default::default(), xh: Default::default(), xk: Default::default(), skc: Default::default(), sms, kv_mode: if kv_k_mode == kv_v_mode { kv_k_mode } else { 10 }, kv_k_mode, kv_v_mode, flags, int8_mma, turing, max_smem: max_optin, am, graphs: Default::default(), ring, marks: Default::default(), done, lag: Default::default(), fr: Default::default(), cs: Default::default(), mla_part: Default::default(), pinned: Default::default() }; + LIVE_GPUS.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + Ok(g) } fn f(&self, name: &str) -> &CudaFunction { &self.fns[name] } @@ -1276,7 +1278,7 @@ impl Backend for Gpu { let am = self.stream.alloc_zeros(128 * AMAX_PARTS)?; let ring = std::sync::Mutex::new((unsafe { self.ctx.alloc_pinned::(RING)? }, 0, VecDeque::new())); let done = self.ctx.new_event(None)?; - Ok(Box::new(Gpu { + let g = Gpu { ctx: self.ctx.clone(), side: self.stream.fork()?, copy: self.stream.fork()?, @@ -1313,7 +1315,9 @@ impl Backend for Gpu { cs: Default::default(), mla_part: Default::default(), pinned: Default::default(), - })) + }; + LIVE_GPUS.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + Ok(Box::new(g)) } /// The type policy gated on this device: `gemm_raw` takes the f16 `gemm_*` path where the arch has no int8 /// tensor cores (Volta), so a test comparing kernels must not expect `gemmi_*` there. @@ -1338,6 +1342,49 @@ impl Backend for Gpu { // marks are events: `side_mark`/`main_mark` record the point a stream has reached, `main_waits`/`side_waits` // hold the other stream there (the callers in `prefill_ffn_pool` order the staging slots with them). fn htod_side(&self, src: &[u8], dst: &Buf, off: usize) -> anyhow::Result<()> { self.htod_to(src, dst, off, &self.side) } + + /// `cuMemHostRegister` of the whole pages inside `data` (the mapped model file: read-only where the driver takes + /// that flag, else plain), portable, so every device's `htod` DMAs from them without the ring. The edge pages + /// stay unpinned: tensors that share a page with a neighbour another device pinned never overlap a registration + /// (a copy touching them goes through the ring as before). The ranges are kept in `PINNED_FILE`, which every + /// device reads, and unregistered when the last `Gpu` drops (before the mapping goes). + fn pin_cold_only(&self) -> bool { true } + fn pin_host(&self, data: &[u8]) -> anyhow::Result { + const PAGE: usize = 4096; + let (a, b) = (data.as_ptr() as usize, data.as_ptr() as usize + data.len()); + let (pa, pb) = (a.div_ceil(PAGE) * PAGE, b & !(PAGE - 1)); + if pb <= pa { return Ok(false); } + // Held through the registration, so two devices handed the same range cannot both register (or remap) it. + let mut reg = PINNED_FILE.lock().unwrap(); + if reg.iter().any(|&(s, e)| s <= pa && pb <= e) { return Ok(true); } + // Ranges are the whole pages inside distinct tensors, so they never partly overlap; if one ever did, leave + // it to the ring rather than register (or remap) pages another range holds. + if reg.iter().any(|&(s, e)| s < pb && pa < e) { return Ok(false); } + self.ctx.bind_to_thread()?; + let mut last = sys::CUresult::CUDA_SUCCESS; + for flags in [sys::CU_MEMHOSTREGISTER_READ_ONLY | sys::CU_MEMHOSTREGISTER_PORTABLE, sys::CU_MEMHOSTREGISTER_PORTABLE] { + last = unsafe { sys::cuMemHostRegister_v2(pa as *mut _, pb - pa, flags) }; + if last == sys::CUresult::CUDA_SUCCESS { + reg.push((pa, pb)); + return Ok(true); + } + } + // The model file is a shared read-only mapping, and cards without CU_DEVICE_ATTRIBUTE_READ_ONLY_HOST_REGISTER_ + // SUPPORTED (GeForce) refuse to register it (CUDA_ERROR_INVALID_VALUE): swap these pages in place for private + // anonymous ones holding the same bytes (same addresses, so every tensor slice stays valid) and pin those. + // This costs their size in RAM; the caller hands only the experts that can stage (`pin_cold_only`). Any other + // failure leaves the mapping as it is. + let len = pb - pa; + if last == sys::CUresult::CUDA_ERROR_INVALID_VALUE && remap_anon(pa, len) { + last = unsafe { sys::cuMemHostRegister_v2(pa as *mut _, len, sys::CU_MEMHOSTREGISTER_PORTABLE) }; + if last == sys::CUresult::CUDA_SUCCESS { + reg.push((pa, pb)); + return Ok(true); + } + } + crate::say!("warning: registering {} MB of expert pages failed ({last:?}); their staging goes through the ring", len >> 20); + Ok(false) + } fn side_mark(&self) -> anyhow::Result { self.mark(&self.side) } fn main_mark(&self) -> anyhow::Result { self.mark(&self.stream) } fn main_waits(&self, side_mark: usize) -> anyhow::Result<()> { self.wait_mark(&self.stream, side_mark) } @@ -2169,7 +2216,9 @@ 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) + || PINNED_FILE.lock().unwrap().iter().any(|&(s, e)| start >= s && start + data.len() <= e) } fn host_register(&self, p: usize, len: usize) -> anyhow::Result> { @@ -2194,6 +2243,29 @@ impl Backend for Gpu { #[cfg(test)] mod tests { + /// `pin_host`'s GeForce fallback: the pages of a read-only file mapping become private anonymous pages at the + /// same addresses with the same bytes, and writable (no device needed). + #[cfg(target_os = "linux")] + #[test] + fn remap_anon_keeps_bytes_and_addresses() { + const PAGE: usize = 4096; + let path = std::env::temp_dir().join(format!("strata_remap_{}", std::process::id())); + let data: Vec = (0..4 * PAGE).map(|i| (i * 7 % 251) as u8).collect(); + std::fs::write(&path, &data).unwrap(); + let f = std::fs::File::open(&path).unwrap(); + let map = unsafe { memmap2::Mmap::map(&f) }.unwrap(); + let base = map.as_ptr() as usize; + // The two middle pages, as `pin_host` would take them from a tensor spanning the file. + assert!(super::remap_anon(base + PAGE, 2 * PAGE)); + assert_eq!(map.as_ptr() as usize, base); + assert_eq!(&map[..], &data[..]); + unsafe { *((base + PAGE) as *mut u8) ^= 0xff }; + assert_eq!(map[PAGE], data[PAGE] ^ 0xff); + assert_eq!(std::fs::read(&path).unwrap(), data, "the file itself is untouched"); + drop(map); + std::fs::remove_file(&path).unwrap(); + } + #[test] fn prune_ptx_drops_only_stale_ptx() { let d = std::env::temp_dir().join(format!("strata_prune_{}", std::process::id())); @@ -2814,11 +2886,49 @@ mod tests { } } +/// Replaces the pages `[pa, pa+len)` of a read-only file mapping with private anonymous pages holding the same bytes. +/// Linux only (`STRATA_MLOCK_EXPERTS` locks nothing elsewhere); false on other systems. +#[cfg(target_os = "linux")] +fn remap_anon(pa: usize, len: usize) -> bool { + unsafe extern "C" { + fn mmap(addr: *mut std::ffi::c_void, len: usize, prot: i32, flags: i32, fd: i32, off: i64) -> *mut std::ffi::c_void; + } + const PROT_RW: i32 = 0x1 | 0x2; + const MAP_PRIVATE_ANON_FIXED: i32 = 0x02 | 0x20 | 0x10; + let mut tmp = Vec::::with_capacity(len); + unsafe { + std::ptr::copy_nonoverlapping(pa as *const u8, tmp.as_mut_ptr(), len); + tmp.set_len(len); + let r = mmap(pa as *mut _, len, PROT_RW, MAP_PRIVATE_ANON_FIXED, -1, 0); + if r as usize != pa { return false; } + std::ptr::copy_nonoverlapping(tmp.as_ptr(), pa as *mut u8, len); + } + true +} +#[cfg(not(target_os = "linux"))] +fn remap_anon(_: usize, _: usize) -> bool { false } + +/// Pages of the mapped model file `pin_host` registered (start, end): portable, so every device's `htod` DMAs from +/// them, whichever `Gpu` registered them. They stay registered until the last `Gpu` drops. +static PINNED_FILE: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); +/// `Gpu`s alive (`new` and `share`), so `PINNED_FILE` outlives every device that may DMA from it. +static LIVE_GPUS: AtomicUsize = AtomicUsize::new(0); + impl Drop for Gpu { fn drop(&mut self) { let pinned = std::mem::take(&mut *self.pinned.lock().unwrap()); if !pinned.is_empty() && self.ctx.bind_to_thread().is_ok() { for (p, _) in pinned { unsafe { sys::cuMemHostUnregister(p as *mut _) }; } } + // The last `Gpu` unregisters the file pages (portable, so any context can). If its context cannot be bound + // the ranges stay listed: they are still registered. + // Counted under the registry's lock, which `pin_host` holds too: a `Gpu` created meanwhile either keeps the + // count above zero or finds the ranges already gone and registers them again. + let mut g = PINNED_FILE.lock().unwrap(); + if LIVE_GPUS.fetch_sub(1, std::sync::atomic::Ordering::SeqCst) == 1 { + if !g.is_empty() && self.ctx.bind_to_thread().is_ok() { + for (p, _) in g.drain(..) { unsafe { sys::cuMemHostUnregister(p as *mut _) }; } + } + } } } diff --git a/src/gpu_model.rs b/src/gpu_model.rs index 8df4c0fd..a84b253f 100644 --- a/src/gpu_model.rs +++ b/src/gpu_model.rs @@ -1236,14 +1236,17 @@ impl<'a> GpuModel<'a> { }; Some(ExpertCache::new(m, &*gpu, budget, range.start..range.end + (mtp && c.eagle3.is_none()) as usize)?) } else { None }; - // STRATA_MLOCK_EXPERTS has locked the experts' pages already; registering them with the device (`pin_host`, - // HIP only) lets a prompt's staging copies DMA from the mapped file instead of a host copy through the pinned - // ring, which held the copies under the link's rate. Qwen3.8-Flash-Next UD-IQ4_XS: 57.6 GB in 7 s at load. + // STRATA_MLOCK_EXPERTS has locked the experts' pages already; registering them with the device (`pin_host`) + // lets a prompt's staging copies DMA from the mapped file instead of a host copy through the pinned ring, which + // held the copies under the link's rate. Qwen3.8-Flash-Next UD-IQ4_XS: 57.6 GB in 7 s at load (HIP). // Not when the model exceeds RAM: `weights::cold` drops each staged run's pages there, under the device. - if cache.is_some() && std::env::var_os("STRATA_MLOCK_EXPERTS").is_some_and(|v| v != "0") && crate::weights::fits_ram() { + // A backend whose registration copies the pages (`pin_cold_only`: CUDA on cards without read-only + // registration) takes only the layers with experts outside the slots, the only ones that ever stage. + if let Some(cache) = cache.as_ref().filter(|_| std::env::var_os("STRATA_MLOCK_EXPERTS").is_some_and(|v| v != "0") && crate::weights::fits_ram()) { let t0 = std::time::Instant::now(); let mut bytes = 0usize; - 'pin: for il in range.clone().filter(|&il| c.is_moe_layer(il)) { + let cold = |il: usize| cache.layer(il).is_some() && !(0..c.n_expert).all(|e| cache.resident(il, e)); + 'pin: for il in range.clone().filter(|&il| c.is_moe_layer(il) && (!gpu.pin_cold_only() || cold(il))) { for name in crate::expert_cache::MATS { let Ok(w) = m.w.layer(il, name) else { continue }; match gpu.pin_host(w.data) {