From 4b6a19fa2a656c7b8b2de3c548d0a201b85c4b55 Mon Sep 17 00:00:00 2001 From: Garret Buell Date: Sat, 14 Nov 2026 10:16:00 -0800 Subject: [PATCH 1/3] Check fixed reservations against the WDDM GPU address width Under WDDM, cuMemAddressReserve with a fixed address beyond the GPU's virtual address space does not return. docs/windows.md records this for host reservations at 16 TiB and 32 TiB on RTX Spark N1X. The same hang occurs for Heliopause's default Windows device window (4 TiB, 1 TiB per rank) on a GPU whose WDDM address space is 1 TiB. Export and load then stall inside the driver without an error, and the process must be killed. WDDM reports the address width per adapter, so a reservation that cannot fit can be rejected before it is requested. helios/src/runtime_core/address_space.rs adds virtual_address_bits, which maps a CUDA device to its WDDM adapter (cuDeviceGetLuid, then D3DKMTOpenAdapterFromLuid) and returns the VirtualAddressBitCount that D3DKMTQueryAdapterInfo reports for KMTQAITYPE_QUERY_GPUMMU_CAPS. It also adds check_fits, which rejects a range ending beyond 2^bits. Outside Windows, or when the query fails, the width is unknown and nothing is rejected. Helios checks each core reservation and each Windows host reservation before reserving it; Heliopause checks every rank's device window in flare_core_initialize. A reservation that fits behaves as before. docs/windows.md describes the check and what it does not cover: Linux, and Ignition's own host-region reservations during export. Result: on a GPU whose address space cannot hold a fixed window, export and load fail immediately with an error that names the reservation and the width, instead of hanging. Evidence, on Windows 11 build 26200 with an RTX 3090 (SM86, not a supported GPU; WDDM reports 40 bits) and NVIDIA driver 621.01: - heliopause's reports_the_device_address_width (ignored by default; run with --include-ignored) prints 40 bits for device 0, read through the CUDA LUID to adapter mapping. - CoreStorage() with the default Windows window fails after 0.02 s: "native core device window 0x40000000000+0x10000000000 exceeds the GPU's 40-bit virtual address space". Without this check the same call does not return. This ran on a tree that also contains the explicit device window and device identity changes that follow and #293/#294, which Windows builds and exports need. - With the check active, the Helios loader loaded a 15.5 GiB core exported at 256 GiB, and an existing core, and replayed all 13 of each one's graphs bit-identically to the export. - heliopause's library suite passes except sync_parent_normalizes_a_relative_basename, which fails with "Access is denied" with and without this change. check_fits's unit test is in Helios, whose library tests do not compile on Windows (execution/roce_fabric.rs uses std::os::unix); it was not run. Not tested: any supported GPU. Whether RTX Spark N1X reports 44 bits, which would explain the 16 TiB host hang, is unverified. Design-Signed-Off-By: Claude Opus 5.5 (Claude Code); design-review=ed22 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Garret Buell --- docs/windows.md | 9 ++ heliopause/src/allocator.rs | 24 ++++ helios/src/runtime_core/address_space.rs | 148 +++++++++++++++++++++++ helios/src/runtime_core/host.rs | 3 + helios/src/runtime_core/mod.rs | 9 ++ 5 files changed, 193 insertions(+) create mode 100644 helios/src/runtime_core/address_space.rs diff --git a/docs/windows.md b/docs/windows.md index 539331b45..25e362698 100644 --- a/docs/windows.md +++ b/docs/windows.md @@ -231,6 +231,15 @@ does not relocate graph storage, so such a core must be re-exported before Windows use. Re-export a Linux TP1 core to a different filename; its host storage is placed at 12 TiB. +Under WDDM, export and load compare every fixed reservation with the GPU +virtual address width that WDDM reports for the device's adapter +(`D3DKMTQueryAdapterInfo` with `KMTQAITYPE_QUERY_GPUMMU_CAPS`) before +requesting it, and fail with an error naming the reservation and the width +instead of calling `cuMemAddressReserve` with an address it cannot return +from. The check covers Heliopause's device windows and the device and host +reservations Helios makes for a core. Linux reservations and Ignition's own +host-region reservations during export are not checked. + Validate fixed device mappings and graph replay using the exported runtime fixtures on each target GPU. Cores with mapped host storage additionally require mapped access, stream-memory waits, and external event ordering tests. diff --git a/heliopause/src/allocator.rs b/heliopause/src/allocator.rs index d91759ab9..84efe412d 100644 --- a/heliopause/src/allocator.rs +++ b/heliopause/src/allocator.rs @@ -13,6 +13,7 @@ use std::{ sync::Mutex, }; +use crate::runtime_core::address_space; use crate::runtime_core::driver::{Access, AllocationProperties, Driver, Location}; use crate::{Error, ExecutionError, Result}; @@ -288,6 +289,12 @@ extern "C" fn flare_core_initialize(rank: u32, world: u32, device: i32) -> i32 { "cuMemGetAllocationGranularity", (driver.granularity)(&mut granularity, &properties(device, gpudirect != 0), 0), )?; + let bits = address_space::virtual_address_bits(device); + for peer in 0..world { + let base = BASE + u64::from(peer) * EXTENT as u64; + address_space::check_fits("native core device window", base, EXTENT as u64, bits) + .map_err(invalid)?; + } let mut reserved = Vec::new(); for peer in 0..world { let base = BASE + u64::from(peer) * EXTENT as u64; @@ -1260,4 +1267,21 @@ mod tests { assert!(device_base + u64::from(world) * EXTENT as u64 <= host); } } + + /// Prints device 0's WDDM GPU virtual address width; run with --ignored on a CUDA host. + #[test] + #[ignore = "needs a CUDA device"] + fn reports_the_device_address_width() { + let driver = Driver::load().unwrap(); + // SAFETY: cuInit has no preconditions. + assert_eq!(unsafe { (driver.init)(0) }, 0); + let bits = address_space::virtual_address_bits(0); + println!("device 0 GPU virtual address bits: {bits:?}"); + if cfg!(target_os = "windows") { + assert!( + bits.is_some_and(|bits| (32..64).contains(&bits)), + "{bits:?}" + ); + } + } } diff --git a/helios/src/runtime_core/address_space.rs b/helios/src/runtime_core/address_space.rs new file mode 100644 index 000000000..9413c7a1f --- /dev/null +++ b/helios/src/runtime_core/address_space.rs @@ -0,0 +1,148 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 Flare community contributors + * SPDX-License-Identifier: Apache-2.0 + */ + +//! The GPU virtual address space that fixed-address reservations must fit. +//! +//! Under WDDM, `cuMemAddressReserve` with a fixed address outside the adapter's +//! GPU virtual address space does not return. WDDM reports the address width +//! through `D3DKMTQueryAdapterInfo` (`KMTQAITYPE_QUERY_GPUMMU_CAPS`) for the +//! adapter whose LUID CUDA reports for the device, so fixed reservations are +//! checked against it before they are requested. Where the width is unknown +//! (Linux, or a failed query), no check applies. + +use std::ffi::c_int; + +/// GPU virtual address width of a CUDA device's WDDM adapter, in bits. +/// +/// Returns `None` when the width is unavailable. The CUDA driver must be +/// initialized. +#[cfg(windows)] +pub fn virtual_address_bits(device: c_int) -> Option { + use std::ffi::{c_char, c_uint, c_void}; + + #[repr(C)] + struct Luid { + low: u32, + high: i32, + } + #[repr(C)] + struct OpenAdapterFromLuid { + luid: Luid, + adapter: u32, + } + #[repr(C)] + struct QueryAdapterInfo { + adapter: u32, + kind: c_int, + data: *mut c_void, + size: c_uint, + } + // D3DKMT_QUERY_GPUMMU_CAPS: the physical adapter index, then + // D3DKMT_GPUMMU_CAPS { Flags, VirtualAddressBitCount }. + #[repr(C)] + #[derive(Default)] + struct GpuMmuCaps { + physical_adapter_index: u32, + flags: u32, + virtual_address_bits: u32, + } + #[repr(C)] + struct CloseAdapter { + adapter: u32, + } + const KMTQAITYPE_QUERY_GPUMMU_CAPS: c_int = 34; + + type GetLuid = unsafe extern "C" fn(*mut c_char, *mut c_uint, c_int) -> c_int; + type Open = unsafe extern "system" fn(*mut OpenAdapterFromLuid) -> i32; + type Query = unsafe extern "system" fn(*const QueryAdapterInfo) -> i32; + type Close = unsafe extern "system" fn(*const CloseAdapter) -> i32; + + // SAFETY: the signatures match cuDeviceGetLuid and the D3DKMT thunks, the + // structures match d3dkmthk.h, and every pointer outlives its call. + unsafe { + let cuda = crate::os::cuda_library().ok()?; + let get_luid = *cuda.get::(b"cuDeviceGetLuid\0").ok()?; + let mut luid = [0u8; 8]; + let mut node_mask: c_uint = 0; + if get_luid(luid.as_mut_ptr().cast(), &mut node_mask, device) != 0 { + return None; + } + let gdi = libloading::Library::new("gdi32.dll").ok()?; + let open = *gdi.get::(b"D3DKMTOpenAdapterFromLuid\0").ok()?; + let query = *gdi.get::(b"D3DKMTQueryAdapterInfo\0").ok()?; + let close = *gdi.get::(b"D3DKMTCloseAdapter\0").ok()?; + let mut adapter = OpenAdapterFromLuid { + luid: Luid { + low: u32::from_le_bytes(luid[..4].try_into().unwrap()), + high: i32::from_le_bytes(luid[4..].try_into().unwrap()), + }, + adapter: 0, + }; + if open(&mut adapter) != 0 { + return None; + } + let mut caps = GpuMmuCaps::default(); + let info = QueryAdapterInfo { + adapter: adapter.adapter, + kind: KMTQAITYPE_QUERY_GPUMMU_CAPS, + data: (&mut caps as *mut GpuMmuCaps).cast(), + size: std::mem::size_of::() as c_uint, + }; + let status = query(&info); + close(&CloseAdapter { + adapter: adapter.adapter, + }); + (status == 0 && (1..64).contains(&caps.virtual_address_bits)) + .then_some(caps.virtual_address_bits) + } +} + +/// GPU virtual address width of a CUDA device; unknown outside WDDM. +#[cfg(not(windows))] +pub fn virtual_address_bits(_device: c_int) -> Option { + None +} + +/// Rejects a fixed reservation of `[address, address + nbytes)` that does not +/// fit a GPU virtual address space of `bits` bits. `what` names the +/// reservation in the error. +pub fn check_fits(what: &str, address: u64, nbytes: u64, bits: Option) -> Result<(), String> { + let Some(bits) = bits else { + return Ok(()); + }; + let limit = 1u64 << bits; + match address.checked_add(nbytes) { + Some(end) if end <= limit => Ok(()), + _ => Err(format!( + "{what} {address:#x}+{nbytes:#x} exceeds the GPU's {bits}-bit virtual address space \ + (ends at {limit:#x}); CUDA would not return from reserving it" + )), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reservations_fit_or_name_the_limit() { + assert_eq!( + check_fits("window", 0x40_0000_0000, 1 << 36, Some(40)), + Ok(()) + ); + assert_eq!( + check_fits("window", (1 << 40) - 4096, 4096, Some(40)), + Ok(()) + ); + let error = check_fits("device window", 0x400_0000_0000, 1 << 40, Some(40)).unwrap_err(); + assert!( + error.contains("device window 0x40000000000+0x10000000000"), + "{error}" + ); + assert!(error.contains("40-bit"), "{error}"); + assert!(check_fits("window", u64::MAX, 2, Some(48)).is_err()); + assert_eq!(check_fits("window", u64::MAX - 1, 1, None), Ok(())); + } +} diff --git a/helios/src/runtime_core/host.rs b/helios/src/runtime_core/host.rs index a69c4e725..50f8514b4 100644 --- a/helios/src/runtime_core/host.rs +++ b/helios/src/runtime_core/host.rs @@ -108,7 +108,10 @@ impl super::NativeResources { flags: 3, }, ]; + let bits = super::address_space::virtual_address_bits(self.device); for (address, bytes) in ranges { + super::address_space::check_fits("host reservation", address, bytes as u64, bits) + .map_err(|error| invalid(format!("{error}; re-export the core for this GPU")))?; let mut pointer = 0; driver.check( "cuMemAddressReserve(host)", diff --git a/helios/src/runtime_core/mod.rs b/helios/src/runtime_core/mod.rs index e10bf651a..ff66338b2 100644 --- a/helios/src/runtime_core/mod.rs +++ b/helios/src/runtime_core/mod.rs @@ -12,6 +12,7 @@ mod cache_memory; mod cooperative_tests; mod describe; pub use describe::InspectionOptions; +pub mod address_space; mod device_memory; pub mod driver; mod engram; @@ -426,7 +427,15 @@ impl NativeResources { let driver = &self.driver; unsafe { driver.check("cuCtxSetCurrent", (driver.context_set)(self.context))?; + let bits = address_space::virtual_address_bits(self.device); for reservation in &core.reservations { + address_space::check_fits( + "core reservation", + reservation.address, + reservation.nbytes as u64, + bits, + ) + .map_err(|error| invalid(format!("{error}; re-export the core for this GPU")))?; let mut address = 0; driver.check( "cuMemAddressReserve", From 20e0bfff5bc7b5753accabc7f2c716d95492b499 Mon Sep 17 00:00:00 2001 From: Garret Buell Date: Sat, 14 Nov 2026 10:16:00 -0800 Subject: [PATCH 2/3] Accept an explicit fixed device window in CoreStorage Heliopause places each rank's fixed device window at a compile-time base: 4 TiB on Windows, 8 TiB on Linux, 1 TiB per rank. A caller whose GPU address space ends below that base cannot export, and with the preceding address-width check it now fails with an explicit error instead of hanging. The only remedies were to patch the constants in heliopause/src/allocator.rs and ignition/preparation/core_storage.py, or to add an environment override, which docs/design-review.md principle 10 prohibits. An explicit, typed argument lets a caller that drives CoreStorage and export_capture as a library place the window where the device can reserve it. CoreStorage gains a keyword argument, device_window=(base, extent). Rank r's window is then base + r * extent, extent bytes long; omitted, the defaults (DEVICE_BASE, RESERVATION_BYTES) apply as before. The base must lie at or above EXTERNAL_FLOOR and the extent must be nonzero, checked before CUDA is touched. Heliopause adds flare_core_initialize_window(rank, world, device, base, extent), and flare_core_initialize now calls it with the platform defaults. It rejects empty or overflowing windows, windows that are not aligned to the allocation granularity (the extent to twice it, since its halves serve the pool and persistent storage), and windows that overlap the host ranges. With the default window the overlap condition is the same as before. Host ranges keep their 1 TiB per rank stride, now named HOST_RESERVATION_BYTES in CoreStorage, and host bounds no longer depend on the device extent. docs/windows.md documents the argument. Result: on a GPU whose address space cannot hold the default window, export works with a window the caller chooses. Recipes and callers that do not pass device_window see no change. Evidence, on Windows 11 build 26200 with an RTX 3090 (SM86, not a supported GPU) and NVIDIA driver 621.01, on a tree that also contains the device identity change that follows and #293/#294: - CoreStorage(device_window=(0x4000000000, 0x1000000000)) initializes. Windows below EXTERNAL_FLOOR and empty windows raise ValueError. - A core export with that window captured 13 CUDA graphs (15.5 GiB mapped), and a separate process loaded the core through Helios and replayed all 13 bit-identically to the export. - heliopause's library suite passes, including explicit_device_windows_are_validated, except sync_parent_normalizes_a_relative_basename, which fails with "Access is denied" with and without this change. - tests/preparation/test_core_storage.py passes on Windows (8 tests, including the two device-window cases); its Linux layout test was skipped. Limits: the caller chooses a window that WDDM's own per-process placements leave free. One of four loads of that core failed with an address collision at the window base; the other three succeeded. No supported GPU or Linux system was tested. Design-Signed-Off-By: Claude Opus 5.5 (Claude Code); design-review=ed22 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Garret Buell --- docs/windows.md | 7 +- heliopause/src/allocator.rs | 111 ++++++++++++++++++++----- ignition/preparation/core_storage.py | 24 +++++- tests/preparation/test_core_storage.py | 11 ++- 4 files changed, 124 insertions(+), 29 deletions(-) diff --git a/docs/windows.md b/docs/windows.md index 25e362698..ad6ff108c 100644 --- a/docs/windows.md +++ b/docs/windows.md @@ -220,7 +220,12 @@ Ignition places rank-zero host storage at 12 TiB on Windows and on Linux when all device rank ranges fit below it (up to four Linux ranks). Larger Linux layouts use 32 TiB so their host and device ranges are disjoint, including sixteen-rank preparation. Heliopause selects the base and reports each rank's -host range to Ignition before allocation. +host range to Ignition before allocation. Each rank's device window is 1 TiB, +starting at 4 TiB on Windows and 8 TiB on Linux. A caller that constructs +`CoreStorage(device_window=(base, extent))` places rank `r`'s window at +`base + r * extent` instead; the base must lie at or above `EXTERNAL_FLOOR` +(256 GiB), and Heliopause rejects windows that are not aligned to the +allocation granularity or that overlap the host ranges. Linux and Windows share the core format and the mailbox release/acquire protocol. A core loads on Windows only when its GPU architecture matches, its recorded virtual addresses are available, and its CUDA operations are supported. diff --git a/heliopause/src/allocator.rs b/heliopause/src/allocator.rs index 84efe412d..a887ee2b1 100644 --- a/heliopause/src/allocator.rs +++ b/heliopause/src/allocator.rs @@ -31,8 +31,8 @@ const EXTENT: usize = 1 << 40; // Keep small Linux exports within the Windows WDDM address range as well. const HOST_BASE: u64 = 0xc0000000000; -fn host_base(device_base: u64, world: u32) -> u64 { - if device_base + u64::from(world) * EXTENT as u64 <= HOST_BASE { +fn host_base(device_base: u64, world: u32, extent: u64) -> u64 { + if device_base + u64::from(world) * extent <= HOST_BASE { HOST_BASE } else { 0x200000000000 @@ -258,8 +258,50 @@ fn failure(error: impl ToString) { .get_or_insert_with(|| CString::new(error.to_string().replace('\0', " ")).unwrap()); } +/// The host base for `world` device windows of `extent` bytes from `base`, +/// rejecting empty or overflowing windows and windows that overlap the host ranges. +fn window_host_base(base: u64, extent: u64, world: u32) -> Result { + let span = u64::from(world) + .checked_mul(extent) + .filter(|span| base != 0 && extent != 0 && base.checked_add(*span).is_some()) + .filter(|_| usize::try_from(extent).is_ok()) + .ok_or_else(|| { + invalid(format!( + "invalid native core device window {base:#x}+{extent:#x}" + )) + })?; + let host_base = if cfg!(target_os = "windows") { + HOST_BASE + } else { + host_base(base, world, extent) + }; + let host_end = host_base + u64::from(world) * EXTENT as u64; + if base < host_end && host_base < base + span { + return Err(invalid( + "core host reservations would overlap device reservations", + )); + } + Ok(host_base) +} + #[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) +} + +/// 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. +/// `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. +#[unsafe(no_mangle)] +extern "C" fn flare_core_initialize_window( + rank: u32, + world: u32, + device: i32, + base: u64, + extent: u64, +) -> i32 { let initialize = || -> Result<()> { let mut arena = ARENA.lock().unwrap_or_else(|e| e.into_inner()); if arena.is_some() { @@ -268,16 +310,8 @@ extern "C" fn flare_core_initialize(rank: u32, world: u32, device: i32) -> i32 { if world == 0 || rank >= world || device < 0 { return Err(invalid("invalid core rank or device")); } - let host_base = if cfg!(target_os = "windows") { - HOST_BASE - } else { - host_base(BASE, world) - }; - if u64::from(world) * EXTENT as u64 > BASE.abs_diff(host_base) { - return Err(invalid( - "core host reservations would overlap device reservations", - )); - } + let host_base = window_host_base(base, extent, world)?; + let extent_bytes = extent as usize; let driver = Driver::load()?; let (mut address, mut granularity, mut gpudirect) = (0, 0, 0); unsafe { @@ -289,26 +323,32 @@ extern "C" fn flare_core_initialize(rank: u32, world: u32, device: i32) -> i32 { "cuMemGetAllocationGranularity", (driver.granularity)(&mut granularity, &properties(device, gpudirect != 0), 0), )?; + let granule = granularity as u64; + if base % granule != 0 || extent % (2 * granule) != 0 { + return Err(invalid(format!( + "native core device window {base:#x}+{extent:#x} is not aligned to the {granule:#x}-byte allocation granularity" + ))); + } let bits = address_space::virtual_address_bits(device); for peer in 0..world { - let base = BASE + u64::from(peer) * EXTENT as u64; - address_space::check_fits("native core device window", base, EXTENT as u64, bits) + let start = base + u64::from(peer) * extent; + address_space::check_fits("native core device window", start, extent, bits) .map_err(invalid)?; } let mut reserved = Vec::new(); for peer in 0..world { - let base = BASE + u64::from(peer) * EXTENT as u64; - let status = (driver.reserve)(&mut address, EXTENT, 0, base, 0); - if status != 0 || address != base { + let start = base + u64::from(peer) * extent; + let status = (driver.reserve)(&mut address, extent_bytes, 0, start, 0); + if status != 0 || address != start { if status == 0 { - (driver.release_address)(address, EXTENT); + (driver.release_address)(address, extent_bytes); } for address in reserved { - (driver.release_address)(address, EXTENT); + (driver.release_address)(address, extent_bytes); } driver.check("cuMemAddressReserve", status)?; return Err(invalid(format!( - "native core device address range {base:#x}+{EXTENT:#x} is unavailable; CUDA returned {address:#x}" + "native core device address range {start:#x}+{extent:#x} is unavailable; CUDA returned {address:#x}" ))); } reserved.push(address); @@ -320,7 +360,7 @@ extern "C" fn flare_core_initialize(rank: u32, world: u32, device: i32) -> i32 { granularity, gpudirect: gpudirect != 0, host_base: host_base + u64::from(rank) * EXTENT as u64, - free: vec![(BASE + u64::from(rank) * EXTENT as u64, EXTENT / 2)], + free: vec![(base + u64::from(rank) * extent, extent_bytes / 2)], mappings: BTreeMap::new(), retained: RetainedBacking::default(), retained_mappings: RetainedMappingPool::default(), @@ -1251,7 +1291,7 @@ mod tests { fn small_linux_exports_keep_every_host_range_within_windows_addresses() { let device_base = 8 << 40; for world in 1..=4 { - let host = host_base(device_base, world); + let host = host_base(device_base, world, EXTENT as u64); assert_eq!(host, 12 << 40); assert!(device_base + u64::from(world) * EXTENT as u64 <= host); assert!(host + u64::from(world) * EXTENT as u64 <= 16 << 40); @@ -1262,12 +1302,37 @@ mod tests { fn larger_linux_exports_keep_host_ranges_clear_of_all_device_ranks() { let device_base = 8 << 40; for world in 5..=24 { - let host = host_base(device_base, world); + let host = host_base(device_base, world, EXTENT as u64); assert_eq!(host, 32 << 40); assert!(device_base + u64::from(world) * EXTENT as u64 <= host); } } + #[test] + fn explicit_device_windows_are_validated() { + assert_eq!( + window_host_base(BASE, EXTENT as u64, 1).unwrap(), + if cfg!(target_os = "windows") { + HOST_BASE + } else { + host_base(BASE, 1, EXTENT as u64) + } + ); + // A 64 GiB window at 256 GiB fits below the host ranges. + assert!(window_host_base(0x40_0000_0000, 64 << 30, 2).is_ok()); + assert!(window_host_base(0, 1 << 30, 1).is_err()); + assert!(window_host_base(1 << 40, 0, 1).is_err()); + assert!(window_host_base(u64::MAX - (1 << 30), 1 << 30, 2).is_err()); + // A window reaching the host range is rejected. Linux moves its host range to + // 32 TiB when device windows reach 12 TiB, so only one reaching 32 TiB overlaps it. + let host = if cfg!(target_os = "windows") { + HOST_BASE + } else { + 0x200000000000 + }; + assert!(window_host_base(host - (1 << 30), 2 << 30, 1).is_err()); + } + /// Prints device 0's WDDM GPU virtual address width; run with --ignored on a CUDA host. #[test] #[ignore = "needs a CUDA device"] diff --git a/ignition/preparation/core_storage.py b/ignition/preparation/core_storage.py index 677f15ac3..a175e73a1 100644 --- a/ignition/preparation/core_storage.py +++ b/ignition/preparation/core_storage.py @@ -36,23 +36,37 @@ class CoreStorage: # The native allocator selects a higher base when the device ranks need this range. HOST_BASE = 0xc0000000000 RESERVATION_BYTES = 1 << 40 + # Each rank's host range; independent of an explicit device window. + HOST_RESERVATION_BYTES = 1 << 40 # Keep library-owned device storage above the ranges occupied by Linux and WDDM contexts. EXTERNAL_FLOOR = 0x4000000000 # Where sealing below the floor starts; a context's own storage lies above it. LOW_SCAN_START = 1 << 32 - def __init__(self, *, rank=0, world=1, device=0, local_ranks=None): + def __init__(self, *, rank=0, world=1, device=0, local_ranks=None, device_window=None): + """``device_window=(base, extent)`` places rank ``r``'s fixed device window at + ``base + r * extent`` instead of the platform default ``(DEVICE_BASE, RESERVATION_BYTES)``. + A GPU whose virtual address space ends below the default window needs one. + ``base`` must lie at or above ``EXTERNAL_FLOOR``; the native allocator validates + alignment, the host ranges, and the GPU's address width.""" import torch self.rank, self.world, self.device = rank, world, device self.local_ranks = world if local_ranks is None else local_ranks if type(self.local_ranks) is not int or not 1 <= self.local_ranks <= world: raise ValueError("local preparation ranks must be positive and fit the rank group") + if device_window is not None: + base, extent = (int(value) for value in device_window) + if base < self.EXTERNAL_FLOOR or extent <= 0: + raise ValueError(f"device window {base:#x}+{extent:#x} must start at or above " + f"{self.EXTERNAL_FLOOR:#x} and be nonempty") + self.DEVICE_BASE, self.RESERVATION_BYTES = base, extent properties = torch.cuda.get_device_properties(device) self.integrated = properties.is_integrated self._persistent_total_bytes = properties.total_memory self._retention_scope = False self._retention_pool = None + window = (self.DEVICE_BASE, self.RESERVATION_BYTES) self.DEVICE_BASE += rank * self.RESERVATION_BYTES self.cuda = _Cuda() from flare_heliopause import flare_heliopause as native @@ -71,7 +85,9 @@ def __init__(self, *, rank=0, world=1, device=0, local_ranks=None): self.library = C.CDLL(native.__file__) self.library.flare_core_error.restype = C.c_char_p self.library.flare_core_snapshot.restype = C.c_void_p - if self.library.flare_core_initialize(rank, world, device): + 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): raise self.error or RuntimeError("cannot initialize native core allocator") layout = self._snapshot() self.granularity = layout["granularity"] @@ -330,11 +346,11 @@ def host_allocate(self, name, shape, dtype): # 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.RESERVATION_BYTES: + 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_cursor + region.extent > self.HOST_BASE + self.RESERVATION_BYTES: + if self._host_cursor + region.extent > self.HOST_BASE + self.HOST_RESERVATION_BYTES: region.close() raise MemoryError("native core host-address range exhausted") self._host_cursor += region.extent diff --git a/tests/preparation/test_core_storage.py b/tests/preparation/test_core_storage.py index 3641b1f95..ed77d9c61 100644 --- a/tests/preparation/test_core_storage.py +++ b/tests/preparation/test_core_storage.py @@ -21,6 +21,15 @@ def test_local_export_rank_count_must_fit_the_global_group(local_ranks): CoreStorage(world=3, local_ranks=local_ranks) +@pytest.mark.parametrize("window", [ + (CoreStorage.EXTERNAL_FLOOR - (1 << 30), 1 << 36), + (CoreStorage.EXTERNAL_FLOOR, 0), +]) +def test_explicit_device_window_starts_at_the_floor_and_is_nonempty(window): + with pytest.raises(ValueError, match="device window"): + CoreStorage(device_window=window) + + def test_cuda_access_descriptor_array_matches_driver_abi(): from ignition.preparation.core_storage import _Access, _Location @@ -68,4 +77,4 @@ def test_linux_device_ranges_avoid_mimalloc_arena_hints(): 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.RESERVATION_BYTES <= 16 << 40 + assert CoreStorage.HOST_BASE + CoreStorage.HOST_RESERVATION_BYTES <= 16 << 40 From 46b59cf49fee98c74b0f25d7c2d7de381e5b8d48 Mon Sep 17 00:00:00 2001 From: Garret Buell Date: Sat, 14 Nov 2026 10:16:20 -0800 Subject: [PATCH 3/3] Let capture exports record no device identity Heliopause's capture export names every core after the platform that the capture GPU's PCI id maps to in helios/src/core/naming.rs. It fails when the id maps to none ("NVML reports unsupported GPU PCI id"). A program that drives export_capture as a library on a development or test GPU outside that table therefore cannot export at all, unless it adds the GPU to the platform table, which would present it as a supported platform. Helios already defines cores without a device identity: they load, their cache entries use the unknown-device label (naming::unknown_device_candidate), and Flare's catalog and hub, which filter on naming::PLATFORMS, never list them as a supported platform. Export is the one path that cannot produce such a core. The capture request gains device_identity. "required", the default, keeps the current behavior: the PCI id must name a platform. "none" skips the lookup and records no platform. Export then names the core with the existing unknown-device scheme: - signed hardware_identity "unknown-device" (the schema requires a nonempty value); - deployment unknown-device-tp, unless the cluster supplies an export id; - cache entry unknown-device-tp-, from deployment_candidate(None, ...). No request field can name a platform, so a capture is either identified by its hardware or claims none. docs/core-format-design.md describes the field. Result: export_capture can export on a GPU outside the platform table, and the resulting core is marked as claiming no platform. Requests that omit the field behave as before. Evidence, on Windows 11 build 26200 with an RTX 3090 (SM86, PCI id outside the platform table) and NVIDIA driver 621.01, on a tree that also contains the two preceding changes and #293/#294: - device_identity_defaults_to_required_and_accepts_none: an omitted field and "required" parse as Required, "none" as None, other values are rejected. - A capture export with device_identity "none" and an unmodified platform table produced a core whose deployment is unknown-device-tp1, cache entry unknown-device-tp1-202611141806. A separate process loaded it through Helios's VerifiedCore and NativeResources and replayed all 13 graphs bit-identically to the export. - heliopause's library suite passes except sync_parent_normalizes_a_relative_basename, which fails with "Access is denied" with and without this change. Not tested: the "required" path was not re-run, though it is the unchanged call to current_platform. flare run, the catalog, and the hub were not exercised with an unknown-device core. Design-Signed-Off-By: Claude Opus 5.5 (Claude Code); design-review=ed22 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Garret Buell --- docs/core-format-design.md | 4 ++- heliopause/src/export/capture.rs | 11 +++++--- heliopause/src/export/core.rs | 24 +++++++++++------- heliopause/src/export/mod.rs | 43 ++++++++++++++++++++++++++++++++ 4 files changed, 68 insertions(+), 14 deletions(-) diff --git a/docs/core-format-design.md b/docs/core-format-design.md index 5fa95e6c6..98192f624 100644 --- a/docs/core-format-design.md +++ b/docs/core-format-design.md @@ -107,7 +107,9 @@ Device identity comes from the target hardware, not from an SM-version-to-name guess. Numeric SM architecture requirements are recorded in compatibility metadata; loaders validate that metadata independently of descriptive names. Payload exports record the captured device name in the signed core's -`hardware_identity`. Cluster deployment IDs may be arbitrary identifiers. +`hardware_identity`; export fails on a device whose PCI id names no platform. +A capture request with `device_identity: "none"` records no device name +instead, so the core is labeled `unknown-device` and claims no platform. Cluster deployment IDs may be arbitrary identifiers. Cores without a recorded device name are usable; when their authenticated metadata cannot identify the device, acquisition uses an `unknown-device-tp-` cache label. The downloader never substitutes diff --git a/heliopause/src/export/capture.rs b/heliopause/src/export/capture.rs index bf6761133..b21a1e815 100644 --- a/heliopause/src/export/capture.rs +++ b/heliopause/src/export/capture.rs @@ -17,9 +17,9 @@ use libloading::Library; use prost::Message; use super::{ - Allocation, Argument, CaptureRequest, ExportResult, FilePart, FileSource, Kernel, RankOutput, - Relocation, WeightPayloadGroup, WeightPayloadSourceSpan, WeightPayloadSources, cubin, invalid, - weight_payload, + Allocation, Argument, CaptureRequest, DeviceIdentity, ExportResult, FilePart, FileSource, + Kernel, RankOutput, Relocation, WeightPayloadGroup, WeightPayloadSourceSpan, + WeightPayloadSources, cubin, invalid, weight_payload, reachability::{Reachability, merge_ranges, subtract_ranges}, recorder::Recorder, wire, @@ -3376,7 +3376,10 @@ pub(crate) fn capture_rank( }, )?; } - output.hardware = current_platform(&cuda)?; + output.hardware = match request.device_identity { + DeviceIdentity::Required => current_platform(&cuda)?, + DeviceIdentity::None => None, + }; drop(store); let granule = request.granularity.max(1 << 30); let reservations = if request.reservations.is_empty() { diff --git a/heliopause/src/export/core.rs b/heliopause/src/export/core.rs index 25d6ebdca..8014c546a 100644 --- a/heliopause/src/export/core.rs +++ b/heliopause/src/export/core.rs @@ -502,6 +502,11 @@ pub(crate) fn combine( } use pyo3::{exceptions::PyValueError, prelude::*, types::PyBytes}; + +/// Signed hardware identity and deployment label of a core exported without a +/// device identity; it names no platform. +const UNKNOWN_DEVICE: &str = "unknown-device"; + fn py_error(error: impl std::fmt::Display) -> PyErr { PyValueError::new_err(error.to_string()) } @@ -716,17 +721,18 @@ pub(crate) fn publish_payload( let (index, payload) = combine(ranks, peer_memory, cluster.clone())?; let rank_count = u32::try_from(index.ranks.len()).map_err(|_| invalid("too many ranks"))?; let architecture = index.ranks[0].architecture.clone(); - let platform = ranks - .iter() - .find_map(|rank| rank.hardware.clone()) - .ok_or_else(|| { - invalid("export naming requires the capture device identity") - })?; + // Capture records a platform unless the request asked for no device + // identity (`device_identity: "none"`). Such a core claims no platform: + // its signed hardware identity and deployment use the unknown-device label. + let platform = ranks.iter().find_map(|rank| rank.hardware.clone()); + let hardware_identity = platform + .clone() + .unwrap_or_else(|| UNKNOWN_DEVICE.to_string()); let deployment_id = cluster .as_ref() .map(|c| c.export_id.clone()) .filter(|id| !id.is_empty()) - .unwrap_or_else(|| format!("{platform}-tp{rank_count}")); + .unwrap_or_else(|| format!("{hardware_identity}-tp{rank_count}")); let mut core_payloads = Vec::new(); let mut assets = Vec::new(); for (position, asset) in index.assets.iter().enumerate() { @@ -778,7 +784,7 @@ pub(crate) fn publish_payload( .map(|c| c.model_id.clone()) .filter(|id| !id.is_empty()) .unwrap_or_else(|| "model".into()), - hardware_identity: platform.clone(), + hardware_identity: hardware_identity.clone(), publisher: Some(pwire::PublisherMetadata { namespace: publisher.namespace.clone(), official_source: publisher.official_source.clone(), @@ -913,7 +919,7 @@ pub(crate) fn publish_payload( // error, never a lossy rewrite that could merge two models. let model = helios_core::core::cache::model_key(&request.core.model_identity)?; let candidate = helios_core::core::naming::deployment_candidate( - Some(&platform), + platform.as_deref(), &[rank_count], SystemTime::now(), ) diff --git a/heliopause/src/export/mod.rs b/heliopause/src/export/mod.rs index 303a3eeba..a65f98be3 100644 --- a/heliopause/src/export/mod.rs +++ b/heliopause/src/export/mod.rs @@ -138,6 +138,19 @@ pub(crate) struct ExportOptions { pub reuse_weights: Option, } +/// Whether a capture export records the device's platform identity. +#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub(crate) enum DeviceIdentity { + /// Record the platform named by the device's PCI id; a device outside the + /// platform table fails the export. + #[default] + Required, + /// Record no platform identity. The core's entry uses the `unknown-device` + /// label, and no platform is claimed for it. + None, +} + #[derive(Clone, Debug, Deserialize, Serialize)] pub(crate) struct CaptureRequest { pub path: PathBuf, @@ -183,6 +196,8 @@ pub(crate) struct CaptureRequest { pub zero_ranges: Vec<(u64, u64)>, #[serde(default)] pub device_address_floor: u64, + #[serde(default)] + pub device_identity: DeviceIdentity, pub execution: Option, pub server: Option, #[serde(default)] @@ -198,6 +213,34 @@ pub(crate) struct CaptureRequest { pub sources: bool, } +#[cfg(test)] +mod device_identity_tests { + use super::*; + + fn request(extra: &str) -> serde_json::Result { + serde_json::from_str(&format!( + r#"{{"path": "core", "context": 0, "graphs": [], "allocations": []{extra}}}"# + )) + } + + #[test] + fn device_identity_defaults_to_required_and_accepts_none() { + assert_eq!( + request("").unwrap().device_identity, + DeviceIdentity::Required + ); + assert_eq!( + request(r#", "device_identity": "required""#).unwrap().device_identity, + DeviceIdentity::Required + ); + assert_eq!( + request(r#", "device_identity": "none""#).unwrap().device_identity, + DeviceIdentity::None + ); + assert!(request(r#", "device_identity": "gb202""#).is_err()); + } +} + impl CaptureRequest { fn local_rank_count(&self) -> ExportResult { let count = self.local_ranks.unwrap_or(self.world_size);