From ea65cb2763f70d96635efb2f20f13581ffb4b031 Mon Sep 17 00:00:00 2001 From: kbenkhaled Date: Tue, 1 Dec 2026 20:52:06 +0000 Subject: [PATCH 1/2] helios,heliopause,ignition: fall back to host-backed CUDA VMM when registered host memory lacks identity addressing Why: Tegra Linux GPUs such as Jetson Orin (GA10B / SM87) report CU_DEVICE_ATTRIBUTE_CAN_USE_HOST_POINTER_FOR_REGISTERED_MEM (91) == 0 alongside CU_DEVICE_ATTRIBUTE_HOST_REGISTER_SUPPORTED (99) == 1 and CU_DEVICE_ATTRIBUTE_HOST_NUMA_VMM (141) == 1. Because Flare's Linux MappedHost path requires registered host pages to share the exact CPU and GPU virtual address, fixed-address MappedHost buffers (such as offloaded embedding mailboxes) fail on these devices even though the driver supports host-backed CUDA VMM. In addition, the default SM87 device window (0x12_0000_0000 + 48 GiB = 120 GiB) exceeds the measured 96.56 GiB (0x18_23c0_0000) CUDA VMM ceiling on 8 GiB Jetson Orin Nano, and the default 12 TiB HOST_BASE also exceeds Orin's VMM aperture. What: - Before: host-backed CUDA VMM (allocate_host / host_mappings in Helios, WindowsHostRegion in CoreStorage) was gated strictly behind #[cfg(windows)] / os.name == "nt"; Heliopause always used the 12 TiB / 32 TiB host range on Linux; and SM87 placed its 48 GiB device window at 0x12_0000_0000 (72..120 GiB). - After: - helios/src/runtime_core/{driver.rs,host.rs,mod.rs}: define named CUDA device attribute constants (18, 91, 99, 116, 134, 141); add shared host::use_host_vmm(windows, host_register_supported, can_use_host_pointer) and host::host_numa_properties(driver, device) (validating HOST_NUMA_VMM and power-of-two host-NUMA granularity); ungate allocate_host and host_mappings on Unix; query both attributes 99 and 91 in NativeResources::initialize and check cuMemRelease status during VMM mapping. - heliopause/src/allocator.rs: query attributes 99 and 91 via host::use_host_vmm, store host_vmm on Arena, and expose it in flare_core_snapshot() so Ignition consumes one source of truth. When !cfg!(windows) && host_vmm and host_numa_properties returns Some, align fallback host windows to max(granule, 1 GiB) (matching exported GiB-rounded device reservations), probe the full host span (propagating cuMemAddressFree errors), and fall back to an 8 GiB per-rank host VMM window immediately before (at or above the low restore floor) or after the device windows. - ignition/preparation/core_storage.py: lower the default SM87 DEVICE_BASE from 0x12_0000_0000 to 0x0c_0000_0000 (48..96 GiB), read _host_vmm from layout["host_vmm"], rename WindowsHostRegion to HostVmmRegion, and check HOST_NUMA_VMM (141) before allocation to match Helios. - docs/runtime-core-design.md: document host-backed CUDA VMM fallback, narrow-aperture host ranges across Linux and WDDM, and SM87 defaults. - Tests: add host_vmm_dispatch_requires_both_host_register_and_host_pointer in host.rs, vmm_host_window_respects_aperture_floor_and_rank_count in allocator.rs, and HostVmmRegion dispatch, overflow non-mutation, and HOST_NUMA_VMM rejection in tests/preparation/test_core_storage.py. Result: Linux devices lacking identity-addressed host registration automatically export and natively replay fixed-address MappedHost cores using host-backed CUDA VMM and a reservable host address range (verified end-to-end on Jetson Orin Nano 8 GiB SM87), while Linux GPUs supporting both attributes 99 and 91 preserve the existing mmap + cuMemHostRegister path (verified end-to-end on Jetson AGX Thor SM110). Evidence: - Live end-to-end MappedHost export + native Helios replay + two-phase teardown (helios/tests/fixed_core_fixture.py -> runtime_core::event_tests::named_external_wait_survives_export_and_native_replay): - Jetson Orin Nano 8 GiB (SM87, JetPack 6 / CUDA 12.6; attributes 18=1, 91=0, 99=1, 134=0, 141=1; max 2 MiB VMM end = 0x18_23c0_0000 = 96.56 GiB): CoreStorage selected host_vmm=True, DEVICE_BASE=0xc00000000 (48 GiB, extent 48 GiB), HOST_BASE=0xa00000000 (40 GiB, extent 8 GiB); exported 6-allocation core including MappedHost table and passed native replay + byte-exact output check + clean teardown in 1.04s. - Jetson AGX Thor (SM110; attributes 18=1, 91=1, 99=1, 134=0, 141=1): CoreStorage kept host_vmm=False, DEVICE_BASE=0x80000000000, HOST_BASE=0xc0000000000 (HostRegion); exported and passed native replay + teardown in 0.37s. - Full release-mode Rust & Python CPU suites (ARM64 container on Thor, non-root runner, ext4 TMPDIR): - helios (--locked --release --features runtime-core,server): --lib 1775 passed, 6 failed (all 6 in tests/support/templates.rs:19 due to 401 Unauthorized on gated meta-models/Muse-Spark-Open-816B-A42B-NVFP4); --test '*': 62 passed, 0 failed. - heliopause (--locked --release): 228 passed, 1 failed (unrelated export::blob::tests::verification_retries_hardlink_metadata_changes_and_bounds_churn coarse ctime on ARM64 ext4; all 19 allocator and 34 export::core tests passed). - flare (--locked --release): 253 passed, 0 failed (245 + 7 + 1). - flare-cli (--locked --release): 241 passed, 0 failed (215 + 9 + 6 + 4 + 7). - pytest -q tests/preparation/test_core_storage.py tests/preparation/test_core_boundary.py tests/preparation/test_low_window.py: 18 passed, 1 skipped, 0 failed. - Limitations: Windows WDDM builds/serving, GB10 (SM121), AGX Orin 64 GiB, discrete Linux GPUs, and RoCE over host-VMM buffers were not run locally. Design-Signed-Off-By: Gemini 4 Neon (Cursor); design-review=2e5b Signed-off-by: kbenkhaled --- docs/runtime-core-design.md | 17 +- heliopause/src/allocator.rs | 214 ++++++++++++++++++++++++- helios/src/runtime_core/driver.rs | 7 + helios/src/runtime_core/host.rs | 126 ++++++++++----- helios/src/runtime_core/mod.rs | 45 ++++-- ignition/preparation/core_storage.py | 20 ++- tests/preparation/test_core_storage.py | 59 +++++++ 7 files changed, 417 insertions(+), 71 deletions(-) diff --git a/docs/runtime-core-design.md b/docs/runtime-core-design.md index 97145ddb2..89764b22f 100644 --- a/docs/runtime-core-design.md +++ b/docs/runtime-core-design.md @@ -89,8 +89,8 @@ owners. Final assembly consumes rank indexes and open source file ranges independently of the prepared model. **Storage.** PyTorch's persistent device allocations come from one address range -reserved before model loading: 1 TiB per rank from `0x0800_0000_0000` on Linux or -`0x0400_0000_0000` on Windows, backed on +reserved before model loading: 1 TiB per rank from `0x0800_0000_0000` on Linux +(48 GiB from `0x0c_0000_0000` on integrated SM87) or `0x0400_0000_0000` on Windows, backed on demand with `cuMemCreate` and `cuMemMap` at allocation granularity. Cores reserve GiB-aligned ranges covering stored allocations and the declared maximum extents of dynamic caches; unused gaps in the preparation arena are omitted. PyTorch @@ -101,8 +101,13 @@ separate PyTorch pools backed by that arena. Mapped host buffers, including n-gram request mailboxes, use fixed addresses from `0x0c00_0000_0000` when the device rank ranges fit below it. Larger Linux layouts start host storage at `0x2000_0000_0000` to avoid overlap. Each rank has a disjoint 1 TiB host -range; the native allocator reports the selected base to Ignition. -Linux maps and registers host pages; Windows uses host-backed CUDA VMM. +range (or a smaller range — 8 GiB on narrow Linux CUDA VMM apertures, or up to +1 TiB within `1 << bits` on narrow Windows WDDM adapters — adjacent to the +device windows); the native allocator reports the selected host range and +backing mode to Ignition. Linux maps and registers host pages when the device +supports identity-addressed host registration (`HOST_REGISTER_SUPPORTED` and +`CAN_USE_HOST_POINTER_FOR_REGISTERED_MEM`); Windows and Linux devices lacking +either capability use host-backed CUDA VMM (`HOST_NUMA`). Both expose the recorded address to the CPU and GPU. A CUPTI subscriber logs driver allocations and removes records when their context is destroyed. Persistent device allocations outside the arena are grouped into complete @@ -111,9 +116,9 @@ granularity. Reservations without retained allocations are omitted. Only their live byte spans are considered for payload storage; page gaps are zero. Before copying, the exporter checks that each external allocation belongs to the serving context. On Linux integrated GPUs, preparation reserves the low address -window through 256 GiB without physical backing. Windows retains the driver's +window through 256 GiB (12 GiB on integrated SM87) without physical backing. Windows retains the driver's low allocation pool. Export on either integrated platform rejects reachable -external device storage below 256 GiB, where context mappings can prevent replay. +external device storage below that floor, where context mappings can prevent replay. The model exporter retains allocations reachable from graph arguments, copy and memset endpoints, module globals, native execution buffers, and declared diff --git a/heliopause/src/allocator.rs b/heliopause/src/allocator.rs index fefe43f2b..1a71d7d5d 100644 --- a/heliopause/src/allocator.rs +++ b/heliopause/src/allocator.rs @@ -14,7 +14,8 @@ use std::{ }; use crate::runtime_core::address_space; -use crate::runtime_core::driver::{Access, AllocationProperties, Driver, Location}; +use crate::runtime_core::driver::{self, Access, AllocationProperties, Driver, Location}; +use crate::runtime_core::host; use crate::{Error, ExecutionError, Result}; fn invalid(message: impl Into) -> Error { @@ -191,6 +192,7 @@ struct Arena { device: i32, granularity: usize, gpudirect: bool, + host_vmm: bool, host_base: u64, host_extent: u64, free: Vec<(u64, usize)>, @@ -356,6 +358,65 @@ fn window_host_layout( )) } +/// Selects a CUDA-VMM-reservable `(host_base, host_extent)` on non-WDDM platforms +/// where mapped host storage uses CUDA VMM (`HOST_REGISTER_SUPPORTED == 0` or +/// `CAN_USE_HOST_POINTER_FOR_REGISTERED_MEM == 0`). Keeps the default host range when +/// its full span is reservable; otherwise places an 8 GiB per-rank host range +/// immediately before (at or above `min_host_base`) or after the device windows. +#[allow(clippy::too_many_arguments)] +fn vmm_host_window( + base: u64, + extent: u64, + world: u32, + granule: u64, + min_host_base: u64, + default_base: u64, + default_extent: u64, + mut can_reserve: impl FnMut(u64, u64) -> Result, +) -> Result<(u64, u64)> { + if !granule.is_power_of_two() { + return Err(invalid(format!( + "invalid host allocation granularity {granule:#x}" + ))); + } + if let Some(default_total) = u64::from(world).checked_mul(default_extent) + && default_base.checked_add(default_total).is_some() + && default_base % granule == 0 + && default_extent % granule == 0 + && can_reserve(default_base, default_total)? + { + return Ok((default_base, default_extent)); + } + // Align fallback host windows to at least 1 GiB so exported GiB-rounded device + // reservations can never overlap a mailbox placed adjacent to a custom device window. + let window_align = granule.max(1u64 << 30); + let per_rank = (8u64 << 30).min(default_extent) & !(window_align - 1); + let total = u64::from(world).checked_mul(per_rank).filter(|&n| n > 0); + if let (Some(total), Some(device_span)) = (total, u64::from(world).checked_mul(extent)) { + // Prefer placing immediately before the device window (at or above the low restore + // floor) so cores exported on larger-aperture boards (e.g., 64 GiB AGX Orin) keep + // their host range below smaller sibling ceilings (e.g., 8 GiB Orin Nano). + if let Some(before) = base.checked_sub(total).map(|n| n & !(window_align - 1)) + && before >= min_host_base + && can_reserve(before, total)? + { + return Ok((before, per_rank)); + } + if let Some(after) = base + .checked_add(device_span) + .and_then(|end| end.checked_add(window_align - 1)) + .map(|n| n & !(window_align - 1)) + && after.checked_add(total).is_some() + && can_reserve(after, total)? + { + return Ok((after, per_rank)); + } + } + Err(invalid( + "no reservable CUDA VMM address range for mapped host storage", + )) +} + #[unsafe(no_mangle)] extern "C" fn flare_core_initialize(rank: u32, world: u32, device: i32) -> i32 { flare_core_initialize_window(rank, world, device, BASE, EXTENT as u64) @@ -384,15 +445,46 @@ extern "C" fn flare_core_initialize_window( } let extent_bytes = extent as usize; let driver = Driver::load()?; - let (mut address, mut granularity, mut gpudirect, mut integrated) = (0, 0, 0, 0); - let (host_base, host_extent) = unsafe { + let ( + mut address, + mut granularity, + mut gpudirect, + mut integrated, + mut host_register, + mut can_use_host_pointer, + ) = (0, 0, 0, 0, 1, 1); + let (host_vmm, host_base, host_extent) = unsafe { driver.check( "cuDeviceGetAttribute(INTEGRATED)", - (driver.device_attribute)(&mut integrated, 18, device), + (driver.device_attribute)( + &mut integrated, + driver::CU_DEVICE_ATTRIBUTE_INTEGRATED, + device, + ), + )?; + driver.check( + "cuDeviceGetAttribute(HOST_REGISTER_SUPPORTED)", + (driver.device_attribute)( + &mut host_register, + driver::CU_DEVICE_ATTRIBUTE_HOST_REGISTER_SUPPORTED, + device, + ), + )?; + driver.check( + "cuDeviceGetAttribute(CAN_USE_HOST_POINTER_FOR_REGISTERED_MEM)", + (driver.device_attribute)( + &mut can_use_host_pointer, + driver::CU_DEVICE_ATTRIBUTE_CAN_USE_HOST_POINTER_FOR_REGISTERED_MEM, + device, + ), )?; driver.check( "cuDeviceGetAttribute(GPU_DIRECT_RDMA_SUPPORTED)", - (driver.device_attribute)(&mut gpudirect, 116, device), + (driver.device_attribute)( + &mut gpudirect, + driver::CU_DEVICE_ATTRIBUTE_GPU_DIRECT_RDMA_SUPPORTED, + device, + ), )?; let gpudirect_rdma = gpudirect != 0 && integrated == 0; driver.check( @@ -402,7 +494,7 @@ extern "C" fn flare_core_initialize_window( let granule = granularity as u64; let two_granules = granule .checked_mul(2) - .filter(|_| granule != 0) + .filter(|_| granule.is_power_of_two()) .ok_or_else(|| { invalid(format!( "invalid CUDA allocation granularity {granule:#x}" @@ -414,8 +506,59 @@ extern "C" fn flare_core_initialize_window( ))); } let bits = address_space::virtual_address_bits(device); - let (host_base, host_extent) = + let (default_host_base, default_host_extent) = window_host_layout(base, extent, world, granule, bits)?; + let host_vmm = host::use_host_vmm( + cfg!(windows), + host_register != 0, + can_use_host_pointer != 0, + ); + // Never run speculative cuMemAddressReserve probes on Windows WDDM, where + // out-of-range fixed addresses can hang even when D3DKMT width lookup fails. + let (host_base, host_extent) = if !cfg!(windows) && host_vmm { + if let Some((_, host_granularity)) = host::host_numa_properties(&driver, device)? { + let host_granule = granule.max(host_granularity as u64); + let host_align = usize::try_from(host_granule).map_err(|_| { + invalid(format!( + "invalid host CUDA allocation granularity {host_granule:#x}" + )) + })?; + let min_host_base = if integrated != 0 && base < 0x40_0000_0000 { + 0x3_0000_0000 + } else { + 0x40_0000_0000 + }; + vmm_host_window( + base, + extent, + world, + host_granule, + min_host_base, + default_host_base, + default_host_extent, + |addr, bytes| { + let Ok(len) = usize::try_from(bytes) else { + return Ok(false); + }; + let mut probe = 0; + let status = (driver.reserve)(&mut probe, len, host_align, addr, 0); + if status == 0 { + driver.check( + "cuMemAddressFree(host probe)", + (driver.release_address)(probe, len), + )?; + Ok(probe == addr) + } else { + Ok(false) + } + }, + )? + } else { + (default_host_base, default_host_extent) + } + } else { + (default_host_base, default_host_extent) + }; let mut reserved = Vec::new(); for peer in 0..world { let start = base + u64::from(peer) * extent; @@ -434,13 +577,14 @@ extern "C" fn flare_core_initialize_window( } reserved.push(address); } - (host_base, host_extent) + (host_vmm, host_base, host_extent) }; *arena = Some(Arena { driver, device, granularity, gpudirect: gpudirect != 0 && integrated == 0, + host_vmm, host_base: host_base + u64::from(rank) * host_extent, host_extent, free: vec![(base + u64::from(rank) * extent, extent_bytes / 2)], @@ -716,6 +860,7 @@ extern "C" fn flare_core_snapshot() -> *mut c_char { }; let value = serde_json::json!({ "granularity": a.granularity, "mappings": a.mappings, + "host_vmm": a.host_vmm, "host_base": a.host_base, "host_extent": a.host_extent, "retained_reference_bytes": a.retained.reference_bytes, "retained_handles": a.retained.handles.len(), @@ -1216,6 +1361,7 @@ mod tests { device: 0, granularity: 4096, gpudirect: false, + host_vmm: false, host_base: 0, host_extent: 0, free: Vec::new(), @@ -1295,6 +1441,7 @@ mod tests { device: 0, granularity: 4096, gpudirect: false, + host_vmm: false, host_base: 0, host_extent: 0, free: Vec::new(), @@ -1339,6 +1486,7 @@ mod tests { device: 0, granularity: 4096, gpudirect: false, + host_vmm: false, host_base: 0, host_extent: 0, free: Vec::new(), @@ -1438,6 +1586,56 @@ mod tests { assert!(window_host_layout(0x80_0000_0000, 512 << 30, 1, 2 << 20, Some(40)).is_err()); } + #[test] + fn vmm_host_window_respects_aperture_floor_and_rank_count() { + let granule = 2 << 20; + let orin_floor = 0x3_0000_0000u64; + let orin_nano_cap = 0x18_23c0_0000u64; + let agx_orin_cap = 0x20_0000_0000u64; + let below = |cap: u64| move |addr: u64, len: u64| Ok(addr.checked_add(len).is_some_and(|e| e <= cap)); + + // Both 8 GiB Orin Nano and 64 GiB AGX Orin place host VMM at 40..48 GiB so cores + // exported on AGX remain loadable on Nano. + for cap in [orin_nano_cap, agx_orin_cap] { + assert_eq!( + vmm_host_window(0x0c_0000_0000, 48 << 30, 1, granule, orin_floor, HOST_BASE, EXTENT as u64, below(cap)) + .unwrap(), + (0x0a_0000_0000, 8 << 30) + ); + } + + // When the device window sits at the external restore floor, pre-device placement + // would collide with seal_low_window(), so host VMM falls back to post-device + // rounded up to 1 GiB so exported GiB-aligned device reservations never overlap. + assert_eq!( + vmm_host_window(orin_floor, (48 << 30) + (4 << 20), 1, granule, orin_floor, HOST_BASE, EXTENT as u64, below(orin_nano_cap)) + .unwrap(), + (orin_floor + (49 << 30), 8 << 30) + ); + + // Multi-rank (world = 2): host span covers both ranks (2 * 8 GiB) and rejects a + // default window where only rank 0 would fit. + let partial_default_cap = HOST_BASE + EXTENT as u64; + assert_eq!( + vmm_host_window(0x0c_0000_0000, 32 << 30, 2, granule, orin_floor, HOST_BASE, EXTENT as u64, below(partial_default_cap)) + .unwrap(), + (0x08_0000_0000, 8 << 30) + ); + + // Full 48-bit aperture keeps the default host base unchanged. + assert_eq!( + vmm_host_window(0x0c_0000_0000, 48 << 30, 2, granule, orin_floor, HOST_BASE, EXTENT as u64, |_, _| Ok(true)) + .unwrap(), + (HOST_BASE, EXTENT as u64) + ); + + // Reject invalid granularity, unreservable apertures, and probe cleanup failures. + assert!(vmm_host_window(0x0c_0000_0000, 48 << 30, 1, 0, orin_floor, HOST_BASE, EXTENT as u64, |_, _| Ok(true)).is_err()); + assert!(vmm_host_window(0x0c_0000_0000, 48 << 30, 1, 3 << 20, orin_floor, HOST_BASE, EXTENT as u64, |_, _| Ok(true)).is_err()); + assert!(vmm_host_window(0x0c_0000_0000, 48 << 30, 1, granule, orin_floor, HOST_BASE, EXTENT as u64, |_, _| Ok(false)).is_err()); + assert!(vmm_host_window(0x0c_0000_0000, 48 << 30, 1, granule, orin_floor, HOST_BASE, EXTENT as u64, |_, _| Err(invalid("release failed"))).is_err()); + } + #[test] fn zero_byte_allocate_and_null_free_do_not_poison_error() { let _guard = ARENA_TEST_LOCK diff --git a/helios/src/runtime_core/driver.rs b/helios/src/runtime_core/driver.rs index edaea753c..7e27f202b 100644 --- a/helios/src/runtime_core/driver.rs +++ b/helios/src/runtime_core/driver.rs @@ -11,6 +11,13 @@ use crate::{CudaError, ExecutionError, Result}; pub type Handle = *mut c_void; +pub const CU_DEVICE_ATTRIBUTE_INTEGRATED: c_int = 18; +pub const CU_DEVICE_ATTRIBUTE_CAN_USE_HOST_POINTER_FOR_REGISTERED_MEM: c_int = 91; +pub const CU_DEVICE_ATTRIBUTE_HOST_REGISTER_SUPPORTED: c_int = 99; +pub const CU_DEVICE_ATTRIBUTE_GPU_DIRECT_RDMA_SUPPORTED: c_int = 116; +pub const CU_DEVICE_ATTRIBUTE_HOST_NUMA_ID: c_int = 134; +pub const CU_DEVICE_ATTRIBUTE_HOST_NUMA_VMM: c_int = 141; + #[repr(C)] pub struct KernelParams { pub function: Handle, diff --git a/helios/src/runtime_core/host.rs b/helios/src/runtime_core/host.rs index 8501a0f13..e2121e459 100644 --- a/helios/src/runtime_core/host.rs +++ b/helios/src/runtime_core/host.rs @@ -3,10 +3,20 @@ * SPDX-License-Identifier: Apache-2.0 */ -//! Host-backed CUDA VMM preserves recorded mailbox addresses on Windows. +//! Host-backed CUDA VMM preserves recorded mailbox addresses when the device cannot +//! map registered host memory at the CPU virtual address (Windows WDDM, or Linux +//! devices with `HOST_REGISTER_SUPPORTED == 0` or `CAN_USE_HOST_POINTER_FOR_REGISTERED_MEM == 0`). use super::{Result, invalid}; +pub fn use_host_vmm( + windows: bool, + host_register_supported: bool, + can_use_host_pointer: bool, +) -> bool { + windows || !host_register_supported || !can_use_host_pointer +} + fn ranges( allocations: impl Iterator, granularity: usize, @@ -39,11 +49,58 @@ fn ranges( .collect()) } -#[cfg(windows)] +/// Query host-NUMA VMM allocation properties and granularity for `device`. +/// Returns `Ok(None)` when the driver reports `HOST_NUMA_VMM == 0`. +/// +/// # Safety +/// `driver` must be initialized and `device` must be a valid CUDA device ordinal. +pub unsafe fn host_numa_properties( + driver: &super::driver::Driver, + device: i32, +) -> Result> { + use super::driver; + unsafe { + let mut supported = 0; + driver.check( + "cuDeviceGetAttribute(HOST_NUMA_VMM)", + (driver.device_attribute)(&mut supported, driver::CU_DEVICE_ATTRIBUTE_HOST_NUMA_VMM, device), + )?; + if supported == 0 { + return Ok(None); + } + let mut numa = 0; + driver.check( + "cuDeviceGetAttribute(HOST_NUMA_ID)", + (driver.device_attribute)(&mut numa, driver::CU_DEVICE_ATTRIBUTE_HOST_NUMA_ID, device), + )?; + let properties = super::AllocationProperties { + kind: 1, + handles: 0, + location: super::Location { + kind: 3, + device: numa.max(0), + }, + windows: std::ptr::null_mut(), + flags: [0; 8], + }; + let mut granularity = 0; + driver.check( + "cuMemGetAllocationGranularity(host)", + (driver.granularity)(&mut granularity, &properties, 0), + )?; + if !granularity.is_power_of_two() { + return Err(invalid(format!( + "invalid host allocation granularity {granularity:#x}" + ))); + } + Ok(Some((properties, granularity))) + } +} + impl super::NativeResources { pub(super) unsafe fn allocate_host(&mut self, core: &super::Core) -> Result<()> { use super::driver::Access; - use super::{AllocationProperties, Location, Memory}; + use super::{Location, Memory}; if !core .allocations @@ -55,36 +112,8 @@ impl super::NativeResources { let driver = &self.driver; unsafe { driver.check("cuCtxSetCurrent", (driver.context_set)(self.context))?; - let mut supported = 0; - driver.check( - "cuDeviceGetAttribute(HOST_NUMA_VMM)", - (driver.device_attribute)(&mut supported, 141, self.device), - )?; - if supported == 0 { - return Err(invalid( - "mapped core storage requires host-backed CUDA VMM on Windows", - )); - } - let mut numa = 0; - driver.check( - "cuDeviceGetAttribute(HOST_NUMA_ID)", - (driver.device_attribute)(&mut numa, 134, self.device), - )?; - let properties = AllocationProperties { - kind: 1, - handles: 0, - location: Location { - kind: 3, - device: numa.max(0), - }, - windows: std::ptr::null_mut(), - flags: [0; 8], - }; - let mut granularity = 0; - driver.check( - "cuMemGetAllocationGranularity(host)", - (driver.granularity)(&mut granularity, &properties, 0), - )?; + let (properties, granularity) = host_numa_properties(driver, self.device)? + .ok_or_else(|| invalid("mapped core storage requires host-backed CUDA VMM"))?; let ranges = ranges( core .allocations @@ -96,8 +125,8 @@ impl super::NativeResources { let access = [ Access { location: Location { - kind: 3, - device: numa.max(0), + kind: properties.location.kind, + device: properties.location.device, }, flags: 3, }, @@ -129,10 +158,11 @@ impl super::NativeResources { "cuMemCreate(host)", (driver.physical_create)(&mut physical, bytes, &properties, 0), )?; - let status = (driver.map)(address, bytes, 0, physical, 0); - (driver.physical_release)(physical); - driver.check("cuMemMap(host)", status)?; + let map_status = (driver.map)(address, bytes, 0, physical, 0); + let release_status = (driver.physical_release)(physical); + driver.check("cuMemMap(host)", map_status)?; self.host_mappings.push((address, bytes)); + driver.check("cuMemRelease(host)", release_status)?; driver.check( "cuMemSetAccess(host)", (driver.access)(address, bytes, access.as_ptr(), access.len()), @@ -168,4 +198,24 @@ mod tests { assert!(ranges([(u64::MAX - 4095, 4096)].into_iter(), 2 << 20).is_err()); assert!(ranges([(4096, 4096)].into_iter(), 0).is_err()); } + + #[test] + fn host_vmm_dispatch_requires_both_host_register_and_host_pointer() { + use super::super::driver; + assert_eq!(driver::CU_DEVICE_ATTRIBUTE_CAN_USE_HOST_POINTER_FOR_REGISTERED_MEM, 91); + assert_eq!(driver::CU_DEVICE_ATTRIBUTE_HOST_REGISTER_SUPPORTED, 99); + assert_eq!(driver::CU_DEVICE_ATTRIBUTE_HOST_NUMA_ID, 134); + assert_eq!(driver::CU_DEVICE_ATTRIBUTE_HOST_NUMA_VMM, 141); + for windows in [false, true] { + for host_reg in [false, true] { + for host_ptr in [false, true] { + assert_eq!( + use_host_vmm(windows, host_reg, host_ptr), + windows || !host_reg || !host_ptr, + "windows={windows} host_reg={host_reg} host_ptr={host_ptr}" + ); + } + } + } + } } diff --git a/helios/src/runtime_core/mod.rs b/helios/src/runtime_core/mod.rs index 87dbc4b09..fff0d2b24 100644 --- a/helios/src/runtime_core/mod.rs +++ b/helios/src/runtime_core/mod.rs @@ -19,8 +19,7 @@ mod engram; #[cfg(test)] mod event_tests; mod format; -#[cfg(any(windows, test))] -mod host; +pub mod host; mod limits; mod metadata; #[cfg(test)] @@ -121,9 +120,10 @@ pub struct NativeResources { execution: Option, // An integrated GPU (GB10) registers host memory without pinning it. integrated: bool, + // Windows WDDM and devices lacking identity-addressed host registration back MappedHost via CUDA VMM. + host_vmm: bool, events: HashMap, cache: Option, - #[cfg(windows)] host_mappings: Vec<(u64, usize)>, green_partition: Option, persistent_worker: Option>, @@ -358,9 +358,32 @@ impl NativeResources { } let mut integrated = 0; driver.check( - "cuDeviceGetAttribute", - (driver.device_attribute)(&mut integrated, 18, device), + "cuDeviceGetAttribute(INTEGRATED)", + (driver.device_attribute)(&mut integrated, driver::CU_DEVICE_ATTRIBUTE_INTEGRATED, device), )?; + let mut host_register_supported = 1; + driver.check( + "cuDeviceGetAttribute(HOST_REGISTER_SUPPORTED)", + (driver.device_attribute)( + &mut host_register_supported, + driver::CU_DEVICE_ATTRIBUTE_HOST_REGISTER_SUPPORTED, + device, + ), + )?; + let mut can_use_host_pointer = 1; + driver.check( + "cuDeviceGetAttribute(CAN_USE_HOST_POINTER_FOR_REGISTERED_MEM)", + (driver.device_attribute)( + &mut can_use_host_pointer, + driver::CU_DEVICE_ATTRIBUTE_CAN_USE_HOST_POINTER_FOR_REGISTERED_MEM, + device, + ), + )?; + let host_vmm = host::use_host_vmm( + cfg!(windows), + host_register_supported != 0, + can_use_host_pointer != 0, + ); if let Some(execution) = core.execution.as_ref() && execution.persistent_workers.len() > 1 { @@ -419,9 +442,9 @@ impl NativeResources { reservations: vec![], execution: core.execution.clone(), integrated: integrated != 0, + host_vmm, events: HashMap::new(), cache: None, - #[cfg(windows)] host_mappings: Vec::new(), green_partition: None, persistent_worker: None, @@ -538,8 +561,7 @@ impl NativeResources { } unsafe fn allocate(&mut self, core: &Core, phase: &Phase) -> Result<()> { - #[cfg(windows)] - if self.host_mappings.is_empty() { + if self.host_vmm && self.host_mappings.is_empty() { unsafe { self.allocate_host(core)? }; } let driver = self.driver.clone(); @@ -620,7 +642,7 @@ impl NativeResources { } Memory::MappedHost => { #[cfg(unix)] - { + if !self.host_vmm { let mapped = libc::mmap( address as Handle, allocation.nbytes, @@ -686,7 +708,7 @@ impl NativeResources { } Memory::MappedHost => { #[cfg(unix)] - { + if !self.host_vmm { let mut gpu = 0; driver.check( "cuMemHostGetDevicePointer_v2", @@ -1585,7 +1607,7 @@ impl NativeResources { } (Memory::MappedHost, _) => { #[cfg(unix)] - { + if !self.host_vmm { (self.driver.host_unregister)(allocation.address as Handle); libc::munmap(allocation.address as Handle, allocation.nbytes); } @@ -1593,7 +1615,6 @@ impl NativeResources { (Memory::Peer, _) => {} } } - #[cfg(windows)] for (address, bytes) in self.host_mappings.drain(..).rev() { (self.driver.unmap)(address, bytes); } diff --git a/ignition/preparation/core_storage.py b/ignition/preparation/core_storage.py index 02bcb0b05..b19809912 100644 --- a/ignition/preparation/core_storage.py +++ b/ignition/preparation/core_storage.py @@ -64,9 +64,10 @@ def __init__(self, *, rank=0, world=1, device=0, local_ranks=None, device_window properties = torch.cuda.get_device_properties(device) self.integrated = properties.is_integrated if device_window is None and self.integrated and (properties.major, properties.minor) == (8, 7): - # Jetson Orin (GA10B) exposes a 128 GiB CUDA VMM address window (below 0x20_0000_0000). + # Jetson Orin (GA10B) exposes ~96.5 GiB VMM on 8 GiB Nano and 128 GiB on 64 GiB AGX; + # [48 GiB, 96 GiB) fits both while leaving room for host VMM reservations. self.EXTERNAL_FLOOR = 0x300000000 - self.DEVICE_BASE = 0x1200000000 + self.DEVICE_BASE = 0x0c00000000 self.RESERVATION_BYTES = 48 << 30 self._persistent_total_bytes = min(properties.total_memory, self.RESERVATION_BYTES // 4) self._retention_scope = False @@ -99,6 +100,7 @@ def __init__(self, *, rank=0, world=1, device=0, local_ranks=None, device_window gpudirect = C.c_int() self.cuda.call("cuDeviceGetAttribute", C.byref(gpudirect), C.c_int(116), C.c_int(device)) self.gpudirect = bool(gpudirect.value) and not self.integrated + self._host_vmm = bool(layout["host_vmm"]) self.HOST_BASE = layout["host_base"] self.HOST_RESERVATION_BYTES = layout.get("host_extent", self.HOST_RESERVATION_BYTES) self._host_cursor = self.HOST_BASE @@ -351,7 +353,7 @@ def host_allocate(self, name, shape, dtype): size = math.prod(shape) * dtype.itemsize # Host mappings are whole host pages; Grace kernels may use 64 KiB pages. extent = -(-size // mmap.PAGESIZE) * mmap.PAGESIZE - region_type = WindowsHostRegion if os.name == "nt" else HostRegion + region_type = HostVmmRegion if self._host_vmm else HostRegion if self._host_cursor + extent > self.HOST_BASE + self.HOST_RESERVATION_BYTES: raise MemoryError("native core host-address range exhausted") region = region_type(self.cuda, self._host_cursor, extent, shape, dtype, self.device, @@ -487,16 +489,20 @@ class _Access(C.Structure): _fields_ = [("location", _Location), ("flags", C.c_int)] -class WindowsHostRegion: +class HostVmmRegion: """Host-backed CUDA VMM storage at one recorded CPU/GPU virtual address.""" def __init__(self, cuda, address, extent, shape, dtype, device, *, lock=False): - import torch - from b12x.sequence import tensor_from_pointer as _tensor_from_pointer - self.cuda, self.address = cuda, address self.nbytes = math.prod(shape) * dtype.itemsize self.closed = True + supported = C.c_int() + cuda.call("cuDeviceGetAttribute", C.byref(supported), C.c_int(141), C.c_int(device)) + if not supported.value: + raise RuntimeError("mapped core storage requires host-backed CUDA VMM") + import torch + from b12x.sequence import tensor_from_pointer as _tensor_from_pointer + numa = C.c_int() cuda.call("cuDeviceGetAttribute", C.byref(numa), C.c_int(134), C.c_int(device)) properties = _Properties(1, 0, _Location(3, max(0, numa.value)), None, (C.c_ubyte * 8)()) diff --git a/tests/preparation/test_core_storage.py b/tests/preparation/test_core_storage.py index ed77d9c61..e149e393f 100644 --- a/tests/preparation/test_core_storage.py +++ b/tests/preparation/test_core_storage.py @@ -78,3 +78,62 @@ def test_windows_host_range_stays_below_stalling_wddm_addresses(): # RTX Spark's driver stalls on host-address hints at 16 TiB and 32 TiB. assert CoreStorage.DEVICE_BASE + CoreStorage.RESERVATION_BYTES <= CoreStorage.HOST_BASE assert CoreStorage.HOST_BASE + CoreStorage.HOST_RESERVATION_BYTES <= 16 << 40 + + +@pytest.mark.parametrize("host_vmm,expected", [(True, "vmm"), (False, "register")]) +def test_host_allocate_selects_region_by_host_vmm(monkeypatch, host_vmm, expected): + from ignition.preparation import core_storage + + chosen = [] + closed = [] + + class FakeRegion: + def __init__(self, kind, cuda, address, extent, shape, dtype, device, *, lock=False, rounded=None): + chosen.append((kind, address, extent, device, lock)) + self.extent = extent if rounded is None else rounded + + def close(self): + closed.append(True) + + monkeypatch.setattr(core_storage, "HostVmmRegion", lambda *a, **k: FakeRegion("vmm", *a, **k)) + monkeypatch.setattr(core_storage, "HostRegion", lambda *a, **k: FakeRegion("register", *a, **k)) + storage = CoreStorage.__new__(CoreStorage) + storage.cuda = None + storage.device = 0 + storage.integrated = True + storage._host_vmm = host_vmm + storage.HOST_BASE = 0x0a_0000_0000 + storage.HOST_RESERVATION_BYTES = 8 << 30 + storage._host_cursor = storage.HOST_BASE + storage.host_regions = [] + region = storage.host_allocate("mailbox", (64,), torch.int64) + assert len(storage.host_regions) == 1 + assert chosen[0][0] == expected + assert (chosen[0][1], chosen[0][3], chosen[0][4]) == (storage.HOST_BASE, 0, True) + assert storage._host_cursor == storage.HOST_BASE + region.extent + + if host_vmm: + # HostVmmRegion rounding up to host-NUMA granularity past HOST_RESERVATION_BYTES closes and fails. + monkeypatch.setattr( + core_storage, "HostVmmRegion", + lambda *a, **k: FakeRegion("vmm", *a, rounded=2 << 20, **k), + ) + overflow_cursor = storage.HOST_BASE + storage.HOST_RESERVATION_BYTES - (1 << 20) + storage._host_cursor = overflow_cursor + with pytest.raises(MemoryError, match="host-address range exhausted"): + storage.host_allocate("overflow", (64,), torch.int64) + assert closed == [True] + assert len(storage.host_regions) == 1 + assert storage._host_cursor == overflow_cursor + + +def test_host_vmm_region_requires_host_numa_vmm(): + from ignition.preparation.core_storage import HostVmmRegion + + class StubCuda: + def call(self, name, out, attr, device): + assert name == "cuDeviceGetAttribute" and attr.value == 141 and device.value == 0 + out._obj.value = 0 + + with pytest.raises(RuntimeError, match="host-backed CUDA VMM"): + HostVmmRegion(StubCuda(), 0x0a_0000_0000, 4096, (64,), torch.int64, 0) From e88a8907ab8ed4a7ebbdd5db453c0a7f30beae5f Mon Sep 17 00:00:00 2001 From: kbenkhaled Date: Thu, 3 Dec 2026 02:49:46 +0000 Subject: [PATCH 2/2] Hold probed host VMM window and pass floor explicitly Probing the non-WDDM host VMM address range with reserve-then-free left a TOCTOU gap before HostVmmRegion mapped it, failing the host VMM probe aborted allocator initialization even for models without MappedHost storage while discarding CUDA status codes, allocator.rs hardcoded an integrated-GPU floor heuristic instead of using CoreStorage.EXTERNAL_FLOOR, and the cuDeviceGetAttribute(99/91) queries were duplicated between Helios and Heliopause. Changes: - helios/src/runtime_core/host.rs and mod.rs: move CUDA driver attribute 99/91 queries into host::use_host_vmm(driver, device) and share it across Helios and Heliopause; remove the tautological boolean/constant unit tests. - heliopause/src/allocator.rs: add min_host_base to flare_core_initialize_window (passed from CoreStorage.EXTERNAL_FLOOR); group vmm_host_window inputs into HostWindowPlan (removing clippy::too_many_arguments and unreachable granularity/usize checks); keep the successfully probed host VMM VA span reserved for the allocator lifetime (releasing it if device-window reservation fails); and record host-NUMA query or probe failures (with attempted ranges and CUDA status) in Arena.host_error instead of aborting initialization, exposing host_reserved and host_error via flare_core_snapshot(). - ignition/preparation/core_storage.py: pass self.EXTERNAL_FLOOR to flare_core_initialize_window, read host_reserved and host_error directly from the snapshot, raise host_error only in host_allocate(), drop the unused lock parameter from HostVmmRegion, and add reserved=bool so pre-reserved non-WDDM spans skip cuMemAddressReserve/cuMemAddressFree while Windows WDDM keeps its existing reserve/free lifecycle. - docs/runtime-core-design.md and tests/preparation/test_core_storage.py: document the held fallback reservation and cover deferred host_error, pre-reserved vs unreserved HostVmmRegion lifecycles, and HostWindowPlan. Result: closes the host VMM reservation race on non-WDDM host-VMM devices, keeps non-MappedHost initialization working when no host VMM window is available while surfacing full CUDA diagnostics on host_allocate(), and eliminates duplicated driver queries and hardcoded floor constants. Validation: - Jetson Orin Nano 8 GiB (SM87, JetPack 6 / CUDA 12.6, hf-orin): - Multi-region held-reservation check: CoreStorage initialized with host_vmm=True, host_reserved=True, host_error=None, DEVICE_BASE=0xc00000000, HOST_BASE=0xa00000000, extent=8 GiB; mapped two back-to-back HostVmmRegion(reserved=True) allocations inside the single held VA span (0xa00000000+0x200000, 0xa00200000+0x200000), verified bidirectional CPU/GPU reads and writes at identical virtual addresses, closed both (cuMemUnmap without freeing the held span), and mapped/verified/closed a third allocation at 0xa00400000+0x200000. - End-to-end MappedHost export + native Helios replay + teardown (helios/tests/fixed_core_fixture.py -> runtime_core::event_tests::named_external_wait_survives_export_and_native_replay): exported 6-allocation core and passed native replay in 1.13s (1 passed). - Unit tests (Thor hf-thor-v2b container): - cargo test --manifest-path helios/Cargo.toml --features runtime-core --lib host: 30 passed, 0 failed (2 GPU-only ignored) - cargo test --manifest-path heliopause/Cargo.toml --lib allocator: 19 passed, 0 failed (1 GPU-only ignored) - pytest -q tests/preparation/test_core_storage.py: 13 passed, 1 skipped (Windows-only layout test) Material limitations: Windows WDDM execution and multi-rank TP export on host-VMM hardware were not run locally; unreserved WDDM HostVmmRegion calls are covered by driver-stubbed unit tests and multi-rank placement by unit tests. Design-Signed-Off-By: Gemini 4 Neon; design-review=2e5b Signed-off-by: kbenkhaled --- docs/runtime-core-design.md | 10 +- heliopause/src/allocator.rs | 292 +++++++++++++++---------- helios/src/runtime_core/host.rs | 57 ++--- helios/src/runtime_core/mod.rs | 24 +- ignition/preparation/core_storage.py | 36 +-- tests/preparation/test_core_storage.py | 52 ++++- 6 files changed, 288 insertions(+), 183 deletions(-) diff --git a/docs/runtime-core-design.md b/docs/runtime-core-design.md index 89764b22f..86f8c7df5 100644 --- a/docs/runtime-core-design.md +++ b/docs/runtime-core-design.md @@ -101,10 +101,12 @@ separate PyTorch pools backed by that arena. Mapped host buffers, including n-gram request mailboxes, use fixed addresses from `0x0c00_0000_0000` when the device rank ranges fit below it. Larger Linux layouts start host storage at `0x2000_0000_0000` to avoid overlap. Each rank has a disjoint 1 TiB host -range (or a smaller range — 8 GiB on narrow Linux CUDA VMM apertures, or up to -1 TiB within `1 << bits` on narrow Windows WDDM adapters — adjacent to the -device windows); the native allocator reports the selected host range and -backing mode to Ignition. Linux maps and registers host pages when the device +range (or a smaller range — 8 GiB before the device window at or above the +restore floor, or after the device windows, when the default host span cannot be +reserved on non-WDDM host-VMM devices, and up to 1 TiB within `1 << bits` on +narrow Windows WDDM adapters); on non-WDDM host-VMM devices the native allocator +holds the probed host reservation for the preparation process and reports the +selected host range and backing mode to Ignition. Linux maps and registers host pages when the device supports identity-addressed host registration (`HOST_REGISTER_SUPPORTED` and `CAN_USE_HOST_POINTER_FOR_REGISTERED_MEM`); Windows and Linux devices lacking either capability use host-backed CUDA VMM (`HOST_NUMA`). diff --git a/heliopause/src/allocator.rs b/heliopause/src/allocator.rs index 1a71d7d5d..5bf55ef96 100644 --- a/heliopause/src/allocator.rs +++ b/heliopause/src/allocator.rs @@ -193,6 +193,8 @@ struct Arena { granularity: usize, gpudirect: bool, host_vmm: bool, + host_reserved: bool, + host_error: Option, host_base: u64, host_extent: u64, free: Vec<(u64, usize)>, @@ -358,13 +360,9 @@ fn window_host_layout( )) } -/// Selects a CUDA-VMM-reservable `(host_base, host_extent)` on non-WDDM platforms -/// where mapped host storage uses CUDA VMM (`HOST_REGISTER_SUPPORTED == 0` or -/// `CAN_USE_HOST_POINTER_FOR_REGISTERED_MEM == 0`). Keeps the default host range when -/// its full span is reservable; otherwise places an 8 GiB per-rank host range -/// immediately before (at or above `min_host_base`) or after the device windows. -#[allow(clippy::too_many_arguments)] -fn vmm_host_window( +const DEFAULT_EXTERNAL_FLOOR: u64 = 0x40_0000_0000; + +struct HostWindowPlan { base: u64, extent: u64, world: u32, @@ -372,58 +370,88 @@ fn vmm_host_window( min_host_base: u64, default_base: u64, default_extent: u64, - mut can_reserve: impl FnMut(u64, u64) -> Result, -) -> Result<(u64, u64)> { - if !granule.is_power_of_two() { - return Err(invalid(format!( - "invalid host allocation granularity {granule:#x}" - ))); - } - if let Some(default_total) = u64::from(world).checked_mul(default_extent) - && default_base.checked_add(default_total).is_some() - && default_base % granule == 0 - && default_extent % granule == 0 - && can_reserve(default_base, default_total)? +} + +/// Selects and reserves a `(host_base, host_extent)` on non-WDDM platforms where +/// mapped host storage uses CUDA VMM (`HOST_REGISTER_SUPPORTED == 0` or +/// `CAN_USE_HOST_POINTER_FOR_REGISTERED_MEM == 0`). `try_reserve(addr, total)` +/// reserves `[addr, addr + total)` and keeps it held on `Ok(Ok(()))`, returns +/// `Ok(Err(detail))` when that candidate range is unavailable, or returns `Err` +/// on an unrecoverable driver cleanup failure. +fn vmm_host_window( + plan: &HostWindowPlan, + mut try_reserve: impl FnMut(u64, u64) -> Result>, +) -> Result> { + let mut attempts = Vec::new(); + let mut try_candidate = |addr: u64, per_rank: u64, total: u64| -> Result> { + match try_reserve(addr, total)? { + Ok(()) => Ok(Some((addr, per_rank, total))), + Err(detail) => { + attempts.push(format!("{addr:#x}+{total:#x}: {detail}")); + Ok(None) + } + } + }; + + if let Some(default_total) = u64::from(plan.world).checked_mul(plan.default_extent) + && plan.default_base.checked_add(default_total).is_some() + && plan.default_base % plan.granule == 0 + && plan.default_extent % plan.granule == 0 + && let Some(found) = try_candidate(plan.default_base, plan.default_extent, default_total)? { - return Ok((default_base, default_extent)); + return Ok(Ok(found)); } // Align fallback host windows to at least 1 GiB so exported GiB-rounded device // reservations can never overlap a mailbox placed adjacent to a custom device window. - let window_align = granule.max(1u64 << 30); - let per_rank = (8u64 << 30).min(default_extent) & !(window_align - 1); - let total = u64::from(world).checked_mul(per_rank).filter(|&n| n > 0); - if let (Some(total), Some(device_span)) = (total, u64::from(world).checked_mul(extent)) { + let window_align = plan.granule.max(1u64 << 30); + let per_rank = (8u64 << 30).min(plan.default_extent) & !(window_align - 1); + let total = u64::from(plan.world).checked_mul(per_rank).filter(|&n| n > 0); + if let (Some(total), Some(device_span)) = (total, u64::from(plan.world).checked_mul(plan.extent)) { // Prefer placing immediately before the device window (at or above the low restore // floor) so cores exported on larger-aperture boards (e.g., 64 GiB AGX Orin) keep // their host range below smaller sibling ceilings (e.g., 8 GiB Orin Nano). - if let Some(before) = base.checked_sub(total).map(|n| n & !(window_align - 1)) - && before >= min_host_base - && can_reserve(before, total)? + if let Some(before) = plan.base.checked_sub(total).map(|n| n & !(window_align - 1)) + && before >= plan.min_host_base + && let Some(found) = try_candidate(before, per_rank, total)? { - return Ok((before, per_rank)); + return Ok(Ok(found)); } - if let Some(after) = base + if let Some(after) = plan + .base .checked_add(device_span) .and_then(|end| end.checked_add(window_align - 1)) .map(|n| n & !(window_align - 1)) && after.checked_add(total).is_some() - && can_reserve(after, total)? + && let Some(found) = try_candidate(after, per_rank, total)? { - return Ok((after, per_rank)); + return Ok(Ok(found)); } } - Err(invalid( - "no reservable CUDA VMM address range for mapped host storage", - )) + let detail = if attempts.is_empty() { + "no candidate range fits within the virtual address space".to_string() + } else { + attempts.join("; ") + }; + Ok(Err(format!( + "no reservable CUDA VMM address range for mapped host storage ({detail})" + ))) } #[unsafe(no_mangle)] extern "C" fn flare_core_initialize(rank: u32, world: u32, device: i32) -> i32 { - flare_core_initialize_window(rank, world, device, BASE, EXTENT as u64) + flare_core_initialize_window( + rank, + world, + device, + BASE, + EXTENT as u64, + DEFAULT_EXTERNAL_FLOOR, + ) } /// Initializes the allocator with rank `r`'s device window at `base + r * extent`, -/// `extent` bytes long. `flare_core_initialize` uses this platform's default window. +/// `extent` bytes long, and `min_host_base` as the lowest address a fallback host +/// VMM window may occupy. `flare_core_initialize` uses this platform's default window. /// `base` and `extent` must be multiples of the allocation granularity (`extent` /// of twice it: the lower half serves the pool, the upper half persistent /// storage), and the windows must not overlap the host ranges. @@ -434,6 +462,7 @@ extern "C" fn flare_core_initialize_window( device: i32, base: u64, extent: u64, + min_host_base: u64, ) -> i32 { let initialize = || -> Result<()> { let mut arena = ARENA.lock().unwrap_or_else(|e| e.into_inner()); @@ -445,15 +474,8 @@ extern "C" fn flare_core_initialize_window( } let extent_bytes = extent as usize; let driver = Driver::load()?; - let ( - mut address, - mut granularity, - mut gpudirect, - mut integrated, - mut host_register, - mut can_use_host_pointer, - ) = (0, 0, 0, 0, 1, 1); - let (host_vmm, host_base, host_extent) = unsafe { + let (mut address, mut granularity, mut gpudirect, mut integrated) = (0, 0, 0, 0); + let (host_vmm, host_reserved, host_error, host_base, host_extent) = unsafe { driver.check( "cuDeviceGetAttribute(INTEGRATED)", (driver.device_attribute)( @@ -462,22 +484,6 @@ extern "C" fn flare_core_initialize_window( device, ), )?; - driver.check( - "cuDeviceGetAttribute(HOST_REGISTER_SUPPORTED)", - (driver.device_attribute)( - &mut host_register, - driver::CU_DEVICE_ATTRIBUTE_HOST_REGISTER_SUPPORTED, - device, - ), - )?; - driver.check( - "cuDeviceGetAttribute(CAN_USE_HOST_POINTER_FOR_REGISTERED_MEM)", - (driver.device_attribute)( - &mut can_use_host_pointer, - driver::CU_DEVICE_ATTRIBUTE_CAN_USE_HOST_POINTER_FOR_REGISTERED_MEM, - device, - ), - )?; driver.check( "cuDeviceGetAttribute(GPU_DIRECT_RDMA_SUPPORTED)", (driver.device_attribute)( @@ -508,56 +514,65 @@ extern "C" fn flare_core_initialize_window( let bits = address_space::virtual_address_bits(device); let (default_host_base, default_host_extent) = window_host_layout(base, extent, world, granule, bits)?; - let host_vmm = host::use_host_vmm( - cfg!(windows), - host_register != 0, - can_use_host_pointer != 0, - ); + let host_vmm = host::use_host_vmm(&driver, device)?; // Never run speculative cuMemAddressReserve probes on Windows WDDM, where // out-of-range fixed addresses can hang even when D3DKMT width lookup fails. - let (host_base, host_extent) = if !cfg!(windows) && host_vmm { - if let Some((_, host_granularity)) = host::host_numa_properties(&driver, device)? { - let host_granule = granule.max(host_granularity as u64); - let host_align = usize::try_from(host_granule).map_err(|_| { - invalid(format!( - "invalid host CUDA allocation granularity {host_granule:#x}" - )) - })?; - let min_host_base = if integrated != 0 && base < 0x40_0000_0000 { - 0x3_0000_0000 - } else { - 0x40_0000_0000 - }; - vmm_host_window( - base, - extent, - world, - host_granule, - min_host_base, - default_host_base, - default_host_extent, - |addr, bytes| { + let mut held_host: Option<(u64, usize)> = None; + let (host_reserved, host_error, host_base, host_extent) = if !cfg!(windows) && host_vmm { + match host::host_numa_properties(&driver, device) { + Ok(Some((_, host_granularity))) => { + let host_align = granularity.max(host_granularity); + let plan = HostWindowPlan { + base, + extent, + world, + granule: host_align as u64, + min_host_base, + default_base: default_host_base, + default_extent: default_host_extent, + }; + match vmm_host_window(&plan, |addr, bytes| { let Ok(len) = usize::try_from(bytes) else { - return Ok(false); + return Ok(Err("range exceeds host usize".to_string())); }; let mut probe = 0; let status = (driver.reserve)(&mut probe, len, host_align, addr, 0); - if status == 0 { + if status == 0 && probe == addr { + Ok(Ok(())) + } else if status == 0 { driver.check( "cuMemAddressFree(host probe)", (driver.release_address)(probe, len), )?; - Ok(probe == addr) + Ok(Err(format!("CUDA returned {probe:#x}"))) } else { - Ok(false) + Ok(Err(format!("cuMemAddressReserve status {status}"))) } - }, - )? - } else { - (default_host_base, default_host_extent) + })? { + Ok((selected_base, selected_extent, total)) => { + held_host = Some((selected_base, total as usize)); + (true, None, selected_base, selected_extent) + } + Err(message) => { + (false, Some(message), default_host_base, default_host_extent) + } + } + } + Ok(None) => ( + false, + Some("mapped core storage requires host-backed CUDA VMM".to_string()), + default_host_base, + default_host_extent, + ), + Err(error) => ( + false, + Some(error.to_string()), + default_host_base, + default_host_extent, + ), } } else { - (default_host_base, default_host_extent) + (false, None, default_host_base, default_host_extent) }; let mut reserved = Vec::new(); for peer in 0..world { @@ -570,6 +585,9 @@ extern "C" fn flare_core_initialize_window( for address in reserved { (driver.release_address)(address, extent_bytes); } + if let Some((host_addr, host_len)) = held_host { + (driver.release_address)(host_addr, host_len); + } driver.check("cuMemAddressReserve", status)?; return Err(invalid(format!( "native core device address range {start:#x}+{extent:#x} is unavailable; CUDA returned {address:#x}" @@ -577,7 +595,7 @@ extern "C" fn flare_core_initialize_window( } reserved.push(address); } - (host_vmm, host_base, host_extent) + (host_vmm, host_reserved, host_error, host_base, host_extent) }; *arena = Some(Arena { driver, @@ -585,6 +603,8 @@ extern "C" fn flare_core_initialize_window( granularity, gpudirect: gpudirect != 0 && integrated == 0, host_vmm, + host_reserved, + host_error, host_base: host_base + u64::from(rank) * host_extent, host_extent, free: vec![(base + u64::from(rank) * extent, extent_bytes / 2)], @@ -861,6 +881,8 @@ extern "C" fn flare_core_snapshot() -> *mut c_char { let value = serde_json::json!({ "granularity": a.granularity, "mappings": a.mappings, "host_vmm": a.host_vmm, + "host_reserved": a.host_reserved, + "host_error": a.host_error, "host_base": a.host_base, "host_extent": a.host_extent, "retained_reference_bytes": a.retained.reference_bytes, "retained_handles": a.retained.handles.len(), @@ -1362,6 +1384,8 @@ mod tests { granularity: 4096, gpudirect: false, host_vmm: false, + host_reserved: false, + host_error: None, host_base: 0, host_extent: 0, free: Vec::new(), @@ -1442,6 +1466,8 @@ mod tests { granularity: 4096, gpudirect: false, host_vmm: false, + host_reserved: false, + host_error: None, host_base: 0, host_extent: 0, free: Vec::new(), @@ -1487,6 +1513,8 @@ mod tests { granularity: 4096, gpudirect: false, host_vmm: false, + host_reserved: false, + host_error: None, host_base: 0, host_extent: 0, free: Vec::new(), @@ -1592,15 +1620,33 @@ mod tests { let orin_floor = 0x3_0000_0000u64; let orin_nano_cap = 0x18_23c0_0000u64; let agx_orin_cap = 0x20_0000_0000u64; - let below = |cap: u64| move |addr: u64, len: u64| Ok(addr.checked_add(len).is_some_and(|e| e <= cap)); + let below = |cap: u64| { + move |addr: u64, len: u64| { + if addr.checked_add(len).is_some_and(|e| e <= cap) { + Ok(Ok(())) + } else { + Ok(Err("cuMemAddressReserve status 1".to_string())) + } + } + }; + let plan = |base, extent, world, min_host_base| HostWindowPlan { + base, + extent, + world, + granule, + min_host_base, + default_base: HOST_BASE, + default_extent: EXTENT as u64, + }; // Both 8 GiB Orin Nano and 64 GiB AGX Orin place host VMM at 40..48 GiB so cores // exported on AGX remain loadable on Nano. for cap in [orin_nano_cap, agx_orin_cap] { assert_eq!( - vmm_host_window(0x0c_0000_0000, 48 << 30, 1, granule, orin_floor, HOST_BASE, EXTENT as u64, below(cap)) + vmm_host_window(&plan(0x0c_0000_0000, 48 << 30, 1, orin_floor), below(cap)) + .unwrap() .unwrap(), - (0x0a_0000_0000, 8 << 30) + (0x0a_0000_0000, 8 << 30, 8 << 30) ); } @@ -1608,32 +1654,50 @@ mod tests { // would collide with seal_low_window(), so host VMM falls back to post-device // rounded up to 1 GiB so exported GiB-aligned device reservations never overlap. assert_eq!( - vmm_host_window(orin_floor, (48 << 30) + (4 << 20), 1, granule, orin_floor, HOST_BASE, EXTENT as u64, below(orin_nano_cap)) - .unwrap(), - (orin_floor + (49 << 30), 8 << 30) + vmm_host_window( + &plan(orin_floor, (48 << 30) + (4 << 20), 1, orin_floor), + below(orin_nano_cap), + ) + .unwrap() + .unwrap(), + (orin_floor + (49 << 30), 8 << 30, 8 << 30) ); // Multi-rank (world = 2): host span covers both ranks (2 * 8 GiB) and rejects a // default window where only rank 0 would fit. let partial_default_cap = HOST_BASE + EXTENT as u64; assert_eq!( - vmm_host_window(0x0c_0000_0000, 32 << 30, 2, granule, orin_floor, HOST_BASE, EXTENT as u64, below(partial_default_cap)) - .unwrap(), - (0x08_0000_0000, 8 << 30) + vmm_host_window( + &plan(0x0c_0000_0000, 32 << 30, 2, orin_floor), + below(partial_default_cap), + ) + .unwrap() + .unwrap(), + (0x08_0000_0000, 8 << 30, 16 << 30) ); // Full 48-bit aperture keeps the default host base unchanged. assert_eq!( - vmm_host_window(0x0c_0000_0000, 48 << 30, 2, granule, orin_floor, HOST_BASE, EXTENT as u64, |_, _| Ok(true)) + vmm_host_window(&plan(0x0c_0000_0000, 48 << 30, 2, orin_floor), |_, _| Ok(Ok(()))) + .unwrap() .unwrap(), - (HOST_BASE, EXTENT as u64) + (HOST_BASE, EXTENT as u64, 2 * EXTENT as u64) ); - // Reject invalid granularity, unreservable apertures, and probe cleanup failures. - assert!(vmm_host_window(0x0c_0000_0000, 48 << 30, 1, 0, orin_floor, HOST_BASE, EXTENT as u64, |_, _| Ok(true)).is_err()); - assert!(vmm_host_window(0x0c_0000_0000, 48 << 30, 1, 3 << 20, orin_floor, HOST_BASE, EXTENT as u64, |_, _| Ok(true)).is_err()); - assert!(vmm_host_window(0x0c_0000_0000, 48 << 30, 1, granule, orin_floor, HOST_BASE, EXTENT as u64, |_, _| Ok(false)).is_err()); - assert!(vmm_host_window(0x0c_0000_0000, 48 << 30, 1, granule, orin_floor, HOST_BASE, EXTENT as u64, |_, _| Err(invalid("release failed"))).is_err()); + // Unreservable apertures return a non-fatal diagnostic preserving CUDA status and ranges, + // while cleanup failures still propagate as hard errors. + let msg = vmm_host_window(&plan(0x0c_0000_0000, 48 << 30, 1, orin_floor), |_, _| { + Ok(Err("cuMemAddressReserve status 2".to_string())) + }) + .unwrap() + .unwrap_err(); + assert!(msg.contains("status 2") && msg.contains("0xa00000000+0x200000000")); + assert!( + vmm_host_window(&plan(0x0c_0000_0000, 48 << 30, 1, orin_floor), |_, _| { + Err(invalid("release failed")) + }) + .is_err() + ); } #[test] diff --git a/helios/src/runtime_core/host.rs b/helios/src/runtime_core/host.rs index e2121e459..384a5588d 100644 --- a/helios/src/runtime_core/host.rs +++ b/helios/src/runtime_core/host.rs @@ -9,12 +9,37 @@ use super::{Result, invalid}; -pub fn use_host_vmm( - windows: bool, - host_register_supported: bool, - can_use_host_pointer: bool, -) -> bool { - windows || !host_register_supported || !can_use_host_pointer +/// Whether mapped host storage on `device` must use host-backed CUDA VMM +/// instead of registering host pages at an identical CPU/GPU virtual address. +/// +/// # Safety +/// `driver` must be initialized and `device` must be a valid CUDA device ordinal. +pub unsafe fn use_host_vmm(driver: &super::driver::Driver, device: i32) -> Result { + use super::driver; + if cfg!(windows) { + return Ok(true); + } + unsafe { + let mut host_register_supported = 1; + driver.check( + "cuDeviceGetAttribute(HOST_REGISTER_SUPPORTED)", + (driver.device_attribute)( + &mut host_register_supported, + driver::CU_DEVICE_ATTRIBUTE_HOST_REGISTER_SUPPORTED, + device, + ), + )?; + let mut can_use_host_pointer = 1; + driver.check( + "cuDeviceGetAttribute(CAN_USE_HOST_POINTER_FOR_REGISTERED_MEM)", + (driver.device_attribute)( + &mut can_use_host_pointer, + driver::CU_DEVICE_ATTRIBUTE_CAN_USE_HOST_POINTER_FOR_REGISTERED_MEM, + device, + ), + )?; + Ok(host_register_supported == 0 || can_use_host_pointer == 0) + } } fn ranges( @@ -198,24 +223,4 @@ mod tests { assert!(ranges([(u64::MAX - 4095, 4096)].into_iter(), 2 << 20).is_err()); assert!(ranges([(4096, 4096)].into_iter(), 0).is_err()); } - - #[test] - fn host_vmm_dispatch_requires_both_host_register_and_host_pointer() { - use super::super::driver; - assert_eq!(driver::CU_DEVICE_ATTRIBUTE_CAN_USE_HOST_POINTER_FOR_REGISTERED_MEM, 91); - assert_eq!(driver::CU_DEVICE_ATTRIBUTE_HOST_REGISTER_SUPPORTED, 99); - assert_eq!(driver::CU_DEVICE_ATTRIBUTE_HOST_NUMA_ID, 134); - assert_eq!(driver::CU_DEVICE_ATTRIBUTE_HOST_NUMA_VMM, 141); - for windows in [false, true] { - for host_reg in [false, true] { - for host_ptr in [false, true] { - assert_eq!( - use_host_vmm(windows, host_reg, host_ptr), - windows || !host_reg || !host_ptr, - "windows={windows} host_reg={host_reg} host_ptr={host_ptr}" - ); - } - } - } - } } diff --git a/helios/src/runtime_core/mod.rs b/helios/src/runtime_core/mod.rs index fff0d2b24..286850108 100644 --- a/helios/src/runtime_core/mod.rs +++ b/helios/src/runtime_core/mod.rs @@ -361,29 +361,7 @@ impl NativeResources { "cuDeviceGetAttribute(INTEGRATED)", (driver.device_attribute)(&mut integrated, driver::CU_DEVICE_ATTRIBUTE_INTEGRATED, device), )?; - let mut host_register_supported = 1; - driver.check( - "cuDeviceGetAttribute(HOST_REGISTER_SUPPORTED)", - (driver.device_attribute)( - &mut host_register_supported, - driver::CU_DEVICE_ATTRIBUTE_HOST_REGISTER_SUPPORTED, - device, - ), - )?; - let mut can_use_host_pointer = 1; - driver.check( - "cuDeviceGetAttribute(CAN_USE_HOST_POINTER_FOR_REGISTERED_MEM)", - (driver.device_attribute)( - &mut can_use_host_pointer, - driver::CU_DEVICE_ATTRIBUTE_CAN_USE_HOST_POINTER_FOR_REGISTERED_MEM, - device, - ), - )?; - let host_vmm = host::use_host_vmm( - cfg!(windows), - host_register_supported != 0, - can_use_host_pointer != 0, - ); + let host_vmm = host::use_host_vmm(&driver, device)?; if let Some(execution) = core.execution.as_ref() && execution.persistent_workers.len() > 1 { diff --git a/ignition/preparation/core_storage.py b/ignition/preparation/core_storage.py index b19809912..c88711549 100644 --- a/ignition/preparation/core_storage.py +++ b/ignition/preparation/core_storage.py @@ -92,8 +92,8 @@ def __init__(self, *, rank=0, world=1, device=0, local_ranks=None, device_window self.library.flare_core_error.restype = C.c_char_p self.library.flare_core_snapshot.restype = C.c_void_p self.library.flare_core_initialize_window.argtypes = [ - C.c_uint32, C.c_uint32, C.c_int32, C.c_uint64, C.c_uint64] - if self.library.flare_core_initialize_window(rank, world, device, *window): + C.c_uint32, C.c_uint32, C.c_int32, C.c_uint64, C.c_uint64, C.c_uint64] + if self.library.flare_core_initialize_window(rank, world, device, *window, self.EXTERNAL_FLOOR): raise self.error or RuntimeError("cannot initialize native core allocator") layout = self._snapshot() self.granularity = layout["granularity"] @@ -101,8 +101,10 @@ def __init__(self, *, rank=0, world=1, device=0, local_ranks=None, device_window self.cuda.call("cuDeviceGetAttribute", C.byref(gpudirect), C.c_int(116), C.c_int(device)) self.gpudirect = bool(gpudirect.value) and not self.integrated self._host_vmm = bool(layout["host_vmm"]) + self._host_reserved = bool(layout["host_reserved"]) + self._host_error = layout["host_error"] self.HOST_BASE = layout["host_base"] - self.HOST_RESERVATION_BYTES = layout.get("host_extent", self.HOST_RESERVATION_BYTES) + self.HOST_RESERVATION_BYTES = layout["host_extent"] self._host_cursor = self.HOST_BASE self.low_reservations = [] # WDDM retains its low allocation pool; export rejects retained storage below the floor. @@ -350,14 +352,19 @@ def close(self): self._persistent_closed = True def host_allocate(self, name, shape, dtype): + if self._host_error: + raise RuntimeError(self._host_error) size = math.prod(shape) * dtype.itemsize # Host mappings are whole host pages; Grace kernels may use 64 KiB pages. extent = -(-size // mmap.PAGESIZE) * mmap.PAGESIZE - region_type = HostVmmRegion if self._host_vmm else HostRegion if self._host_cursor + extent > self.HOST_BASE + self.HOST_RESERVATION_BYTES: raise MemoryError("native core host-address range exhausted") - region = region_type(self.cuda, self._host_cursor, extent, shape, dtype, self.device, - lock=self.integrated) + if self._host_vmm: + region = HostVmmRegion(self.cuda, self._host_cursor, extent, shape, dtype, self.device, + reserved=self._host_reserved) + else: + region = HostRegion(self.cuda, self._host_cursor, extent, shape, dtype, self.device, + lock=self.integrated) if self._host_cursor + region.extent > self.HOST_BASE + self.HOST_RESERVATION_BYTES: region.close() raise MemoryError("native core host-address range exhausted") @@ -492,8 +499,8 @@ class _Access(C.Structure): class HostVmmRegion: """Host-backed CUDA VMM storage at one recorded CPU/GPU virtual address.""" - def __init__(self, cuda, address, extent, shape, dtype, device, *, lock=False): - self.cuda, self.address = cuda, address + def __init__(self, cuda, address, extent, shape, dtype, device, *, reserved=False): + self.cuda, self.address, self.reserved = cuda, address, bool(reserved) self.nbytes = math.prod(shape) * dtype.itemsize self.closed = True supported = C.c_int() @@ -509,9 +516,10 @@ def __init__(self, cuda, address, extent, shape, dtype, device, *, lock=False): granularity = C.c_size_t() cuda.call("cuMemGetAllocationGranularity", C.byref(granularity), C.byref(properties), C.c_int(0)) self.extent = -(-extent // granularity.value) * granularity.value - pointer = C.c_uint64() - cuda.call("cuMemAddressReserve", C.byref(pointer), C.c_size_t(self.extent), - C.c_size_t(granularity.value), C.c_uint64(address), C.c_uint64(0)) + pointer = C.c_uint64(address) + if not self.reserved: + cuda.call("cuMemAddressReserve", C.byref(pointer), C.c_size_t(self.extent), + C.c_size_t(granularity.value), C.c_uint64(address), C.c_uint64(0)) mapped = False try: if pointer.value != address: @@ -532,7 +540,8 @@ def __init__(self, cuda, address, extent, shape, dtype, device, *, lock=False): except BaseException: if mapped: cuda.call("cuMemUnmap", pointer, C.c_size_t(self.extent)) - cuda.call("cuMemAddressFree", pointer, C.c_size_t(self.extent)) + if not self.reserved: + cuda.call("cuMemAddressFree", pointer, C.c_size_t(self.extent)) raise self.closed = False @@ -540,7 +549,8 @@ def close(self): if not self.closed: self.cuda.call("cuCtxSynchronize") self.cuda.call("cuMemUnmap", C.c_uint64(self.address), C.c_size_t(self.extent)) - self.cuda.call("cuMemAddressFree", C.c_uint64(self.address), C.c_size_t(self.extent)) + if not self.reserved: + self.cuda.call("cuMemAddressFree", C.c_uint64(self.address), C.c_size_t(self.extent)) self.closed = True diff --git a/tests/preparation/test_core_storage.py b/tests/preparation/test_core_storage.py index e149e393f..86217d96f 100644 --- a/tests/preparation/test_core_storage.py +++ b/tests/preparation/test_core_storage.py @@ -88,8 +88,8 @@ def test_host_allocate_selects_region_by_host_vmm(monkeypatch, host_vmm, expecte closed = [] class FakeRegion: - def __init__(self, kind, cuda, address, extent, shape, dtype, device, *, lock=False, rounded=None): - chosen.append((kind, address, extent, device, lock)) + def __init__(self, kind, cuda, address, extent, shape, dtype, device, *, lock=False, reserved=False, rounded=None): + chosen.append((kind, address, extent, device, lock, reserved)) self.extent = extent if rounded is None else rounded def close(self): @@ -102,6 +102,8 @@ def close(self): storage.device = 0 storage.integrated = True storage._host_vmm = host_vmm + storage._host_reserved = host_vmm + storage._host_error = None storage.HOST_BASE = 0x0a_0000_0000 storage.HOST_RESERVATION_BYTES = 8 << 30 storage._host_cursor = storage.HOST_BASE @@ -109,7 +111,9 @@ def close(self): region = storage.host_allocate("mailbox", (64,), torch.int64) assert len(storage.host_regions) == 1 assert chosen[0][0] == expected - assert (chosen[0][1], chosen[0][3], chosen[0][4]) == (storage.HOST_BASE, 0, True) + assert (chosen[0][1], chosen[0][3], chosen[0][4], chosen[0][5]) == ( + storage.HOST_BASE, 0, not host_vmm, host_vmm, + ) assert storage._host_cursor == storage.HOST_BASE + region.extent if host_vmm: @@ -126,6 +130,11 @@ def close(self): assert len(storage.host_regions) == 1 assert storage._host_cursor == overflow_cursor + # Deferred host VMM probe error surfaces only on host_allocate(). + storage._host_error = "no reservable CUDA VMM address range (status 2)" + with pytest.raises(RuntimeError, match="status 2"): + storage.host_allocate("deferred_fail", (64,), torch.int64) + def test_host_vmm_region_requires_host_numa_vmm(): from ignition.preparation.core_storage import HostVmmRegion @@ -137,3 +146,40 @@ def call(self, name, out, attr, device): with pytest.raises(RuntimeError, match="host-backed CUDA VMM"): HostVmmRegion(StubCuda(), 0x0a_0000_0000, 4096, (64,), torch.int64, 0) + + +@pytest.mark.parametrize("reserved", [False, True]) +def test_host_vmm_region_respects_pre_reserved_flag(monkeypatch, reserved): + import sys + import types + from ignition.preparation.core_storage import HostVmmRegion + + buf = ctypes.create_string_buffer(4096) + address = ctypes.addressof(buf) + calls = [] + + class StubCuda: + def call(self, name, *args): + calls.append(name) + if name == "cuDeviceGetAttribute": + out, attr, _device = args + out._obj.value = 1 if attr.value == 141 else 0 + elif name == "cuMemGetAllocationGranularity": + args[0]._obj.value = 4096 + elif name == "cuMemAddressReserve": + args[0]._obj.value = args[3].value + elif name == "cuMemCreate": + args[0]._obj.value = 7 + + fake_seq = types.ModuleType("b12x.sequence") + fake_seq.tensor_from_pointer = lambda ptr, **kw: (ptr, kw["device"].type) + fake_b12x = types.ModuleType("b12x") + fake_b12x.sequence = fake_seq + monkeypatch.setitem(sys.modules, "b12x", fake_b12x) + monkeypatch.setitem(sys.modules, "b12x.sequence", fake_seq) + + region = HostVmmRegion(StubCuda(), address, 4096, (64,), torch.int64, 0, reserved=reserved) + region.close() + assert ("cuMemAddressReserve" in calls) is (not reserved) + assert ("cuMemAddressFree" in calls) is (not reserved) + assert "cuMemMap" in calls and "cuMemUnmap" in calls