Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion docs/core-format-design.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<N>-<UTC minute>` cache label. The downloader never substitutes
Expand Down
16 changes: 15 additions & 1 deletion docs/windows.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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.
Expand Down
131 changes: 110 additions & 21 deletions heliopause/src/allocator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};

Expand All @@ -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
Expand Down Expand Up @@ -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<u64> {
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() {
Expand All @@ -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 {
Expand All @@ -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);
Expand All @@ -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(),
Expand Down Expand Up @@ -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);
Expand All @@ -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:?}"
);
}
}
}
11 changes: 7 additions & 4 deletions heliopause/src/export/capture.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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() {
Expand Down
24 changes: 15 additions & 9 deletions heliopause/src/export/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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())
}
Expand Down Expand Up @@ -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() {
Expand Down Expand Up @@ -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(),
Expand Down Expand Up @@ -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(),
)
Expand Down
43 changes: 43 additions & 0 deletions heliopause/src/export/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,19 @@ pub(crate) struct ExportOptions {
pub reuse_weights: Option<weight_reuse::Source>,
}

/// 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,
Expand Down Expand Up @@ -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<serde_json::Value>,
pub server: Option<serde_json::Value>,
#[serde(default)]
Expand All @@ -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<CaptureRequest> {
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<usize> {
let count = self.local_ranks.unwrap_or(self.world_size);
Expand Down
Loading