From cecbe3a306c3e69d0ed46bac7e69577535708ce9 Mon Sep 17 00:00:00 2001 From: SubgridAI Date: Sun, 6 Dec 2026 07:34:19 +0000 Subject: [PATCH 1/3] cuda: STRATA_MLOCK_EXPERTS registers the staging experts with the device (CUDA pin_host) #206 registers the locked expert pages on HIP so a prompt's cold-expert staging is one DMA from the mapped file; the CUDA backend had no pin_host and kept copying through the pinned ring. This adds it: - pin_host: cuMemHostRegister of the whole pages inside the tensor, READ_ONLY|PORTABLE, then PORTABLE. GeForce cards (no CU_DEVICE_ATTRIBUTE_READ_ONLY_HOST_REGISTER_SUPPORTED) refuse the shared read-only file mapping with CUDA_ERROR_INVALID_VALUE, so the range is then swapped in place (MAP_FIXED|MAP_PRIVATE|MAP_ANONYMOUS, same bytes, same addresses) and registered PORTABLE. - A process-wide registry of those ranges: host_is_pinned on every device sees them (a range registered PORTABLE by one context is pinned for all; each Gpu kept only its own list), and the registering Gpu unregisters at drop. - The #206 caller takes only layers with experts outside the slots where the backend says so (pin_cold_only: true on CUDA, where the fallback costs RAM; HIP unchanged). 4x RTX 3060 12 GB, Qwen4-35B-A3B UD-Q5_K_M, ctx 1M, --split 27,25,27,21 (one card holds 2581/2816 experts): 2.36-4.13 GB in 4-7 layers registered in 3.6-6.3 s; that card's staging 126 -> 68 ms a 4096-token chunk (3.6 -> ~6.5 GB/s). Pinning is not bounded by RLIMIT_MEMLOCK (8 MB shell limit, 2.36 GB pinned). Co-Authored-By: Claude Opus 5.5 --- src/backend.rs | 3 ++ src/cuda/mod.rs | 74 +++++++++++++++++++++++++++++++++++++++++++++++- src/gpu_model.rs | 13 +++++---- 3 files changed, 84 insertions(+), 6 deletions(-) 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..fc465750 100644 --- a/src/cuda/mod.rs +++ b/src/cuda/mod.rs @@ -1338,6 +1338,43 @@ 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 `Gpu` that registered them 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); } + if PINNED_FILE.lock().unwrap().iter().any(|&(s, e, _)| s <= pa && pb <= e) { return Ok(true); } + 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 { + PINNED_FILE.lock().unwrap().push((pa, pb, self as *const Gpu as usize)); + 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`). + let len = pb - pa; + if remap_anon(pa, len) { + last = unsafe { sys::cuMemHostRegister_v2(pa as *mut _, len, sys::CU_MEMHOSTREGISTER_PORTABLE) }; + if last == sys::CUresult::CUDA_SUCCESS { + PINNED_FILE.lock().unwrap().push((pa, pb, self as *const Gpu as usize)); + 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 +2206,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> { @@ -2814,11 +2853,44 @@ mod tests { } } +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; +} + +/// Replaces the pages `[pa, pa+len)` of a read-only file mapping with private anonymous pages holding the same bytes. +fn remap_anon(pa: usize, len: usize) -> bool { + 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 +} + +/// Pages of the mapped model file `pin_host` registered (start, end, the `Gpu` that registered them): portable, so +/// every device's `htod` DMAs from them; the registering `Gpu` unregisters them when it drops. +static PINNED_FILE: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + 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 _) }; } } + let me = self as *const Gpu as usize; + let mine: Vec = { + let mut g = PINNED_FILE.lock().unwrap(); + let v = g.iter().filter(|r| r.2 == me).map(|r| r.0).collect(); + g.retain(|r| r.2 != me); + v + }; + if !mine.is_empty() && self.ctx.bind_to_thread().is_ok() { + for p in mine { 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) { From f9c47cb14d657e48be374042229ab40ebd88538d Mon Sep 17 00:00:00 2001 From: SubgridAI Date: Sun, 6 Dec 2026 08:29:31 +0000 Subject: [PATCH 2/3] cuda pin_host: Linux-only remap, fallback only on INVALID_VALUE, last Gpu unregisters - remap_anon calls mmap: gate it to Linux like weights::mlock, so the Windows build links. - The anonymous remap runs only when registration failed with CUDA_ERROR_INVALID_VALUE (the read-only file mapping a GeForce card refuses); any other failure leaves the mapping alone. - PINNED_FILE ranges are portable and used by every device, so they stay registered until the last Gpu (new or share) drops, not the one that registered them. A context that can't be bound leaves them listed, since they are still registered. - pin_host holds the PINNED_FILE lock across check and register. - Test: remap_anon keeps the bytes and addresses of a read-only file mapping (no device). Co-Authored-By: Claude Opus 5.5 --- src/cuda/mod.rs | 83 ++++++++++++++++++++++++++++++++++--------------- 1 file changed, 58 insertions(+), 25 deletions(-) diff --git a/src/cuda/mod.rs b/src/cuda/mod.rs index fc465750..5f86fe68 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. @@ -1343,32 +1347,35 @@ impl Backend for Gpu { /// 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 `Gpu` that registered them drops (before the mapping goes). + /// 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); } - if PINNED_FILE.lock().unwrap().iter().any(|&(s, e, _)| s <= pa && pb <= e) { return Ok(true); } + // 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); } 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 { - PINNED_FILE.lock().unwrap().push((pa, pb, self as *const Gpu as usize)); + 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`). + // 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 remap_anon(pa, len) { + 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 { - PINNED_FILE.lock().unwrap().push((pa, pb, self as *const Gpu as usize)); + reg.push((pa, pb)); return Ok(true); } } @@ -2208,7 +2215,7 @@ impl Backend for Gpu { let start = data.as_ptr() as usize; 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) + || PINNED_FILE.lock().unwrap().iter().any(|&(s, e)| start >= s && start + data.len() <= e) } fn host_register(&self, p: usize, len: usize) -> anyhow::Result> { @@ -2233,6 +2240,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())); @@ -2853,12 +2883,13 @@ mod tests { } } -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; -} - /// 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); @@ -2871,10 +2902,14 @@ fn remap_anon(pa: usize, len: usize) -> bool { } true } +#[cfg(not(target_os = "linux"))] +fn remap_anon(_: usize, _: usize) -> bool { false } -/// Pages of the mapped model file `pin_host` registered (start, end, the `Gpu` that registered them): portable, so -/// every device's `htod` DMAs from them; the registering `Gpu` unregisters them when it drops. -static PINNED_FILE: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); +/// 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) { @@ -2882,15 +2917,13 @@ impl Drop for Gpu { if !pinned.is_empty() && self.ctx.bind_to_thread().is_ok() { for (p, _) in pinned { unsafe { sys::cuMemHostUnregister(p as *mut _) }; } } - let me = self as *const Gpu as usize; - let mine: Vec = { + // 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. + if LIVE_GPUS.fetch_sub(1, std::sync::atomic::Ordering::SeqCst) == 1 { let mut g = PINNED_FILE.lock().unwrap(); - let v = g.iter().filter(|r| r.2 == me).map(|r| r.0).collect(); - g.retain(|r| r.2 != me); - v - }; - if !mine.is_empty() && self.ctx.bind_to_thread().is_ok() { - for p in mine { unsafe { sys::cuMemHostUnregister(p as *mut _) }; } + if !g.is_empty() && self.ctx.bind_to_thread().is_ok() { + for (p, _) in g.drain(..) { unsafe { sys::cuMemHostUnregister(p as *mut _) }; } + } } } } From 8847b6a367162393f78fc15221950dbb0a1f307c Mon Sep 17 00:00:00 2001 From: SubgridAI Date: Sun, 6 Dec 2026 15:19:15 +0000 Subject: [PATCH 3/3] cuda pin_host: count Gpu drops under the registry lock; skip partly overlapping ranges - Drop decrements LIVE_GPUS while holding PINNED_FILE, which pin_host holds too, so a Gpu created during the last drop either keeps the count up or registers the ranges anew. - A range that partly overlaps a registered one is left to the ring (never seen: ranges are the whole pages inside distinct tensors). Co-Authored-By: Claude Opus 5.5 --- src/cuda/mod.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/cuda/mod.rs b/src/cuda/mod.rs index 5f86fe68..8fb5b062 100644 --- a/src/cuda/mod.rs +++ b/src/cuda/mod.rs @@ -1357,6 +1357,9 @@ impl Backend for Gpu { // 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] { @@ -2919,8 +2922,10 @@ impl Drop for Gpu { } // 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 { - let mut g = PINNED_FILE.lock().unwrap(); if !g.is_empty() && self.ctx.bind_to_thread().is_ok() { for (p, _) in g.drain(..) { unsafe { sys::cuMemHostUnregister(p as *mut _) }; } }