diff --git a/docs/runtime-core-design.md b/docs/runtime-core-design.md index ec57fc553..b3de796f4 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,15 @@ 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 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`). 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 @@ -112,11 +119,13 @@ 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 its external device floor (`CoreStorage.EXTERNAL_FLOOR`: 256 GiB -by default, or 36 GiB for integrated GA10B / SM 8.7's default 128 GiB VMM layout -with a 72 GiB device base and 48 GiB reservation) without physical backing. -Windows retains the driver's low allocation pool. Export on either integrated -platform rejects reachable external device storage below that floor, where -context mappings can prevent replay. +by default, or 36 GiB for integrated GA10B / SM 8.7 with a 48 GiB device base +and 48 GiB reservation, leaving `[36 GiB, 40 GiB)` for external allocations and +`[40 GiB, 48 GiB)` for host VMM within both Orin Nano's ~96.5 GiB and AGX +Orin's 128 GiB VMM ceilings) without physical backing. Windows retains the +driver's low allocation pool. Export on either integrated platform rejects +reachable 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..5bf55ef96 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,9 @@ struct Arena { device: i32, granularity: usize, gpudirect: bool, + host_vmm: bool, + host_reserved: bool, + host_error: Option, host_base: u64, host_extent: u64, free: Vec<(u64, usize)>, @@ -356,13 +360,98 @@ fn window_host_layout( )) } +const DEFAULT_EXTERNAL_FLOOR: u64 = 0x40_0000_0000; + +struct HostWindowPlan { + base: u64, + extent: u64, + world: u32, + granule: u64, + min_host_base: u64, + default_base: u64, + default_extent: u64, +} + +/// 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(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 = 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) = 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(Ok(found)); + } + 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() + && let Some(found) = try_candidate(after, per_rank, total)? + { + return Ok(Ok(found)); + } + } + 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. @@ -373,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()); @@ -385,14 +475,22 @@ 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 (host_vmm, host_reserved, host_error, 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(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 +500,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 +512,68 @@ 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(&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 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(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 && probe == addr { + Ok(Ok(())) + } else if status == 0 { + driver.check( + "cuMemAddressFree(host probe)", + (driver.release_address)(probe, len), + )?; + Ok(Err(format!("CUDA returned {probe:#x}"))) + } else { + Ok(Err(format!("cuMemAddressReserve status {status}"))) + } + })? { + 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 { + (false, None, default_host_base, default_host_extent) + }; let mut reserved = Vec::new(); for peer in 0..world { let start = base + u64::from(peer) * extent; @@ -427,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}" @@ -434,13 +595,16 @@ extern "C" fn flare_core_initialize_window( } reserved.push(address); } - (host_base, host_extent) + (host_vmm, host_reserved, host_error, host_base, host_extent) }; *arena = Some(Arena { driver, device, 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)], @@ -716,6 +880,9 @@ 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(), @@ -1216,6 +1383,9 @@ mod tests { device: 0, granularity: 4096, gpudirect: false, + host_vmm: false, + host_reserved: false, + host_error: None, host_base: 0, host_extent: 0, free: Vec::new(), @@ -1295,6 +1465,9 @@ mod tests { device: 0, granularity: 4096, gpudirect: false, + host_vmm: false, + host_reserved: false, + host_error: None, host_base: 0, host_extent: 0, free: Vec::new(), @@ -1339,6 +1512,9 @@ mod tests { device: 0, granularity: 4096, gpudirect: false, + host_vmm: false, + host_reserved: false, + host_error: None, host_base: 0, host_extent: 0, free: Vec::new(), @@ -1438,6 +1614,92 @@ 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| { + 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(&plan(0x0c_0000_0000, 48 << 30, 1, orin_floor), below(cap)) + .unwrap() + .unwrap(), + (0x0a_0000_0000, 8 << 30, 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( + &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( + &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(&plan(0x0c_0000_0000, 48 << 30, 2, orin_floor), |_, _| Ok(Ok(()))) + .unwrap() + .unwrap(), + (HOST_BASE, EXTENT as u64, 2 * EXTENT as u64) + ); + + // 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] 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 91538b383..2ad55f5ca 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..384a5588d 100644 --- a/helios/src/runtime_core/host.rs +++ b/helios/src/runtime_core/host.rs @@ -3,10 +3,45 @@ * 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}; +/// 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( allocations: impl Iterator, granularity: usize, @@ -39,11 +74,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 +137,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 +150,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 +183,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()), diff --git a/helios/src/runtime_core/mod.rs b/helios/src/runtime_core/mod.rs index d7238044a..c283261c0 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>, @@ -359,9 +359,10 @@ 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 host_vmm = host::use_host_vmm(&driver, device)?; if let Some(execution) = core.execution.as_ref() && execution.persistent_workers.len() > 1 { @@ -420,9 +421,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, @@ -540,8 +541,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(); @@ -622,7 +622,7 @@ impl NativeResources { } Memory::MappedHost => { #[cfg(unix)] - { + if !self.host_vmm { let mapped = libc::mmap( address as Handle, allocation.nbytes, @@ -688,7 +688,7 @@ impl NativeResources { } Memory::MappedHost => { #[cfg(unix)] - { + if !self.host_vmm { let mut gpu = 0; driver.check( "cuMemHostGetDevicePointer_v2", @@ -1829,7 +1829,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); } @@ -1837,7 +1837,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 69b847b50..577ff897d 100644 --- a/ignition/preparation/core_storage.py +++ b/ignition/preparation/core_storage.py @@ -64,12 +64,13 @@ 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). - # Place EXTERNAL_FLOOR at 0x9_0000_0000 (36 GiB) so external library allocations lie in - # the 36 GiB [0x9_0000_0000, 0x12_0000_0000) band below DEVICE_BASE (72 GiB), above - # cuRAND precalc_xorwow_offset_matrix 64-bit words in [0x3_0000_0000, 0x3_0300_0000]. + # Jetson Orin (GA10B) exposes ~96.5 GiB VMM on 8 GiB Nano and 128 GiB on 64 GiB AGX. + # Place EXTERNAL_FLOOR at 0x9_0000_0000 (36 GiB, above cuRAND offset-matrix words in + # [0x3_0000_0000, 0x3_0300_0000]) and DEVICE_BASE at 0x0c_0000_0000 (48 GiB) so + # [48 GiB, 96 GiB) fits both boards while leaving [36 GiB, 40 GiB) for external + # allocations and [40 GiB, 48 GiB) for host VMM reservations. self.EXTERNAL_FLOOR = 0x900000000 - 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 @@ -94,16 +95,19 @@ 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"] 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_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. @@ -351,14 +355,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 = WindowsHostRegion if os.name == "nt" 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") @@ -490,25 +499,30 @@ 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): + 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() + 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 - self.cuda, self.address = cuda, address - self.nbytes = math.prod(shape) * dtype.itemsize - self.closed = True 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)()) 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: @@ -529,7 +543,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 @@ -537,7 +552,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 5386deeac..5f6a0b36e 100644 --- a/tests/preparation/test_core_storage.py +++ b/tests/preparation/test_core_storage.py @@ -80,6 +80,111 @@ def test_windows_host_range_stays_below_stalling_wddm_addresses(): 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, reserved=False, rounded=None): + chosen.append((kind, address, extent, device, lock, reserved)) + 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_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 + 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], chosen[0][5]) == ( + storage.HOST_BASE, 0, not host_vmm, host_vmm, + ) + 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 + + # 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 + + 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) + + +@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 + + def test_ga10b_integrated_window_places_external_floor_above_curand_table(monkeypatch): from types import SimpleNamespace from ignition.preparation import core_storage @@ -106,7 +211,7 @@ def __init__(self): assert recorded["called"] assert owner.integrated is True assert owner.EXTERNAL_FLOOR == 0x900000000 - assert owner.DEVICE_BASE == 0x1200000000 + assert owner.DEVICE_BASE == 0x0c00000000 assert owner.RESERVATION_BYTES == 48 << 30