Skip to content

cuda: STRATA_MLOCK_EXPERTS registers the staging experts on CUDA (follow-up to #206) - #242

Merged
Vasyl-Trefilov merged 3 commits into
RustingStudio:mainfrom
SubgridAI:cuda-pin-mlock
Dec 6, 2026
Merged

Vasyl-Trefilov merged 3 commits into
RustingStudio:mainfrom
SubgridAI:cuda-pin-mlock

Conversation

@SubgridAI

@SubgridAI SubgridAI commented Dec 6, 2026 •

Copy link
Copy Markdown
Contributor

What changed and why

Follow-up to #206 (merged). With STRATA_MLOCK_EXPERTS=1, #206 registers the locked expert pages with the device on HIP, so a prompt chunk's cold-expert staging is one DMA straight from the mapped file. The CUDA backend has no pin_host, so on NVIDIA the staging still copied every cold expert through the pinned ring. This adds the CUDA side, on top of b330c9c and afbd892.

  • pin_host on CUDA: cuMemHostRegister of the whole pages inside the tensor, first READ_ONLY|PORTABLE, then PORTABLE.
  • GeForce fallback: cards without CU_DEVICE_ATTRIBUTE_READ_ONLY_HOST_REGISTER_SUPPORTED refuse to register a shared read-only file mapping (CUDA_ERROR_INVALID_VALUE). For those cards the range is swapped in place for private anonymous pages holding the same bytes, using MAP_FIXED|MAP_PRIVATE|MAP_ANONYMOUS at the same addresses so every tensor slice stays valid, and then registered PORTABLE.
  • Process-wide registry: each Gpu only checked its own pinned list, so a range registered PORTABLE by one context was still treated as pageable by the others (with --arena, devices 1–3 failed with CUDA_ERROR_HOST_MEMORY_ALREADY_REGISTERED). host_is_pinned now checks a shared list on every device, and the Gpu that registered a range unregisters it at drop.
  • Caller: a new Backend::pin_cold_only() (default false, true on CUDA) makes the existing STRATA_MLOCK_EXPERTS block in gpu_model.rs register only layers that have experts outside the slots. Those are the only layers that ever stage, and on CUDA the fallback costs their size in RAM. The fits_ram() guard is kept. HIP behaviour is unchanged.

Off by default. Without STRATA_MLOCK_EXPERTS nothing changes.

Verification

Setup: 4× RTX 3060 12 GB (no P2P), Qwen4-35B-A3B UD-Q5_K_M, ctx 1M, KV q8, --device split 27,25,27,21, prefill chunk 4096. One card holds 2581/2816 experts; the other three are fully resident. Release build. Same binary and flags for each A/B; the only difference is STRATA_MLOCK_EXPERTS=1.

Without STRATA_MLOCK_EXPERTS=1
Cold-expert staging on the partial card, per 4096-token chunk 126 ms (~3.6 GB/s) 68 ms (~6.5 GB/s)
Registered at load — 2.36–4.13 GB in 4–7 layers, 3.6–6.3 s
194K-token prefill 3124 tok/s 3250 tok/s (+4.0%)
980K-token prefill 2621 tok/s 2693 tok/s (+2.7%)

The two prefill rows include the head-part embedding fix from the separate pipelined-prefill PR. Without that fix, a single-threaded embedding was pacing the pipeline and hid this change's saving.

  • Correctness: 3/3 needle retrieval at 194K and 980K with and without the variable. Decode tok/s unchanged.
  • Memory: pinning does not depend on RLIMIT_MEMLOCK (2.36 GB registered under an 8 MB shell limit). No swap was used, and MemAvailable drops by the pinned size, as expected.
  • Build: the commit is rebased onto main 37291b8 and cargo check passes. The measurements above were taken on the same diff applied to v1.5.2.

To reproduce: run a long prompt (≥100K tokens) on a CUDA multi-GPU split where at least one card can't hold all its experts, once with and once without STRATA_MLOCK_EXPERTS=1, and compare the prefill: tok/s line. STRATA_PF_PROF=1 from the pipelined-prefill PR shows the per-chunk staging time.

Notes for review

  • The anonymous remap replaces the file pages that hip: kernel fixes, MLOCK expert staging and the DFlash2 loader from #166 #206 locks with mlock for those ranges. They stay resident because they're registered, so the mlock no longer applies to them. The other expert pages keep the mlock.
  • pin_cold_only could also be true on HIP. It would cut load-time registration where the slots already hold most experts, but I left HIP alone because I can't test it.
  • No automated test was added. The path needs a multi-GPU CUDA box and a model larger than VRAM, so it was verified with the measurements above.

Checklist

  • I followed this repository's contribution guide and required checks.
  • I updated documentation or examples where needed.
  • I added regression coverage where it helps verify the change.
  • I have the right to contribute the included code and assets under this repository's contribution terms.

This work was done with Claude Code.

🤖 Generated with Claude Code

…ice (CUDA pin_host)

RustingStudio#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 RustingStudio#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 <noreply@anthropic.com>
Comment thread src/cuda/mod.rs
if !mine.is_empty() && self.ctx.bind_to_thread().is_ok() {
for p in mine { 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.

Comment thread src/cuda/mod.rs Outdated
g.retain(|r| r.2 != me);
v
};
if !mine.is_empty() && self.ctx.bind_to_thread().is_ok() {

@aletheore aletheore Bot Dec 6, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ No longer detected as of f9c47cb14d65.


🟠 High · Correctness · 2 of 5

Drop removes PINNED_FILE entries before checking bind_to_thread, leaking the registration if binding fails Gpu drops on a thread where ctx.bind_to_thread() fails (e.g. context already destroyed / wrong thread): mine is collected and retain() already removed the entries, the is_ok() guard skips cuMemHostUnregister, pages stay registered forever and a later Gpu at the same address cannot reclaim them.

Prompt for your AI agent
File: src/cuda/mod.rs
Line: 2892
Issue: Drop removes PINNED_FILE entries before checking bind_to_thread, leaking the registration if binding fails Gpu drops on a thread where ctx.bind_to_thread() fails (e.g. context already destroyed / wrong thread): mine is collected and retain() already removed the entries, the is_ok() guard skips cuMemHostUnregister, pages stay registered forever and a later Gpu at the same address cannot reclaim them.
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 5 (High): entries removed before bind_to_thread succeeds — FIXED

Fixed in the same commit. If the last Gpu's context can't be bound, the ranges stay in PINNED_FILE: they are still registered, so host_is_pinned stays accurate.

Comment thread src/cuda/mod.rs
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.

Comment thread src/cuda/mod.rs Outdated
// 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) {

@aletheore aletheore Bot Dec 6, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ No longer detected as of f9c47cb14d65.


🟡 Medium · Correctness · 4 of 5

remap_anon is attempted on any registration failure and irreversibly replaces the shared file mapping even when the subsequent registration also fails Registration fails for a transient reason (overlap, invalid flags, context error) on a card that would have supported read-only registration; remap_anon succeeds, the retry register fails, function returns Ok(false), but the read-only shared file mapping is gone, replaced by private anon pages costing RAM and breaking file-backed page-drop/cold semantics for all other users of the mapping.

Prompt for your AI agent
File: src/cuda/mod.rs
Line: 1368
Symbol: begin_prefill_read
Issue: remap_anon is attempted on any registration failure and irreversibly replaces the shared file mapping even when the subsequent registration also fails Registration fails for a transient reason (overlap, invalid flags, context error) on a card that would have supported read-only registration; remap_anon succeeds, the retry register fails, function returns Ok(false), but the read-only shared file mapping is gone, replaced by private anon pages costing RAM and breaking file-backed page-drop/cold semantics for all other users of the mapping.
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 5 (Medium): remap on any registration failure — FIXED

Fixed. The anonymous remap now runs only when the registration failed with CUDA_ERROR_INVALID_VALUE, which is the read-only file mapping a GeForce card refuses. Any other failure leaves the mapping alone and staging uses the ring. If the remap succeeds but the second registration fails, the bytes are still correct; only the RAM is spent. weights::cold page-dropping doesn't apply here, because the block runs only under fits_ram().

Comment thread src/gpu_model.rs
'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.

@aletheore

aletheore Bot commented Dec 6, 2026 •

Copy link
Copy Markdown

Aletheore Flash Lite review

Merge confidence Review effort Merge risk
2 / 5 1 / 5 Medium
Area Files Lines
src/cuda 1 +6 −1

No issues held up under independent verification (7 grounded, 0 confirmed by a second model). 7 earlier finding(s) from previous pushes still open.

# Severity Category Where
- 🟠 High Correctness mod.rs:2895 Earlier finding, still open
- 🟡 Medium Correctness mod.rs:1350 Earlier finding, still open
- 🟡 Medium Correctness gpu_model.rs:1250 Earlier finding, still open
- 🟠 High Correctness mod.rs:2922 Earlier finding, still open
- 🟠 High Correctness mod.rs:1359 Earlier finding, still open
- 🟡 Medium Correctness mod.rs:1374 Earlier finding, still open
- 🔵 Low Performance mod.rs:1360 Earlier finding, still open
Review details

Reviewed 1 file(s); skipped 0. Dismissed 0; outside PR diff 0. Grounding: 7 of 7 proposed finding(s).

The pull request description says: "It would cut load-time registration where the slots already hold most experts, but I left HIP alone because I can't test it.". This review read the diff only: it did not compile or run the code, so it cannot confirm that part works.

@aletheore

aletheore Bot commented Dec 6, 2026 •

Copy link
Copy Markdown

🔍 Aletheore evidence diff

graph LR
    n0["src/backend.rs"]
    n1["src/cuda/mod.rs"]
    n2["src/gpu_model.rs"]
    n3["cpu_worker.rs"]
    n4["src/cuda/host_share.rs"]
    n5["chat.rs"]
    n6["mat.rs"]
    n7["expert_cache.rs"]
    n8["src/gpu_model/host_share.rs"]
    n9["prefill.rs"]
    n10["src/hip/mod.rs"]
    n11["dspark.rs"]
    n12["forward.rs"]
    n13["device.rs"]
    n14["pool.rs"]
    n15["worker.rs"]
    n16["lib.rs"]
    n17["main.rs"]
    n18["model.rs"]
    n19["projector.rs"]
    n20["src/vulkan/mod.rs"]
    n21["preflight.rs"]
    n22["tests/backend.rs"]
    n23["tests/common/mod.rs"]
    n24["tests/gpu_model.rs"]
    n25["inkling2_attn_kv.rs"]
    n26["inkling2_q8_attention.rs"]
    n27["kernels.rs"]
    n28["kv_q8.rs"]
    n29["kv_turbo.rs"]
    n30["llama_numerics.rs"]
    n31["tq_probe.rs"]
    n32["vision.rs"]
    n33["vision_gpu.rs"]
    n34["vulkan_split_kv.rs"]
    n0 --> n3
    n0 --> n6
    n0 --> n7
    n0 --> n8
    n0 --> n9
    n0 --> n10
    n0 --> n11
    n0 --> n12
    n0 --> n13
    n0 --> n14
    n0 --> n15
    n0 --> n16
    n0 --> n17
    n0 --> n18
    n0 --> n19
    n0 --> n20
    n0 --> n22
    n0 --> n23
    n0 --> n24
    n0 --> n25
    n0 --> n26
    n0 --> n27
    n0 --> n28
    n0 --> n29
    n0 --> n30
    n0 --> n31
    n0 --> n33
    n0 --> n34
    n1 --> n4
    n1 --> n5
    n1 --> n10
    n1 --> n13
    n1 --> n16
    n1 --> n17
    n1 --> n20
    n1 --> n21
    n1 --> n23
    n1 --> n24
    n1 --> n25
    n1 --> n28
    n1 --> n29
    n1 --> n30
    n1 --> n34
    n2 --> n9
    n2 --> n16
    n2 --> n17
    n2 --> n18
    n2 --> n20
    n2 --> n22
    n2 --> n24
    n2 --> n32
    classDef changed fill:#d9772c,color:#fff,stroke:#b85f1c;
    classDef changedFinding fill:#c0392b,color:#fff,stroke:#922b21;
    classDef dependent fill:#f2f0ec,color:#18140f,stroke:#d6d0c5;
    class n0 changed
    class n1 changed
    class n2 changed
    class n3 dependent
    class n4 dependent
    class n5 dependent
    class n6 dependent
    class n7 dependent
    class n8 dependent
    class n9 dependent
    class n10 dependent
    class n11 dependent
    class n12 dependent
    class n13 dependent
    class n14 dependent
    class n15 dependent
    class n16 dependent
    class n17 dependent
    class n18 dependent
    class n19 dependent
    class n20 dependent
    class n21 dependent
    class n22 dependent
    class n23 dependent
    class n24 dependent
    class n25 dependent
    class n26 dependent
    class n27 dependent
    class n28 dependent
    class n29 dependent
    class n30 dependent
    class n31 dependent
    class n32 dependent
    class n33 dependent
    class n34 dependent
Loading

What changed
Deterministic, computed from this commit's real scan and import graph - posted on every run, whether or not Flash Review found anything.

  • src/backend.rs · modified · +3/-0 · +1 function · 28 other dependents
  • src/cuda/mod.rs · modified · +114/-4 · +6 functions · 15 other dependents
  • src/gpu_model.rs · modified · +8/-5 · 8 other dependents

Aggregate deltas

  • Modules: +0
  • Dependency graph edges: +0
  • Commits: 3

… 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 <noreply@anthropic.com>
Comment thread src/cuda/mod.rs
}
// 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 {

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.

Comment thread src/cuda/mod.rs
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.

Comment thread src/cuda/mod.rs
// 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.

Comment thread src/cuda/mod.rs
// 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()?;

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.

@SubgridAI

Copy link
Copy Markdown
Contributor Author

Pushed a follow-up commit after the review:

  • remap_anon calls mmap, so it's now Linux-only, like weights::mlock (false elsewhere). Without that, the Windows CI job would fail to link, since mmap isn't in the MSVC CRT.
  • Review items 1–4 are fixed. Item 5 is answered inline.
  • New test cuda::tests::remap_anon_keeps_bytes_and_addresses (no GPU needed): the remapped pages keep their addresses and bytes, become writable, and the file is left untouched.
    cargo check and the new test pass on Linux. The drop and refcount paths need a multi-GPU run, which I'll do in the next maintenance window and post here.

…verlapping 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 <noreply@anthropic.com>
@Vasyl-Trefilov

Copy link
Copy Markdown
Member

Hi, ty for this and for the numbers on the 4 card setup.

I tested it here on one 3060 with Qwen4. The default path (without STRATA_MLOCK_EXPERTS) gives the same output as main and the GPU tests pass. I cannot run the pinned path here, the model does not fit in RAM on this box so the block is skipped.

I added one small commit on top before merging:

  1. The mmap extern and the remap are now Linux only. On Windows the plain extern "C" mmap would not link, so the CUDA build there would break.
  2. The remap fallback runs only when register says CUDA_ERROR_INVALID_VALUE and the model fits in RAM. pin_host on CUDA is also reached from STRATA_DS_PIN (GigaChat 4) and STRATA_INK_PIN (Inkling 2), which have no fits_ram check. On a model bigger than RAM the remap would copy all experts into RAM, and weights::cold later drops those anonymous pages, so they would read back as zeros.

It is merged like this now, tell me if something looks wrong to you.

@Vasyl-Trefilov
Vasyl-Trefilov merged commit 5ca00b2 into RustingStudio:main Dec 6, 2026
3 checks passed
@Vasyl-Trefilov

Copy link
Copy Markdown
Member

I saw your two new commits after my reply and merged them too, the registry lock and the last Gpu unregistering are nicer than what I had. I only kept the fits_ram check on the remap, because DS_PIN and INK_PIN reach pin_host on models bigger than RAM, and there weights::cold would drop the anonymous pages.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants