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
3 changes: 3 additions & 0 deletions src/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<bool> { 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<usize> { Ok(0) }
fn main_waits(&self, _side_mark: usize) -> anyhow::Result<()> { Ok(()) }
fn main_mark(&self) -> anyhow::Result<usize> { Ok(0) }
Expand Down
118 changes: 114 additions & 4 deletions src/cuda/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -768,7 +768,9 @@ impl Gpu {
let ring = std::sync::Mutex::new((unsafe { ctx.alloc_pinned::<u8>(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] }
Expand Down Expand Up @@ -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::<u8>(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()?,
Expand Down Expand Up @@ -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.
Expand All @@ -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<bool> {
const PAGE: usize = 4096;
let (a, b) = (data.as_ptr() as usize, data.as_ptr() as usize + data.len());

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 · 3 of 5

Check-then-register on PINNED_FILE is not atomic, so concurrent pin_host calls race and the loser remaps pinned pages Two threads/devices call pin_host for the same range simultaneously, both pass the any() coverage check, both call cuMemHostRegister, the second fails, then remap_anon MAP_FIXED-remaps the range the first just pinned, leaving stale PINNED_FILE entries and unpinned memory.

Prompt for your AI agent
File: src/cuda/mod.rs
Line: 1350
Symbol: dtoh
Issue: Check-then-register on PINNED_FILE is not atomic, so concurrent pin_host calls race and the loser remaps pinned pages Two threads/devices call pin_host for the same range simultaneously, both pass the any() coverage check, both call cuMemHostRegister, the second fails, then remap_anon MAP_FIXED-remaps the range the first just pinned, leaving stale PINNED_FILE entries and unpinned memory.
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.

3 of 5 (Medium): check-then-register race — FIXED (not reachable before)

Today's loader never reaches this, because load_part loads the parts one after another and each part pins only its own layers, so no two calls see the same range. Still, pin_host now holds the PINNED_FILE lock across the check, the registration and the fallback, so concurrent loading can't double-register or remap a range.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟠 High · Correctness · 2 of 4

Partial overlap with an already-registered range is not detected Existing range [s,e) partially overlaps [pa,pb) but does not contain it, so the s<=pa && pb<=e check misses it; cuMemHostRegister fails with ALREADY_REGISTERED or, on INVALID_VALUE, remap_anon MAP_FIXEDs over pages another device has registered, dangling that registration and corrupting the shared registry.

Prompt for your AI agent
File: src/cuda/mod.rs
Line: 1359
Symbol: begin_prefill_read
Issue: Partial overlap with an already-registered range is not detected Existing range [s,e) partially overlaps [pa,pb) but does not contain it, so the s<=pa && pb<=e check misses it; cuMemHostRegister fails with ALREADY_REGISTERED or, on INVALID_VALUE, remap_anon MAP_FIXEDs over pages another device has registered, dangling that registration and corrupting the shared registry.
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.

2 of 4 (High): partial overlap not detected — FIXED (defensive)

Today's caller never produces a partial overlap: each range is the whole pages strictly inside one expert tensor, and tensors don't overlap, so two ranges are either the same or disjoint. Still, pin_host now returns Ok(false) for a range that partly overlaps a registered one, before any registration or remap, so those copies go through the ring.

// 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()?;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 Low · Performance · 4 of 4

PINNED_FILE lock is held across bind, register and remap/copy pin_host holds reg through bind_to_thread, cuMemHostRegister and remap_anon (which copies expert-sized ranges); every other device's pin_host and host_is_pinned blocks on the same mutex for that duration, stalling copy-path checks and serialising multi-device startup, and Drop blocks likewise.

Prompt for your AI agent
File: src/cuda/mod.rs
Line: 1360
Symbol: begin_prefill_read
Issue: PINNED_FILE lock is held across bind, register and remap/copy pin_host holds reg through bind_to_thread, cuMemHostRegister and remap_anon (which copies expert-sized ranges); every other device's pin_host and host_is_pinned blocks on the same mutex for that duration, stalling copy-path checks and serialising multi-device startup, and Drop blocks likewise.
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 (Low): lock held across register and remap — intentional

This is the trade-off for the first review's item 3: holding the lock makes check, register and remap atomic. It costs nothing today, because load_part loads the parts one after another, so no other device is pinning or copying while one registers. If loading becomes parallel, the lock could be narrowed to a per-range claim.

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;

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 · 3 of 4

Failed second registration leaves file mapping destroyed and unrecorded remap_anon MAP_FIXEDs the file pages to private anonymous RAM, then the PORTABLE cuMemHostRegister fails; the range is not added to PINNED_FILE, the file-backed zero-copy benefit and reclaimability are lost, RAM cost is paid anyway, and a retry re-copies/re-remaps the same pages.

Prompt for your AI agent
File: src/cuda/mod.rs
Line: 1374
Symbol: begin_prefill_read
Issue: Failed second registration leaves file mapping destroyed and unrecorded remap_anon MAP_FIXEDs the file pages to private anonymous RAM, then the PORTABLE cuMemHostRegister fails; the range is not added to PINNED_FILE, the file-backed zero-copy benefit and reclaimability are lost, RAM cost is paid anyway, and a retry re-copies/re-remaps the same pages.
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.

3 of 4 (Medium): failed second registration after the remap — by design

The remap only happens after the read-only registration failed with CUDA_ERROR_INVALID_VALUE. If the second registration then also fails, the pages hold the same bytes at the same addresses, so correctness is unaffected; only their size in RAM is spent, and the warning is logged. Reclaiming them wouldn't apply either: the block runs only under fits_ram(), where weights::cold doesn't drop pages. A reload would copy those pages again, which is acceptable for a failure path I haven't seen on hardware.

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<usize> { self.mark(&self.side) }
fn main_mark(&self) -> anyhow::Result<usize> { self.mark(&self.stream) }
fn main_waits(&self, side_mark: usize) -> anyhow::Result<()> { self.wait_mark(&self.stream, side_mark) }
Expand Down Expand Up @@ -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<Option<u64>> {
Expand All @@ -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<u8> = (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()));
Expand Down Expand Up @@ -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::<u8>::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<Vec<(usize, usize)>> = 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 {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟠 High · Correctness · 1 of 4

Last-Gpu drop can unregister ranges a newly created Gpu is already using Last Gpu fetch_sub==1 but before it locks PINNED_FILE, a new Gpu is created (LIVE_GPUS 0->1) and pin_host sees the old ranges still listed and returns Ok(true); the old drop then drains and cuMemHostUnregister()s them while the new Gpu DMAs from them, causing CUDA errors or pageable-memory DMA corruption.

Prompt for your AI agent
File: src/cuda/mod.rs
Line: 2922
Issue: Last-Gpu drop can unregister ranges a newly created Gpu is already using Last Gpu fetch_sub==1 but before it locks PINNED_FILE, a new Gpu is created (LIVE_GPUS 0->1) and pin_host sees the old ranges still listed and returns Ok(true); the old drop then drains and cuMemHostUnregister()s them while the new Gpu DMAs from them, causing CUDA errors or pageable-memory DMA corruption.
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.

1 of 4 (High): last-Gpu drop races a newly created Gpu — FIXED

Fixed in the latest push. Drop now decrements LIVE_GPUS while holding PINNED_FILE, which pin_host also holds. A Gpu created during the last drop either increments first, so the count never reaches zero and nothing is unregistered, or takes the lock after the drain, finds the list empty, and registers the ranges again.

if !g.is_empty() && self.ctx.bind_to_thread().is_ok() {
for (p, _) in g.drain(..) { unsafe { sys::cuMemHostUnregister(p as *mut _) }; }
}
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟠 High · Correctness · 1 of 5

PINNED_FILE entries are owned by one Gpu but used by all devices, so dropping the registrant unregisters pages other live Gpus still DMA from Gpu0 pins expert pages (portable, recorded with Gpu0 id), Gpu1's pin_host sees coverage and returns true without registering, Gpu1's htod relies on it; when Gpu0 drops it cuMemHostUnregisters the range, Gpu1 then DMAs from unpinned host memory (fault/slow/corrupt staging) with no refcount.

Prompt for your AI agent
File: src/cuda/mod.rs
Line: 2895
Issue: PINNED_FILE entries are owned by one Gpu but used by all devices, so dropping the registrant unregisters pages other live Gpus still DMA from Gpu0 pins expert pages (portable, recorded with Gpu0 id), Gpu1's pin_host sees coverage and returns true without registering, Gpu1's htod relies on it; when Gpu0 drops it cuMemHostUnregisters the range, Gpu1 then DMAs from unpinned host memory (fault/slow/corrupt staging) with no refcount.
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.

1 of 5 (High): unregister while other Gpus still use the ranges — FIXED

Fixed in the latest push. PINNED_FILE no longer records an owner. The ranges stay registered until the last Gpu (from new or share) drops, counted by LIVE_GPUS. The registration is PORTABLE, so the last context unregisters them. In practice, parts drop together on unload, but share() creates more Gpus on a context, so tying the ranges to the registrant wasn't safe in general.

}
13 changes: 8 additions & 5 deletions src/gpu_model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {

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 · 5 of 5

cold() requires cache.layer(il).is_some(), so pin_cold_only backends skip MoE layers absent from the cache entirely On CUDA (pin_cold_only=true) a MoE layer whose cache.layer() is None (not yet inserted, evicted, or a layer the cache represents differently) evaluates cold=false and is filtered out, so its experts never get pinned and staging silently falls back to the slow ring, contrary to the original loop that pinned every MoE layer.

Prompt for your AI agent
File: src/gpu_model.rs
Line: 1250
Symbol: load_part
Issue: cold() requires cache.layer(il).is_some(), so pin_cold_only backends skip MoE layers absent from the cache entirely On CUDA (pin_cold_only=true) a MoE layer whose cache.layer() is None (not yet inserted, evicted, or a layer the cache represents differently) evaluates cold=false and is filtered out, so its experts never get pinned and staging silently falls back to the slow ring, contrary to the original loop that pinned every MoE layer.
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.

5 of 5 (Medium): cold() skips layers with cache.layer(il) == None — /dismiss

/dismiss ExpertCache::new creates an entry for every MoE layer in the part's range, and this loop only visits MoE layers in that range, so layer(il) is Some for every candidate. A None would mean the layer has no expert cache on this device, so it never stages and pinning it would only cost RAM.

let Ok(w) = m.w.layer(il, name) else { continue };
match gpu.pin_host(w.data) {
Expand Down