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/docs/windows.md b/docs/windows.md index 539331b45..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. @@ -231,6 +236,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..a887ee2b1 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}; @@ -30,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 @@ -257,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() { @@ -267,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 { @@ -288,20 +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 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); @@ -313,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(), @@ -1244,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); @@ -1255,9 +1302,51 @@ 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"] + 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/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); 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", 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