From 5b700f575e4c204ed1eeec57fe21b908d94c1010 Mon Sep 17 00:00:00 2001 From: Luke Alonso Date: Mon, 30 Nov 2026 10:29:45 -0800 Subject: [PATCH] Fix externalized core signing, stream-0 weight race, export I/O, and multi-host tuning Why these changes are needed Preparation, export, and core-signing workflows contain defects across five areas: 1. Signed envelopes above 128 MiB fail in `combine` and `promote`: `export::publish` externalizes signed metadata bodies larger than 128 MiB into `EXTERNAL_BODY_PREFIX` tensors and clears inline `signed.body` and `rank.body` bytes. `helios/src/core/conversion.rs::inject_dependency_descriptors` decoded those empty inline byte slices directly and re-signed with `EnvelopeBuilder::sign` instead of `sign_envelope`, causing `combine` and `promote` to fail deterministically on externalized cores. 2. Legacy stream-0 zeroing races with non-blocking weight copies: `ignition/preparation/core_storage.py::DeviceRegion.grow` zeroed newly mapped 2 MiB virtual memory granules with `cuMemsetD8_v2` on legacy stream 0 without synchronizing against non-blocking PyTorch streams copying persistent weights (`ignition/preparation/persistent.py`), allowing zero-fills to overwrite live weights. 3. Cached export performs redundant D2H copies, hashing, ring setup, FD duplication, and rejects `--reuse-weights --no-mtp`: - `heliopause/src/export/capture.rs` downloaded all of `request.numeric` over PCIe in Pass 1 even when `cache_scan` was active and the cache pass downloads weights separately. - `heliopause/src/export/io.rs` created a fresh `IoUring` per 4 MiB chunk in single-job reads/writes, `transfer.rs` pre-hashed and stream-hashed content-addressed payload objects verified against `PayloadId` on install, `weight_payload.rs::merge_runs` dropped partial overlaps while `Claimed` sorted a vector per piece (O(V^2 log V)), and `core.rs::convert_prepared` scanned payload views linearly. - `binding.rs::NativeExportStage` retained duplicate file-descriptor leases across ranks (risking `EMFILE`) and held its directory mutex across filesystem checks under the Python GIL; `python.rs::NativeRankSupervisor` held an outer mutex without detaching the GIL during `finish_shutdown`/`abort`. - `weight_reuse.rs::map_groups` rejected reused speculative weight cores when `--no-mtp` omitted draft weight views. - `eos/src/ioring.rs::ReadRing::flush` returned on a partial-submit error before adding `submitted` operations to `self.in_flight`, allowing `Drop` to free DMA buffers while kernel reads remained active. 4. Multi-host preparation and AOT lowering fail on distinct roots, sharded autotune, and multi-storage dependencies: - `ignition/preparation/aot.py::ForwardCache._prepare_ranks` exchanged host-local absolute paths across nodes instead of cache-root-relative paths. - `ignition/preparation/tuning.py` skipped pre-tuning cache sharing and post-tuning `reconcile_selections` when multi-host tuning was sharded, leaving ranks with divergent kernel selections across retries (issue #631). - `ignition/preparation/compilation.py::_storage_regions` aligned spans before grouping and could extend past `storage.nbytes()`, while `_reads_across_mutations` cleared all pending storage dependencies on the first mutated storage instead of only the mutated subset. 5. ABI, device-selection, and 32-bit bound bugs in native preparation helpers: - `ignition/preparation/peer_storage.py::_Access` declared `flags` as `c_uint64` (16 bytes) instead of `c_uint32` (12 bytes matching `CUmemAccessDesc`). - `ignition/preparation/kv_codec.py` queried GPU SM architecture from device 0 instead of the rank's storage device, and `kv_codec_gpu.cu` used a 30-entry `gf2_pow` table (broken at >= 1 GiB half-lengths), 32-bit packet-plan offsets (wrapping at >= 4 GiB), and fixed `__shared__[64]` batch limits. - `heliopause/src/export/binding.rs` did not resolve optional `PersistentWorker.metrics` buffers, and `heliopause/src/allocator.rs` placed host windows at a fixed 12 TiB `HOST_BASE` without checking `virtual_address_bits(device)` for narrow WDDM GPU VA spaces. What changed - Externalized signed-envelope rewriting (`helios/src/core/{protection.rs,conversion.rs,conversion/edit.rs}`): - Before: `conversion/edit.rs` re-signed envelopes inline while `conversion.rs::inject_dependency_descriptors` decoded `signed.body` / `rank.body` directly and called `builder.sign(key)`. - After: Extracted `protection::sign_rewritten_envelope` and `sign_rewritten_envelope_with_limit` to refresh deployment `body_digest`s, read rank bodies through `read_rank_body(rank, body_store)`, and sign with `EnvelopeBuilder::sign_envelope(key)`. Both `conversion/edit.rs` and `conversion.rs::inject_dependency_descriptors` use this helper; `conversion.rs` reads bodies through `metadata.body_store()`, strips stale `EXTERNAL_BODY_PREFIX` tensors on container rewrite, writes `signed.external_bodies`, and drops `metadata` before `fs::rename`. - Stream-ordered granule zeroing, ctypes ABI, and GPU KV codec (`ignition/preparation/{core_storage.py,peer_storage.py,kv_codec.py,runtime_core.py,kv_codec_gpu.cu}`): - Before: `DeviceRegion.grow` called synchronous stream-0 `cuMemsetD8_v2`; `peer_storage._Access.flags` was `c_uint64`; `compile_gpu_codec_cubin` queried device 0; `kv_codec_gpu.cu` used `gf2_pow[30][32]`, `uint32_t` plan totals, and `__shared__[64]`. - After: `DeviceRegion.grow` calls `cuMemsetD8Async` on `torch.cuda.current_stream(device).cuda_stream` and adopts `host_extent` from `flare_core_snapshot`; `_Access.flags` is `c_uint32`; `runtime_core.py` passes `device=storage.device` to `compile_gpu_codec_cubin`; `kv_codec_gpu.cu` expands `gf2_pow` to `[64][32]`, widens plan accumulators to `uint64_t` and the `*low_base_ptr + lane_byte_offs[lane_id]` offset expression to `size_t`, and uses caller-supplied batch arrays instead of `__shared__[64]`. - Heliopause export pipeline, allocator, supervisor, and `eos::ReadRing` (`heliopause/src/{allocator.rs,processes.rs,python.rs}`, `heliopause/src/export/{capture.rs,io.rs,transfer.rs,weight_payload.rs,core.rs,binding.rs,weight_reuse.rs}`, `eos/src/ioring.rs`): - Before: Pass 1 copied `request.numeric` over PCIe even when `cache_scan` was active; `io.rs` created a new `IoUring` per single-job read/write; `transfer.rs` hashed cached payload files twice; `weight_payload.rs` missed partial overlaps in `merge_runs` and sorted `Claimed` on every insert; `convert_prepared` scanned views linearly; `NativeExportStage` stored duplicate leases and held locks under the GIL; `NativeRankSupervisor` serialized `abort` behind `finish_shutdown` without detaching the GIL; `map_groups` rejected prior initializers covering omitted views; `PersistentWorker` ignored `metrics`; `allocator.rs` used a fixed 12 TiB `HOST_BASE`; `ReadRing::flush` returned errors before accounting `submitted` into `in_flight`. - After: `capture.rs` skips `request.numeric` D2H in Pass 1 via `pass_one_skip_numeric` when `cache_scan` is true while still pointer-scanning non-numeric bytes and preserving `data_spans`; `io.rs` reuses one `DirectRing` per scan/write worker and uses `transfer_single_direct` (`pread`/`pwrite`) for single-job Linux I/O; `transfer.rs` skips redundant payload-object SHA-256 pre-hashing/stream-hashing (relying on `PayloadId` verification at install and per-frame HMAC-SHA256) and batches reads up to `super::io::BLOCK` (8 MiB, split into 4 MiB `BLOCK_BYTES` wire frames); `weight_payload.rs` reuses `reachability::merge_ranges` and switches `Claimed` to a `BTreeMap`, and `convert_prepared` uses a `HashMap`; `NativeExportStage` deduplicates leases by `PayloadId` and releases its lock/GIL around filesystem checks; `RankSupervisor` isolates its join handle behind its own `Mutex` and `NativeRankSupervisor` detaches the GIL; `weight_reuse.rs::map_groups` subtracts only exclusively omitted byte ranges (`(prior.views \ current.views) \ retained_by_allocation`) from prior initializers so tied/aliased retained views are preserved intact; `binding.rs` resolves and validates `stop_flag` and `metrics` through a shared `resolve_host_ref` helper; `allocator.rs` computes `window_host_layout` against `virtual_address_bits(device)` and exports `host_extent`; `eos::ReadRing::flush` updates `queued` and `in_flight` before `check(status)?` and returns `InvalidData` if `submitted > queued`. - Multi-host `ForwardCache`, sharded autotune reconciliation, and AOT lowering (`ignition/preparation/{aot.py,tuning.py,compilation.py}`): - Before: `ForwardCache._prepare_ranks` sent absolute paths across hosts; sharded multi-host tuning skipped `share_selections` and `reconcile_selections`; `_storage_regions` aligned before grouping without clamping to `storage.nbytes()`; `_reads_across_mutations` cleared all pending storages on the first mutated input. - After: `ForwardCache._prepare_ranks` exchanges cache-root-relative POSIX paths and `_share_artifacts(..., root=self.root)` resolves and bounds them to each host's cache root; `tuning.py` shares rank 0's cached selections before sharded tuning and runs `reconcile_selections` with `configure_tuning_shard(0, (0,))` afterward (restoring `shard_rank` in `finally`); `_storage_regions` groups raw overlaps before per-group clamped alignment and `_lower_storage` slices clamped multi-dtype `uint8` bases before `aten.view.dtype`; `_reads_across_mutations` removes only `pending & mutations[node]`. Claimed benefit and result - Verified fixes (exercised by unit and contract tests): externalized signed envelopes succeed through `inject_dependency_descriptors` and `promote`; `DeviceRegion.grow` passes the active CUDA stream to `cuMemsetD8Async`; `peer_storage._Access` matches the 12-byte `CUmemAccessDesc` ABI; `capture.rs` `cache_scan` skips numeric D2H in Pass 1 while preserving `data_spans`; `PersistentWorker.metrics`, omitted-draft and aliased-tied-view `--reuse-weights --no-mtp`, `Claimed`, `window_host_layout` VA-width checks, relative-path `ForwardCache` sharing, multi-host sharded autotune cache sharing and reconciliation (issue #631), per-group clamped `_storage_regions`, and multi-storage `_reads_across_mutations` behave as specified; `kv_codec_gpu.cu` compiles cleanly with `nvcc` and zero global/constant ELF symbols. - Expected performance and lifetime improvements (not benchmarked end-to-end on GPUs here): cached exports avoid the duplicate Pass-1 full-weight PCIe D2H copy, per-chunk `IoUring` creation, redundant payload SHA-256 passes, quadratic view/range scans, and cross-rank payload FD duplication; `eos::ReadRing` avoids freeing kernel-owned DMA buffers after partial submit errors. Supporting evidence and limitations All commands below ran on this rebased PR commit (parent `origin/main` `555db719`): - `eos` (`cargo test --locked --release`): 2 passed, 0 failed. - `heliopause` (`cargo test --locked --release --lib` with `PYO3_PYTHON` and Python `LIBDIR`): 221 passed, 0 failed, 6 ignored (CUDA), including `cache_scan_skips_numeric_ranges_in_pass_one_without_dropping_data_spans`, `map_groups_skips_omitted_draft_weights_and_clips_coalesced_initializers`, `map_groups_preserves_retained_initializer_when_omitted_view_aliases_it`, `claimed_tracks_disjoint_and_overlapping_pieces_in_order`, `persistent_worker_resolves_metrics_buffer_and_validates_alignment`, and `explicit_device_windows_are_validated`. - `helios` (`cargo test --locked --release --features runtime-core,server --lib -- core::`): 502 passed, 0 failed, 12 ignored (including `inject_dependency_descriptors_and_promote_handle_externalized_bodies`). - `flare-cli` (`cargo test --locked --release -- --test-threads=1`): 227 passed (201 unit, 26 integration), 0 failed, 3 ignored. - Python CPU tests with `CUDA_VISIBLE_DEVICES=""` against the paired public-`b12x` FlashInfer checkout: `test_persistent.py`, `test_tuning_shards.py`, and `test_peer_storage_groups.py` passed 33/33 with zero NVIDIA driver calls; `tests/preparation/{test_persistent,test_tuning_shards,test_forward_artifact_sharing,test_peer_storage_groups,test_core_storage,test_storage_lifetimes,test_core_boundary,test_persistent_worker}.py` passed 294 passed, 1 skipped (Windows-only), 0 failed; `tests/cli` passed 133/133 against `.venv`. - CUDA compilation (`FLARE_RUN_CUDA_TESTS=1 pytest tests/test_kv_codec.py`): 4 passed, 0 failed (`nvcc` compilation + cubin ELF symbol check). Material limitations and unrun checks: - Live VRAM-allocating GPU tests (`tests/preparation/test_virtual_storage_cuda.py`, live `kv_codec_gpu.cu` kernel execution, end-to-end GPU export/serving, and multi-host live export) could not run because all 16 host GPUs were occupied (~95-96 GiB / 97.9 GiB in use by an external workload). - Windows runtime execution for WDDM `HOST_BASE` placement and `eos::ReadRing` Windows `IoRing` paths was not exercised on Linux. Design-Signed-Off-By: Antigravity (Gemini); design-review=2e5b --- eos/src/ioring.rs | 17 +- heliopause/src/allocator.rs | 133 ++++- heliopause/src/export/binding.rs | 233 ++++++-- heliopause/src/export/capture.rs | 67 ++- heliopause/src/export/core.rs | 24 +- heliopause/src/export/io.rs | 142 ++++- heliopause/src/export/transfer.rs | 55 +- heliopause/src/export/weight_payload.rs | 84 +-- heliopause/src/export/weight_reuse.rs | 515 ++++++++++++++++-- heliopause/src/processes.rs | 12 +- heliopause/src/python.rs | 31 +- helios/src/core/conversion.rs | 188 +++++-- helios/src/core/conversion/edit.rs | 22 +- helios/src/core/protection.rs | 52 ++ ignition/preparation/aot.py | 56 +- ignition/preparation/compilation.py | 46 +- ignition/preparation/core_storage.py | 6 +- ignition/preparation/kv_codec.py | 3 +- ignition/preparation/kv_codec_gpu.cu | 83 ++- ignition/preparation/peer_storage.py | 2 +- ignition/preparation/runtime_core.py | 3 +- ignition/preparation/tuning.py | 29 +- .../test_forward_artifact_sharing.py | 36 ++ tests/preparation/test_peer_storage_groups.py | 5 + tests/preparation/test_persistent.py | 10 +- tests/preparation/test_storage_lifetimes.py | 47 +- tests/preparation/test_tuning_shards.py | 99 ++++ 27 files changed, 1648 insertions(+), 352 deletions(-) diff --git a/eos/src/ioring.rs b/eos/src/ioring.rs index 431800f5f..570d295b5 100644 --- a/eos/src/ioring.rs +++ b/eos/src/ioring.rs @@ -146,14 +146,23 @@ impl ReadRing { fn flush(&mut self) -> io::Result<()> { if self.queued != 0 { let mut submitted = 0; - // A submission failure leaves all entries queued. Drop abandons those - // entries instead of allowing them to execute after buffer reuse. let begin = Instant::now(); let status = unsafe { SubmitIoRing(self.handle, 0, 0, &mut submitted) }; self.timings.submit += begin.elapsed().as_nanos() as u64; + // Account for every entry the kernel accepted before propagating a + // submission error so Drop drains in-flight DMA before freeing buffers. + let reported = submitted as usize; + let overflowed = reported > self.queued; + let accepted = reported.min(self.queued); + self.queued -= accepted; + self.in_flight += accepted; check(status)?; - self.queued -= submitted as usize; - self.in_flight += submitted as usize; + if overflowed { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "Windows I/O ring reported more submissions than queued", + )); + } if self.queued != 0 { return Err(io::Error::other("incomplete Windows I/O ring submission")); } diff --git a/heliopause/src/allocator.rs b/heliopause/src/allocator.rs index ff34b96e9..fefe43f2b 100644 --- a/heliopause/src/allocator.rs +++ b/heliopause/src/allocator.rs @@ -192,6 +192,7 @@ struct Arena { granularity: usize, gpudirect: bool, host_base: u64, + host_extent: u64, free: Vec<(u64, usize)>, mappings: BTreeMap, retained: RetainedBacking, @@ -263,9 +264,21 @@ fn failure(error: impl ToString) { }); } -/// 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 { +/// Computes `(host_base, host_extent)` for `world` ranks given a device window +/// `[base, base + world * extent)` and an optional WDDM GPU virtual address width. +/// +/// Under WDDM, mapped host allocations also reserve fixed GPU virtual addresses, +/// so the host range must fit within `1 << bits`. When `HOST_BASE` exceeds a +/// narrow adapter's virtual address space, the host range is placed immediately +/// after the device windows inside `1 << bits` (aligned to `granule`) instead of +/// handing back an unreservable address that would hang `cuMemAddressReserve`. +fn window_host_layout( + base: u64, + extent: u64, + world: u32, + granule: u64, + bits: Option, +) -> Result<(u64, u64)> { let span = u64::from(world) .checked_mul(extent) .filter(|span| base != 0 && extent != 0 && base.checked_add(*span).is_some()) @@ -275,18 +288,72 @@ fn window_host_base(base: u64, extent: u64, world: u32) -> Result { "invalid native core device window {base:#x}+{extent:#x}" )) })?; - let host_base = if cfg!(target_os = "windows") { + let device_end = base + span; + 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 candidate_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", - )); + let default_extent = EXTENT as u64; + let default_span = u64::from(world).checked_mul(default_extent); + let default_end = default_span.and_then(|s| candidate_base.checked_add(s)); + let default_fits_bits = default_span.is_some_and(|s| { + address_space::check_fits("native core host window", candidate_base, s, bits).is_ok() + }); + if let Some(host_end) = default_end + && default_fits_bits + { + if base < host_end && candidate_base < device_end { + return Err(invalid( + "core host reservations would overlap device reservations", + )); + } + return Ok((candidate_base, default_extent)); + } + if let Some(bits) = bits { + let limit = 1u64 << bits; + let aligned_start = if granule > 1 { + device_end + .checked_add(granule - 1) + .map(|n| n & !(granule - 1)) + } else { + Some(device_end) + }; + if let Some(host_start) = aligned_start + && host_start < limit + { + let remaining = limit - host_start; + let raw_per_rank = (remaining / u64::from(world)).min(default_extent); + let per_rank = if granule > 1 { + raw_per_rank & !(granule - 1) + } else { + raw_per_rank + }; + if per_rank > 0 { + for peer in 0..world { + let start = host_start + u64::from(peer) * per_rank; + address_space::check_fits("native core host window", start, per_rank, Some(bits)) + .map_err(invalid)?; + } + return Ok((host_start, per_rank)); + } + } + address_space::check_fits( + "native core host window", + candidate_base, + u64::from(world).saturating_mul(default_extent), + Some(bits), + ) + .map_err(invalid)?; } - Ok(host_base) + Err(invalid( + "core host reservations would overlap or overflow the virtual address space", + )) } #[unsafe(no_mangle)] @@ -315,11 +382,10 @@ extern "C" fn flare_core_initialize_window( if world == 0 || rank >= world || device < 0 { return Err(invalid("invalid core rank or device")); } - 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, mut integrated) = (0, 0, 0, 0); - unsafe { + let (host_base, host_extent) = unsafe { driver.check( "cuDeviceGetAttribute(INTEGRATED)", (driver.device_attribute)(&mut integrated, 18, device), @@ -348,11 +414,8 @@ extern "C" fn flare_core_initialize_window( ))); } 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 (host_base, host_extent) = + window_host_layout(base, extent, world, granule, bits)?; let mut reserved = Vec::new(); for peer in 0..world { let start = base + u64::from(peer) * extent; @@ -371,13 +434,15 @@ extern "C" fn flare_core_initialize_window( } reserved.push(address); } - } + (host_base, host_extent) + }; *arena = Some(Arena { driver, device, granularity, gpudirect: gpudirect != 0 && integrated == 0, - host_base: host_base + u64::from(rank) * EXTENT as u64, + host_base: host_base + u64::from(rank) * host_extent, + host_extent, free: vec![(base + u64::from(rank) * extent, extent_bytes / 2)], mappings: BTreeMap::new(), retained: RetainedBacking::default(), @@ -650,7 +715,8 @@ extern "C" fn flare_core_snapshot() -> *mut c_char { return null_mut(); }; let value = serde_json::json!({ - "granularity": a.granularity, "mappings": a.mappings, "host_base": a.host_base, + "granularity": a.granularity, "mappings": a.mappings, + "host_base": a.host_base, "host_extent": a.host_extent, "retained_reference_bytes": a.retained.reference_bytes, "retained_handles": a.retained.handles.len(), "retained_reusable_handles": a.retained_mappings.len(), @@ -1151,6 +1217,7 @@ mod tests { granularity: 4096, gpudirect: false, host_base: 0, + host_extent: 0, free: Vec::new(), mappings: BTreeMap::new(), retained, @@ -1229,6 +1296,7 @@ mod tests { granularity: 4096, gpudirect: false, host_base: 0, + host_extent: 0, free: Vec::new(), mappings: BTreeMap::new(), retained, @@ -1272,6 +1340,7 @@ mod tests { granularity: 4096, gpudirect: false, host_base: 0, + host_extent: 0, free: Vec::new(), mappings: BTreeMap::from([(0x10000, 4096)]), retained: RetainedBacking::default(), @@ -1335,7 +1404,7 @@ mod tests { #[test] fn explicit_device_windows_are_validated() { assert_eq!( - window_host_base(BASE, EXTENT as u64, 1).unwrap(), + window_host_layout(BASE, EXTENT as u64, 1, 1, None).unwrap().0, if cfg!(target_os = "windows") { HOST_BASE } else { @@ -1343,10 +1412,10 @@ mod tests { } ); // 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()); + assert!(window_host_layout(0x40_0000_0000, 64 << 30, 2, 1, None).is_ok()); + assert!(window_host_layout(0, 1 << 30, 1, 1, None).is_err()); + assert!(window_host_layout(1 << 40, 0, 1, 1, None).is_err()); + assert!(window_host_layout(u64::MAX - (1 << 30), 1 << 30, 2, 1, None).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") { @@ -1354,7 +1423,19 @@ mod tests { } else { 0x200000000000 }; - assert!(window_host_base(host - (1 << 30), 2 << 30, 1).is_err()); + assert!(window_host_layout(host - (1 << 30), 2 << 30, 1, 1, None).is_err()); + + // Narrow WDDM address space (40-bit = 1 TiB): HOST_BASE (12 TiB) does not fit, + // so host ranges are placed after the device windows inside 1 << 40. + let (narrow_host, narrow_extent) = + window_host_layout(0x40_0000_0000, 64 << 30, 2, 2 << 20, Some(40)).unwrap(); + assert_eq!(narrow_host, 0x40_0000_0000 + (128 << 30)); + assert!(narrow_extent > 0); + assert!(narrow_host + 2 * narrow_extent <= (1u64 << 40)); + + // If device windows fill the entire WDDM address space, reject cleanly instead of + // returning an unreservable host base. + assert!(window_host_layout(0x80_0000_0000, 512 << 30, 1, 2 << 20, Some(40)).is_err()); } #[test] diff --git a/heliopause/src/export/binding.rs b/heliopause/src/export/binding.rs index 008275f72..e1338e1c5 100644 --- a/heliopause/src/export/binding.rs +++ b/heliopause/src/export/binding.rs @@ -352,38 +352,89 @@ pub(crate) fn execution( "persistent worker graph must be distinct from serving and tuning graphs", )); } + let resolve_host_ref = |field: &str, + align_label: &str, + ref_obj: &serde_json::Map, + nbytes: u64, + alignment: u64| + -> super::Result { + let alloc_name = ref_obj + .get("allocation") + .and_then(|v| v.as_str()) + .filter(|s| !s.is_empty()) + .ok_or_else(|| { + super::invalid(format!( + "persistent worker {field} requires an allocation name" + )) + })?; + let offset = match ref_obj.get("offset") { + None => 0, + Some(v) => v.as_u64().ok_or_else(|| { + super::invalid(format!( + "persistent worker {field} offset must be a nonnegative integer" + )) + })?, + }; + let (resolved_alloc, resolved_off) = + resolve_mapped_host(alloc_name, offset, nbytes)?; + if resolved_off % alignment != 0 { + return Err(super::invalid(format!( + "persistent worker {align_label} offset must be {alignment}-byte aligned" + ))); + } + Ok(serde_json::json!({ + "allocation": resolved_alloc, + "offset": resolved_off + })) + }; let stop_flag = worker_obj .get("stop_flag") .and_then(|v| v.as_object()) .ok_or_else(|| { super::invalid("persistent worker requires a stop_flag reference") })?; - let stop_name = stop_flag - .get("allocation") - .and_then(|v| v.as_str()) - .filter(|s| !s.is_empty()) - .ok_or_else(|| { - super::invalid("persistent worker stop_flag requires an allocation name") - })? - .to_owned(); - let stop_off = match stop_flag.get("offset") { - None => 0, + let resolved_stop = resolve_host_ref("stop_flag", "stop flag", stop_flag, 4, 4)?; + worker_obj.insert("stop_flag".into(), resolved_stop); + let metrics_val = worker_obj.get("metrics").filter(|v| !v.is_null()).cloned(); + let metrics_count = match worker_obj.get("metrics_count").filter(|v| !v.is_null()) { + None => 0u64, Some(v) => v.as_u64().ok_or_else(|| { super::invalid( - "persistent worker stop_flag offset must be a nonnegative integer", + "persistent worker metrics_count must be a nonnegative uint32", ) })?, }; - let (stop_alloc, stop_final_off) = resolve_mapped_host(&stop_name, stop_off, 4)?; - if stop_final_off % 4 != 0 { + if metrics_count > u32::MAX as u64 { return Err(super::invalid( - "persistent worker stop flag offset must be 4-byte aligned", + "persistent worker metrics_count must fit in uint32", )); } - worker_obj.insert( - "stop_flag".into(), - serde_json::json!({"allocation": stop_alloc, "offset": stop_final_off}), - ); + match (metrics_val, metrics_count) { + (None, 0) => { + worker_obj.remove("metrics"); + } + (Some(_), 0) => { + return Err(super::invalid( + "persistent worker metrics reference requires a positive metrics_count", + )); + } + (None, _) => { + return Err(super::invalid( + "persistent worker metrics_count requires a metrics reference", + )); + } + (Some(metrics_val), count) => { + let metrics_obj = metrics_val.as_object().ok_or_else(|| { + super::invalid("persistent worker metrics must be an object") + })?; + let metrics_bytes = count.checked_mul(8).ok_or_else(|| { + super::invalid("persistent worker metrics size overflow") + })?; + let resolved_metrics = + resolve_host_ref("metrics", "metrics", metrics_obj, metrics_bytes, 8)?; + worker_obj.insert("metrics".into(), resolved_metrics); + } + } resolved.push(serde_json::Value::Object(worker_obj)); } object.insert( @@ -634,7 +685,9 @@ fn append_planes( pub(crate) struct NativeExportStage { directory: std::sync::Mutex>, cache: Option, - leases: std::sync::Mutex>, + leases: std::sync::Mutex< + std::collections::BTreeMap, + >, #[pyo3(get)] path: String, } @@ -643,7 +696,9 @@ impl NativeExportStage { /// Retain payload object leases for the export's lifetime. /// /// A closed stage rejects retention instead of accepting leases it will drop - /// with its workspace, so the caller learns immediately. + /// with its workspace, so the caller learns immediately. Duplicate payload + /// identities across ranks share a single open lease to avoid exhausting + /// file descriptors. pub(crate) fn retain_payload_leases( &self, leases: crate::export::PayloadLeases, @@ -662,7 +717,9 @@ impl NativeExportStage { .leases .lock() .unwrap_or_else(|error| error.into_inner()); - held.extend(leases.0); + for object in leases.0 { + held.entry(object.id()).or_insert(object); + } drop(directory); Ok(()) } @@ -676,7 +733,7 @@ impl NativeExportStage { Some(tempfile::tempdir().unwrap()) }), cache, - leases: std::sync::Mutex::new(Vec::new()), + leases: std::sync::Mutex::new(std::collections::BTreeMap::new()), path: String::new(), } } @@ -710,45 +767,60 @@ impl NativeExportStage { path: directory.path().to_string_lossy().into_owned(), directory: std::sync::Mutex::new(Some(directory)), cache: cache.map(|path| path.to_path_buf()), - leases: std::sync::Mutex::new(Vec::new()), + leases: std::sync::Mutex::new(std::collections::BTreeMap::new()), }) } /// Reserve one rank's staged source path inside the live workspace. fn rank_path(&self, py: Python<'_>, rank: usize) -> PyResult { - let directory = self - .directory - .lock() - .unwrap_or_else(|e| e.into_inner()); - let directory = directory - .as_ref() - .ok_or_else(|| PyRuntimeError::new_err("export stage is closed"))?; + let root = { + let directory = self + .directory + .lock() + .unwrap_or_else(|e| e.into_inner()); + directory + .as_ref() + .ok_or_else(|| PyRuntimeError::new_err("export stage is closed"))? + .path() + .to_path_buf() + }; if !py - .detach(|| directory.path().try_exists()) + .detach(|| root.try_exists()) .map_err(|e| PyRuntimeError::new_err(e.to_string()))? { return Err(PyRuntimeError::new_err("export stage is closed")); } - Ok(directory - .path() + Ok(root .join(format!("rank-{rank}.json")) .to_string_lossy() .into_owned()) } - /// Lease every cache payload named by staged rank sources. + /// Lease every cache payload named by staged rank sources, returning the + /// number of newly acquired leases not already held by this stage. /// /// Python drops preparation leases when it closes the prepared model, so the - /// stage keeps its own leases until it is closed. + /// stage keeps its own deduplicated leases until it is closed. fn retain_sources(&self, py: Python<'_>, paths: Vec) -> PyResult { let cache = self .cache .clone() .ok_or_else(|| PyRuntimeError::new_err("export stage has no core cache"))?; + let already_held: std::collections::BTreeSet = self + .leases + .lock() + .unwrap_or_else(|error| error.into_inner()) + .keys() + .copied() + .collect(); let retained = py .detach(|| -> super::Result> { let root = crate::core::cache::Root::open(&cache)?; + let mut seen = already_held; let mut objects = Vec::new(); for path in paths { for id in super::core::source_payload_ids(&path)? { + if !seen.insert(id) { + continue; + } let object = root .payload(id)? .ok_or_else(|| super::invalid(format!("staged source names missing payload {id}")))?; @@ -1658,6 +1730,97 @@ mod asset_tests { assert!(super::serving_metadata(&mut bad, &base_server(invalid)).is_err()); } } + + #[test] + fn persistent_worker_resolves_metrics_buffer_and_validates_alignment() { + let allocations = vec![super::super::Allocation { + name: "host-0".into(), + address: 0xc00_0000_0000, + nbytes: 4096, + alignment: 4096, + initialize: "zero".into(), + relocations: vec![], + preserve_address: true, + memory: "mapped_host".into(), + snapshot_spans: None, + sizing: None, + }]; + let base_execution = |metrics: serde_json::Value, metrics_count: serde_json::Value| { + serde_json::json!({ + "buffers": [ + { + "name": "worker_stop", + "dtype": "uint32", + "shape": [1], + "strides": [1], + "nbytes": 4, + "reference": {"allocation": "host-0", "offset": 64} + }, + { + "name": "worker_metrics", + "dtype": "uint64", + "shape": [8], + "strides": [1], + "nbytes": 64, + "reference": {"allocation": "host-0", "offset": 128} + } + ], + "graphs": [], + "persistent_workers": [{ + "worker_sm_count": 2, + "graph": "worker_loop", + "stop_flag": {"allocation": "worker_stop", "offset": 0}, + "metrics": metrics, + "metrics_count": metrics_count + }] + }) + }; + let resolved = super::execution( + &base_execution( + serde_json::json!({"allocation": "worker_metrics", "offset": 16}), + serde_json::json!(4), + ), + &allocations, + ) + .unwrap(); + let worker = &resolved.persistent_workers[0]; + let stop = worker.stop_flag.as_ref().unwrap(); + assert_eq!(stop.allocation, "host-0"); + assert_eq!(stop.offset, 64); + let metrics = worker.metrics.as_ref().unwrap(); + assert_eq!(metrics.allocation, "host-0"); + assert_eq!(metrics.offset, 144); + assert_eq!(worker.metrics_count, 4); + + // Unaligned metrics offset, missing count, or count without metrics must fail. + assert!( + super::execution( + &base_execution( + serde_json::json!({"allocation": "worker_metrics", "offset": 4}), + serde_json::json!(2), + ), + &allocations, + ) + .is_err() + ); + assert!( + super::execution( + &base_execution( + serde_json::json!({"allocation": "worker_metrics", "offset": 0}), + serde_json::json!(0), + ), + &allocations, + ) + .is_err() + ); + assert!( + super::execution( + &base_execution(serde_json::Value::Null, serde_json::json!(2)), + &allocations, + ) + .is_err() + ); + } } #[pyclass(frozen, module = "flare_heliopause")] diff --git a/heliopause/src/export/capture.rs b/heliopause/src/export/capture.rs index 05b39bdce..c18dda889 100644 --- a/heliopause/src/export/capture.rs +++ b/heliopause/src/export/capture.rs @@ -1883,6 +1883,22 @@ fn with_allocation_commits( }) } +fn pass_one_skip_numeric( + request: &CaptureRequest, + allocations: &[Allocation], +) -> ExportResult<(bool, Vec<(u64, u64)>)> { + // Declared captures with a cache persist only semantic objects; the scan + // validates reachability outside numeric ranges and records sparse spans, + // while owner bytes are downloaded once through the live downloader later. + let cache_scan = request.weight_payload.is_some() && request.options.cache.is_some(); + let skip_numeric = if cache_scan { + merge_ranges(request.numeric.clone()) + } else { + super::weight_reuse::numeric_ranges(request, allocations)? + }; + Ok((cache_scan, skip_numeric)) +} + fn allocation_scan_ranges( allocation: &Allocation, reused_numeric: &[(u64, u64)], @@ -3414,11 +3430,7 @@ pub(crate) fn capture_rank( let storage_download_start = downloader.downloaded; let mut scanned = 0u64; let mut stored_bytes = 0u64; - // Declared captures with a cache persist only semantic objects; the scan - // validates reachability and records sparse spans, and owner bytes are read - // through the live downloader later. - let cache_scan = request.weight_payload.is_some() && request.options.cache.is_some(); - let reused_numeric = super::weight_reuse::numeric_ranges(request, &allocations)?; + let (cache_scan, skip_numeric) = pass_one_skip_numeric(request, &allocations)?; let budget = super::io::IoBudget::for_capture(local_ranks)?; let store = if cache_scan { None @@ -3454,7 +3466,7 @@ pub(crate) fn capture_rank( commits, request.options.no_weights, !cache_scan, - &reused_numeric, + &skip_numeric, &storage_phase, &mut scanned, )?; @@ -5310,4 +5322,47 @@ mod tests { assert_ne!(state_object.id(), expected_id); Ok(()) } + + #[test] + fn cache_scan_skips_numeric_ranges_in_pass_one_without_dropping_data_spans() -> ExportResult<()> + { + let allocation: Allocation = serde_json::from_value(serde_json::json!({ + "name": "weights", + "address": 0x10_0000u64, + "nbytes": 0x4000u64, + "memory": "device", + "initialize": "snapshot", + "preserve_address": true + }))?; + let mut request: CaptureRequest = serde_json::from_value(serde_json::json!({ + "path": "/tmp/out.flare", + "context": 0, + "graphs": [], + "allocations": [], + "numeric": [[0x10_1000u64, 0x10_3000u64], [0x10_2800u64, 0x10_3800u64]], + "execution": null, + "server": null, + "rebuild_weights": null, + "weight_payload": {"views": []}, + "core_data": null, + "options": {"cache": "/tmp/cache"} + }))?; + let (cache_scan, skip_numeric) = pass_one_skip_numeric(&request, &[allocation.clone()])?; + assert!(cache_scan); + assert_eq!(skip_numeric, vec![(0x10_1000, 0x10_3800)]); + + let (read, reused) = allocation_scan_ranges(&allocation, &skip_numeric); + assert_eq!(read, vec![(0x0, 0x1000), (0x3800, 0x800)]); + assert_eq!(reused, vec![(0x1000, 0x2800)]); + + // Without a cache, Pass 1 must scan the full allocation (no reuse_weights). + request.options.cache = None; + let (cache_scan, skip_numeric) = pass_one_skip_numeric(&request, &[allocation.clone()])?; + assert!(!cache_scan); + assert!(skip_numeric.is_empty()); + let (read, reused) = allocation_scan_ranges(&allocation, &skip_numeric); + assert_eq!(read, vec![(0, 0x4000)]); + assert!(reused.is_empty()); + Ok(()) + } } diff --git a/heliopause/src/export/core.rs b/heliopause/src/export/core.rs index dbca5579f..40b8d9e9d 100644 --- a/heliopause/src/export/core.rs +++ b/heliopause/src/export/core.rs @@ -2262,7 +2262,16 @@ pub(crate) fn convert_prepared( .enumerate() .map(|(i, a)| (a.name.as_str(), i as u64)) .collect(); - let mut views = Vec::new(); + let views_by_name: std::collections::HashMap<&str, &super::WeightPayloadView> = groups + .map(|groups| { + let mut map = std::collections::HashMap::with_capacity(groups.views.len()); + for view in &groups.views { + map.entry(view.name.as_str()).or_insert(view); + } + map + }) + .unwrap_or_default(); + let mut views = Vec::with_capacity(catalog.tensors.len()); for tensor in &catalog.tensors { let storage = tensor .storage @@ -2286,16 +2295,11 @@ pub(crate) fn convert_prepared( .and_then(|value| value.checked_mul(u64::from(tensor.element_bytes))) .ok_or_else(|| invalid("prepared weight extent overflow"))? }; + let recorded = views_by_name.get(tensor.name.as_str()).copied(); // Prefer the declared semantic group for this view; retained-coverage // inference exists only for older captures without declarations. - let mut group = groups - .and_then(|groups| { - groups - .views - .iter() - .find(|view| view.name == tensor.name) - .map(|view| view.group.clone()) - }) + let mut group = recorded + .map(|view| view.group.clone()) .unwrap_or_default(); let declared_group = !group.is_empty(); // Coverage remains the fallback that must not introduce equivalence: @@ -2326,8 +2330,6 @@ pub(crate) fn convert_prepared( _ => String::new(), }; } - let recorded = - groups.and_then(|groups| groups.views.iter().find(|view| view.name == tensor.name)); let (sources, packing, statistics_domain) = recorded.map(prepared_provenance).unwrap_or_default(); views.push(pwire::PreparedWeightView { diff --git a/heliopause/src/export/io.rs b/heliopause/src/export/io.rs index f39d25ff7..37106f128 100644 --- a/heliopause/src/export/io.rs +++ b/heliopause/src/export/io.rs @@ -230,6 +230,7 @@ impl IoBudget { std::thread::scope(|scope| { let (sender, receiver) = std::sync::mpsc::sync_channel(self.depth); let reader = scope.spawn(move || -> Result<()> { + let mut ring = DirectRing::new(); let mut offset = 0; while offset < source.length { let mut buffers = vec![self.buffer()?]; @@ -258,7 +259,7 @@ impl IoBudget { spans.push((lead, count)); offset += count as u64; } - transfer_batch(&file, &jobs, false)?; + ring.transfer(&file, &jobs, false)?; #[cfg(test)] self.scan_bytes.fetch_add( jobs.iter().map(|job| job.1 as u64).sum(), @@ -375,6 +376,7 @@ impl IoBudget { (filled_receiver, None) }; let writer = scope.spawn(move || -> Result<()> { + let mut ring = DirectRing::new(); while let Ok(first) = receiver.recv() { let mut blocks = vec![first]; while blocks.len() < 32 { @@ -412,7 +414,7 @@ impl IoBudget { } } if !jobs.is_empty() { - transfer_batch(&direct, &jobs, true)?; + ring.transfer(&direct, &jobs, true)?; } } Ok(()) @@ -643,14 +645,14 @@ impl Source { let lead = position as usize % ALIGNMENT; let count = output.len().min(scratch.len() - ALIGNMENT); let padded = (lead + count).next_multiple_of(ALIGNMENT); - transfer_batch( + transfer_single_job( &file, - &[( + ( scratch.as_mut_ptr(), padded, position - lead as u64, lead + count, - )], + ), false, )?; transferred += padded as u64; @@ -674,7 +676,7 @@ impl Source { if self.direct_compatible(offset, output) { let file = self.direct_file()?; let bulk = output.len() / ALIGNMENT * ALIGNMENT; - transfer_batch(&file, &[(output.as_mut_ptr(), bulk, position, bulk)], false)?; + transfer_single_job(&file, (output.as_mut_ptr(), bulk, position, bulk), false)?; read_exact_at(&self.file, &mut output[bulk..], position + bulk as u64) } else { #[repr(align(4096))] @@ -803,10 +805,132 @@ fn direct_reopen(file: &File, write: bool) -> Result { } #[cfg(target_os = "linux")] -fn transfer_batch(file: &File, jobs: &[(*mut u8, usize, u64, usize)], write: bool) -> Result<()> { - use io_uring::{IoUring, opcode, types}; +struct DirectRing { + ring: Option, + entries: u32, +} + +#[cfg(target_os = "linux")] +impl DirectRing { + fn new() -> Self { + Self { + ring: None, + entries: 0, + } + } + + fn transfer( + &mut self, + file: &File, + jobs: &[(*mut u8, usize, u64, usize)], + write: bool, + ) -> Result<()> { + if jobs.len() == 1 { + return transfer_single_direct(file, jobs[0], write); + } + let needed = (jobs.len().next_power_of_two() as u32).max(32); + if self.ring.is_none() || self.entries < needed { + self.ring = Some(io_uring::IoUring::new(needed)?); + self.entries = needed; + } + let ring = self.ring.as_mut().unwrap(); + let result = transfer_batch_on_ring(ring, file, jobs, write); + if result.is_err() { + // Drop any ring left in an error state so a subsequent call never + // reuses stale SQ/CQ state. + self.ring = None; + self.entries = 0; + } + result + } +} + +#[cfg(windows)] +struct DirectRing; + +#[cfg(windows)] +impl DirectRing { + fn new() -> Self { + Self + } + + fn transfer( + &mut self, + file: &File, + jobs: &[(*mut u8, usize, u64, usize)], + write: bool, + ) -> Result<()> { + transfer_batch(file, jobs, write) + } +} + +#[cfg(target_os = "linux")] +fn transfer_single_direct( + file: &File, + (pointer, length, offset, required): (*mut u8, usize, u64, usize), + write: bool, +) -> Result<()> { + use std::os::fd::AsRawFd; + let mut done = 0usize; + while done < required { + let rc = unsafe { + if write { + libc::pwrite( + file.as_raw_fd(), + pointer.add(done).cast(), + length - done, + (offset + done as u64) as libc::off_t, + ) + } else { + libc::pread( + file.as_raw_fd(), + pointer.add(done).cast(), + length - done, + (offset + done as u64) as libc::off_t, + ) + } + }; + if rc < 0 { + let error = std::io::Error::last_os_error(); + if error.kind() == std::io::ErrorKind::Interrupted { + continue; + } + return Err(error.into()); + } + if rc == 0 { + return Err("zero-length direct export write".into()); + } + done += rc as usize; + if done >= required && done <= length { + return Ok(()); + } + if done > length || done % ALIGNMENT != 0 { + return Err("unaligned partial direct export write".into()); + } + } + Ok(()) +} + +fn transfer_single_job(file: &File, job: (*mut u8, usize, u64, usize), write: bool) -> Result<()> { + #[cfg(target_os = "linux")] + { + transfer_single_direct(file, job, write) + } + #[cfg(not(target_os = "linux"))] + { + transfer_batch(file, &[job], write) + } +} + +#[cfg(target_os = "linux")] +fn transfer_batch_on_ring( + ring: &mut io_uring::IoUring, + file: &File, + jobs: &[(*mut u8, usize, u64, usize)], + write: bool, +) -> Result<()> { + use io_uring::{opcode, types}; use std::os::fd::AsRawFd; - let mut ring = IoUring::new(jobs.len().next_power_of_two() as u32)?; let mut done = vec![0usize; jobs.len()]; for (i, &(pointer, length, offset, _)) in jobs.iter().enumerate() { let entry = if write { diff --git a/heliopause/src/export/transfer.rs b/heliopause/src/export/transfer.rs index 19eeb59f7..781fa9d0e 100644 --- a/heliopause/src/export/transfer.rs +++ b/heliopause/src/export/transfer.rs @@ -22,7 +22,8 @@ use sha2::{Digest, Sha256}; use super::{RankOutput, Result, invalid}; -const BLOCK_BYTES: usize = 4 << 20; +// Wire frame size (4 MiB), half of the 8 MiB `super::io::BLOCK` disk read batch. +const BLOCK_BYTES: usize = super::io::BLOCK / 2; const METADATA_BYTES: usize = 256 << 20; const PROTOCOL: u32 = 2; const EXPORT_IDLE_TIMEOUT_MS: i32 = 2 * 60 * 60 * 1000; @@ -590,30 +591,23 @@ pub(crate) fn send_rank( "{} files, {hashed_bytes} bytes hashed", files.len() )); - // Cache-backed declared payloads: one leased object per declared group. + // Cache-backed declared payloads: one leased content-addressed object per + // declared group. The object's payload identity (`hex`) is already verified + // by the cache and re-verified on installation by `install_payload_object`, + // so re-hashing the container file here is redundant. let objects = cache_payload_sources(&output)?; for (path, hex, _length) in &objects { if files.contains_key(path) { continue; } let _transaction = FileTransaction::acquire(FileDirection::Send, 3)?; - let file = Arc::new(super::io::open_read(path)?); + let file = super::io::open_read(path)?; let before = super::io::Identity::of(&file)?; - let mut digest = Sha256::new(); - let source = super::io::Source::from_file(file.clone(), 0, file.metadata()?.len())?; - budget.scan(&source, |bytes| { - digest.update(bytes); - hashed_bytes += bytes.len() as u64; - Ok(()) - })?; - if super::io::Identity::of(&file)? != before { - return Err(invalid("cached payload object changed during metadata scan")); - } files.insert( path.clone(), Source { - size: file.metadata()?.len(), - sha256: format!("{:x}", digest.finalize()), + size: before.size, + sha256: hex.clone(), blob: false, payload: Some(hex.clone()), }, @@ -654,7 +648,7 @@ pub(crate) fn send_rank( let size = files[name].size; let mut offset = 0; while offset < size { - let length = (size - offset).min(BLOCK_BYTES as u64) as usize; + let batch = (size - offset).min(super::io::BLOCK as u64) as usize; { let _transaction = FileTransaction::acquire(FileDirection::Send, 3)?; let source = Arc::new(super::io::open_read(name)?); @@ -662,17 +656,22 @@ pub(crate) fn send_rank( return Err(invalid("rank export source changed before transfer")); } let pinned = super::io::Source::from_file(source.clone(), 0, size)?; - pinned.read_at(offset, &mut buffer.bytes_mut()[..length])?; + pinned.read_at(offset, &mut buffer.bytes_mut()[..batch])?; if super::io::Identity::of(&source)? != identities[name] { return Err(invalid("rank export source changed during transfer")); } } - channel.send( - json!({"kind":"export-data", "name":name, "offset":offset}), - &buffer.bytes()[..length], - )?; - offset += length as u64; - phase.advance_bytes(length as u64); + let mut sent = 0; + while sent < batch { + let length = (batch - sent).min(BLOCK_BYTES); + channel.send( + json!({"kind":"export-data", "name":name, "offset":offset + sent as u64}), + &buffer.bytes()[sent..sent + length], + )?; + sent += length; + phase.advance_bytes(length as u64); + } + offset += batch as u64; } } completion(channel, &names, &files, true) @@ -1010,7 +1009,7 @@ fn receive_rank( let (file, partial) = super::archive::temporary(target.parent().unwrap(), ".rank-blob-")?; let result = (|| -> Result<()> { - let mut digest = Sha256::new(); + let mut digest = info.payload.is_none().then(Sha256::new); budget.write(&file, 0, info.size, |position, bytes| { let mut filled = 0; while filled < bytes.len() { @@ -1026,14 +1025,18 @@ fn receive_rank( { return Err(invalid("rank export payload range differs")); } - digest.update(payload); + if let Some(digest) = digest.as_mut() { + digest.update(payload); + } filled += length; phase.advance_bytes(length as u64); aggregate.advance(length as u64); } Ok(()) })?; - if format!("{:x}", digest.finalize()) != info.sha256 { + if let Some(digest) = digest + && format!("{:x}", digest.finalize()) != info.sha256 + { return Err(invalid("rank payload digest mismatch")); } file.sync_all()?; diff --git a/heliopause/src/export/weight_payload.rs b/heliopause/src/export/weight_payload.rs index 23e7bd1f8..55bb0b498 100644 --- a/heliopause/src/export/weight_payload.rs +++ b/heliopause/src/export/weight_payload.rs @@ -558,8 +558,7 @@ fn occupied_runs(view: &WeightViewInput) -> Result> { let mut dimension = 0; loop { if dimension == outer.len() { - runs.sort_unstable(); - return Ok(merge_runs(runs)); + return Ok(super::reachability::merge_ranges(runs)); } indices[dimension] += 1; if indices[dimension] < outer[dimension].0 { @@ -571,18 +570,6 @@ fn occupied_runs(view: &WeightViewInput) -> Result> { } } -fn merge_runs(runs: Vec<(u64, u64)>) -> Vec<(u64, u64)> { - let mut merged: Vec<(u64, u64)> = Vec::with_capacity(runs.len()); - for (start, end) in runs { - match merged.last_mut() { - Some(last) if last.1 == start => last.1 = end, - Some(last) if last.1 >= end => {} - _ => merged.push((start, end)), - } - } - merged -} - struct AllocationIndex<'a> { allocations: &'a [WeightAllocationInput], } @@ -630,56 +617,66 @@ impl<'a> AllocationIndex<'a> { } /// Deterministic first-declaration ownership of shared bytes. +/// +/// Each allocation stores disjoint, non-adjacent claimed intervals as `start -> end`. struct Claimed { - ranges: BTreeMap>, + ranges: BTreeMap>, } impl Claimed { fn new(allocations: &[WeightAllocationInput]) -> Self { let ranges = allocations .iter() - .map(|allocation| (allocation.name.clone(), Vec::new())) + .map(|allocation| (allocation.name.clone(), BTreeMap::new())) .collect(); Self { ranges } } fn claim(&mut self, allocation: &str, start: u64, end: u64) -> Vec<(u64, u64)> { + if start >= end { + return Vec::new(); + } let claimed = self.ranges.entry(allocation.to_string()).or_default(); let mut pieces = Vec::new(); let mut cursor = start; - for (taken_start, taken_end) in claimed.iter().copied() { - if taken_end <= cursor || taken_start >= end { - continue; + let mut merged_start = start; + let mut merged_end = end; + let mut to_remove = Vec::new(); + + if let Some((&prev_start, &prev_end)) = claimed.range(..=start).next_back() { + if prev_end >= start { + merged_start = prev_start; + merged_end = merged_end.max(prev_end); + to_remove.push(prev_start); + cursor = cursor.max(prev_end); + } + } + for (&taken_start, &taken_end) in claimed.range(start..) { + if taken_start > end { + break; } if taken_start > cursor { pieces.push((cursor, taken_start.min(end))); } cursor = cursor.max(taken_end); - if cursor >= end { - break; - } + merged_end = merged_end.max(taken_end); + to_remove.push(taken_start); } if cursor < end { pieces.push((cursor, end)); } - for piece in &pieces { - claimed.push(*piece); + for key in to_remove { + claimed.remove(&key); } - claimed.sort_unstable(); - let mut merged: Vec<(u64, u64)> = Vec::with_capacity(claimed.len()); - for (start, end) in claimed.drain(..) { - match merged.last_mut() { - Some(last) if last.1 == start => last.1 = end, - Some(last) if last.1 >= end => {} - _ => merged.push((start, end)), - } - } - *claimed = merged; + claimed.insert(merged_start, merged_end); pieces } - fn ranges(&self, allocation: &str) -> &[(u64, u64)] { - self.ranges.get(allocation).map(Vec::as_slice).unwrap_or(&[]) + fn ranges(&self, allocation: &str) -> Vec<(u64, u64)> { + self.ranges + .get(allocation) + .map(|map| map.iter().map(|(&s, &e)| (s, e)).collect()) + .unwrap_or_default() } } @@ -1216,4 +1213,19 @@ mod tests { )) .is_err()); } + + #[test] + fn claimed_tracks_disjoint_and_overlapping_pieces_in_order() { + let mut claimed = Claimed::new(&[allocation("device-0", 0, 0x1000)]); + assert_eq!(claimed.claim("device-0", 10, 20), vec![(10, 20)]); + assert_eq!(claimed.claim("device-0", 30, 40), vec![(30, 40)]); + assert_eq!( + claimed.claim("device-0", 5, 45), + vec![(5, 10), (20, 30), (40, 45)] + ); + assert_eq!(claimed.ranges("device-0"), vec![(5, 45)]); + assert_eq!(claimed.claim("device-0", 45, 60), vec![(45, 60)]); + assert_eq!(claimed.ranges("device-0"), vec![(5, 60)]); + assert!(claimed.claim("device-0", 10, 50).is_empty()); + } } diff --git a/heliopause/src/export/weight_reuse.rs b/heliopause/src/export/weight_reuse.rs index aaf221963..c92400f08 100644 --- a/heliopause/src/export/weight_reuse.rs +++ b/heliopause/src/export/weight_reuse.rs @@ -569,6 +569,51 @@ fn map_groups( (group, allocations) }) .collect(); + let current_names: BTreeSet<&str> = current.views.iter().map(|view| view.name.as_str()).collect(); + // Views present in the cached core but absent from the current export (for + // example speculative draft weights under `--no-mtp`) may be omitted without + // relaxing coverage validation for retained views. Protect any bytes also + // covered by a retained view (for example tied `embed_tokens`/`lm_head`). + let mut retained_by_allocation = BTreeMap::<&str, Vec<(u64, u64)>>::new(); + let mut raw_omitted_by_allocation = BTreeMap::<&str, Vec<(u64, u64)>>::new(); + for old in &prior.views { + if old.nbytes == 0 { + continue; + } + let Some(old_allocation) = previous.allocations.get(old.allocation as usize) else { + return Err(invalid("cached weight allocation is absent")); + }; + let end = old + .offset + .checked_add(old.nbytes) + .ok_or_else(|| invalid("cached weight view extent overflow"))?; + let target = if current_names.contains(old.name.as_str()) { + &mut retained_by_allocation + } else { + &mut raw_omitted_by_allocation + }; + target + .entry(old_allocation.name.as_str()) + .or_default() + .push((old.offset, end)); + } + for ranges in retained_by_allocation.values_mut() { + *ranges = super::reachability::merge_ranges(std::mem::take(ranges)); + } + let mut omitted_by_allocation = BTreeMap::<&str, Vec<(u64, u64)>>::new(); + for (allocation, ranges) in raw_omitted_by_allocation { + let retained = retained_by_allocation + .get(allocation) + .map(Vec::as_slice) + .unwrap_or(&[]); + let mut exclusively_omitted = Vec::new(); + for (start, end) in super::reachability::merge_ranges(ranges) { + exclusively_omitted.extend(super::reachability::subtract_ranges(start, end, retained)); + } + if !exclusively_omitted.is_empty() { + omitted_by_allocation.insert(allocation, exclusively_omitted); + } + } let mut result = BTreeMap::::new(); for initializer in &previous.initializers { let Some(source) = initializer @@ -582,52 +627,79 @@ fn map_groups( .slice .as_ref() .ok_or_else(|| invalid("cached weight initializer has no slice"))?; + let old_start = initializer.destination_offset; + let old_end = old_start + .checked_add(slice.nbytes) + .ok_or_else(|| invalid("cached weight initializer extent overflow"))?; + let excluded = omitted_by_allocation + .get(initializer.allocation.as_str()) + .map(Vec::as_slice) + .unwrap_or(&[]); + let retained_pieces = super::reachability::subtract_ranges(old_start, old_end, excluded); + if retained_pieces.is_empty() { + continue; + } let Some((allocation, old_origin, origin)) = placements.get(&initializer.allocation) else { return Err(invalid( "cached weight allocation has no matching declared views", )); }; - let offset = i128::from(initializer.destination_offset) + i128::from(*origin) - - i128::from(*old_origin); - let offset = u64::try_from(offset) - .map_err(|_| invalid("reused weight offset is outside its allocation"))?; - let end = offset - .checked_add(slice.nbytes) - .ok_or_else(|| invalid("reused weight extent overflow"))?; let storage = if source.role == pwire::PayloadRole::TunedWeights as i32 { weight_payload::StorageClass::Tuned } else { weight_payload::StorageClass::Stable }; - let group = coverage.iter().find(|(group, allocations)| group.storage == storage && - allocations.get(allocation.as_str()).is_some_and(|ranges| - ranges.iter().any(|&(start, stop)| start <= offset && end <= stop))) - .map(|(group, _)| *group) - .ok_or_else(|| invalid(format!( - "rank {} cached {} weight initializer {}[{offset}..{end}] is not covered by one declared weight group; export with weights", - previous.rank, storage.as_str(), allocation, - )))?; - let resolved = result - .entry(group.name.clone()) - .or_insert_with(|| WeightPayloadGroup { - name: group.name.clone(), - storage: group.storage.as_str().to_string(), - nbytes: 0, - spans: Vec::new(), - payload_id: slice.payload_id.clone(), + for (piece_old_start, piece_old_end) in retained_pieces { + let offset = i128::from(piece_old_start) + i128::from(*origin) - i128::from(*old_origin); + let offset = u64::try_from(offset) + .map_err(|_| invalid("reused weight offset is outside its allocation"))?; + let nbytes = piece_old_end - piece_old_start; + let end = offset + .checked_add(nbytes) + .ok_or_else(|| invalid("reused weight extent overflow"))?; + let group = coverage + .iter() + .find(|(group, allocations)| { + group.storage == storage + && allocations.get(allocation.as_str()).is_some_and(|ranges| { + ranges.iter().any(|&(start, stop)| start <= offset && end <= stop) + }) + }) + .map(|(group, _)| *group) + .ok_or_else(|| { + invalid(format!( + "rank {} cached {} weight initializer {}[{offset}..{end}] is not covered by one declared weight group; export with weights", + previous.rank, + storage.as_str(), + allocation, + )) + })?; + let source_offset = slice + .offset + .checked_add(piece_old_start - old_start) + .ok_or_else(|| invalid("reused weight source offset overflow"))?; + let resolved = result + .entry(group.name.clone()) + .or_insert_with(|| WeightPayloadGroup { + name: group.name.clone(), + storage: group.storage.as_str().to_string(), + nbytes: 0, + spans: Vec::new(), + payload_id: slice.payload_id.clone(), + }); + if resolved.payload_id != slice.payload_id { + return Err(invalid( + "cached weight group uses multiple payload objects; export with weights", + )); + } + resolved.nbytes = payloads.length(&slice.payload_id)?; + resolved.spans.push(WeightPayloadSourceSpan { + allocation: allocation.clone(), + destination_offset: offset, + source_offset, + nbytes, }); - if resolved.payload_id != slice.payload_id { - return Err(invalid( - "cached weight group uses multiple payload objects; export with weights", - )); } - resolved.nbytes = payloads.length(&slice.payload_id)?; - resolved.spans.push(WeightPayloadSourceSpan { - allocation: allocation.clone(), - destination_offset: offset, - source_offset: slice.offset, - nbytes: slice.nbytes, - }); } Ok(result.into_values().collect()) } @@ -770,4 +842,379 @@ mod tests { ); } } + + #[test] + fn map_groups_skips_omitted_draft_weights_and_clips_coalesced_initializers() { + use super::super::{RankOutput, WeightPayloadSources, WeightPayloadView, weight_payload, wire}; + use helios_core::core::schema::{Catalog, wire as pwire}; + + let base_id = vec![0x11u8; 32]; + let draft_id = vec![0x22u8; 32]; + let mut payloads = Catalog::new(); + payloads + .insert_all(&[ + pwire::PayloadDescriptor { + id: base_id.clone(), + nbytes: 512, + }, + pwire::PayloadDescriptor { + id: draft_id.clone(), + nbytes: 256, + }, + ]) + .unwrap(); + + // Previous core had a shared arena holding base weights at [0..256) coalesced + // with draft weights at [256..512), plus a separate draft-only allocation. + let prior_catalog = pwire::PreparedWeightCatalog { + version: 1, + views: vec![ + pwire::PreparedWeightView { + name: "layers.0.w".into(), + group: "layer-000".into(), + dtype: "bfloat16".into(), + element_bytes: 2, + shape: vec![128], + stride: vec![1], + layout_type: String::new(), + allocation: 0, + offset: 0, + nbytes: 256, + packing: None, + sources: vec![], + padding: vec![], + statistics_domain: String::new(), + }, + pwire::PreparedWeightView { + name: "draft.0.w".into(), + group: "draft".into(), + dtype: "bfloat16".into(), + element_bytes: 2, + shape: vec![128], + stride: vec![1], + layout_type: String::new(), + allocation: 0, + offset: 256, + nbytes: 256, + packing: None, + sources: vec![], + padding: vec![], + statistics_domain: String::new(), + }, + pwire::PreparedWeightView { + name: "draft.1.w".into(), + group: "draft".into(), + dtype: "bfloat16".into(), + element_bytes: 2, + shape: vec![128], + stride: vec![1], + layout_type: String::new(), + allocation: 1, + offset: 0, + nbytes: 256, + packing: None, + sources: vec![], + padding: vec![], + statistics_domain: String::new(), + }, + ], + unavailable: vec![], + }; + let previous = pwire::RankBody { + rank: 0, + allocations: vec![ + pwire::Allocation { + name: "weights-0".into(), + nbytes: 512, + ..Default::default() + }, + pwire::Allocation { + name: "draft-only".into(), + nbytes: 256, + ..Default::default() + }, + ], + initializers: vec![ + // Coalesced across base [0..256) and dropped draft [256..512). + pwire::Initializer { + allocation: "weights-0".into(), + destination_offset: 0, + source: Some(pwire::PayloadUse { + slice: Some(pwire::PayloadSlice { + payload_id: base_id.clone(), + offset: 0, + nbytes: 512, + }), + role: pwire::PayloadRole::Weights as i32, + }), + }, + // Separate draft-only allocation absent from `--no-mtp` export. + pwire::Initializer { + allocation: "draft-only".into(), + destination_offset: 0, + source: Some(pwire::PayloadUse { + slice: Some(pwire::PayloadSlice { + payload_id: draft_id, + offset: 0, + nbytes: 256, + }), + role: pwire::PayloadRole::Weights as i32, + }), + }, + ], + prepared_weights: Some(prior_catalog), + ..Default::default() + }; + + // Target `--no-mtp` export declares only `layers.0.w` shifted by +64 bytes. + let mut output = RankOutput { + index: wire::ModelIndex::default(), + payload: vec![], + allocations: vec![], + module_globals: vec![], + external: vec![], + staging: None, + weight_payload: None, + hardware: None, + payload_leases: Default::default(), + }; + output.index.ranks.push(wire::BundleIndex { + allocations: vec![wire::Allocation { + name: "new-weights".into(), + nbytes: 512, + ..Default::default() + }], + rebuild_weights: Some(wire::RebuildWeights { + version: 1, + tensors: vec![wire::RebuildTensor { + name: "layers.0.w".into(), + dtype: "bfloat16".into(), + element_bytes: 2, + shape: vec![128], + stride: vec![1], + layout_type: String::new(), + storage: Some(wire::Reference { + allocation: "new-weights".into(), + offset: 64, + }), + }], + unavailable: vec![], + }), + ..Default::default() + }); + let catalog = weight_payload::WeightPayloadCatalog { + groups: vec![weight_payload::WeightGroupPayload { + name: "layer-000".into(), + storage: weight_payload::StorageClass::Stable, + nbytes: 256, + spans: vec![weight_payload::PayloadSpan { + payload_offset: 0, + allocation: "new-weights".into(), + destination_offset: 64, + nbytes: 256, + }], + }], + state: weight_payload::WeightGroupPayload { + name: "initial-state".into(), + storage: weight_payload::StorageClass::State, + nbytes: 0, + spans: vec![], + }, + aliases: vec![], + }; + let views = WeightPayloadSources { + views: vec![WeightPayloadView { + name: "layers.0.w".into(), + group: "layer-000".into(), + storage: "stable".into(), + sources: vec![], + packing: String::new(), + packing_parameters: None, + statistics_domain: String::new(), + }], + ..Default::default() + }; + + let groups = super::map_groups(&previous, &payloads, &output, &catalog, &views).unwrap(); + assert_eq!(groups.len(), 1); + assert_eq!(groups[0].name, "layer-000"); + assert_eq!(groups[0].payload_id, base_id); + assert_eq!(groups[0].spans.len(), 1); + assert_eq!(groups[0].spans[0].allocation, "new-weights"); + assert_eq!(groups[0].spans[0].destination_offset, 64); + assert_eq!(groups[0].spans[0].source_offset, 0); + assert_eq!(groups[0].spans[0].nbytes, 256); + } + + #[test] + fn map_groups_preserves_retained_initializer_when_omitted_view_aliases_it() { + use super::super::{ + RankOutput, WeightPayloadSources, WeightPayloadView, weight_payload, wire, + }; + use helios_core::core::schema::{Catalog, wire as pwire}; + + let embed_id = vec![0x33u8; 32]; + let mut payloads = Catalog::new(); + payloads + .insert_all(&[pwire::PayloadDescriptor { + id: embed_id.clone(), + nbytes: 512, + }]) + .unwrap(); + // Prior core has `embed_tokens` at [0, 256), a tied omitted draft view + // `mtp.embed_tokens` aliasing [0, 256), and a separate omitted draft + // projection `mtp.fc` at [256, 512) in the same coalesced initializer. + let prior_catalog = pwire::PreparedWeightCatalog { + version: 1, + views: vec![ + pwire::PreparedWeightView { + name: "embed_tokens".into(), + group: "embed".into(), + dtype: "bfloat16".into(), + element_bytes: 2, + shape: vec![128], + stride: vec![1], + layout_type: String::new(), + allocation: 0, + offset: 0, + nbytes: 256, + packing: None, + sources: vec![], + padding: vec![], + statistics_domain: String::new(), + }, + pwire::PreparedWeightView { + name: "mtp.embed_tokens".into(), + group: "embed".into(), + dtype: "bfloat16".into(), + element_bytes: 2, + shape: vec![128], + stride: vec![1], + layout_type: String::new(), + allocation: 0, + offset: 0, + nbytes: 256, + packing: None, + sources: vec![], + padding: vec![], + statistics_domain: String::new(), + }, + pwire::PreparedWeightView { + name: "mtp.fc".into(), + group: "draft".into(), + dtype: "bfloat16".into(), + element_bytes: 2, + shape: vec![128], + stride: vec![1], + layout_type: String::new(), + allocation: 0, + offset: 256, + nbytes: 256, + packing: None, + sources: vec![], + padding: vec![], + statistics_domain: String::new(), + }, + ], + ..Default::default() + }; + let previous = pwire::RankBody { + allocations: vec![pwire::Allocation { + name: "old-embed".into(), + nbytes: 512, + ..Default::default() + }], + initializers: vec![pwire::Initializer { + allocation: "old-embed".into(), + destination_offset: 0, + source: Some(pwire::PayloadUse { + slice: Some(pwire::PayloadSlice { + payload_id: embed_id.clone(), + offset: 0, + nbytes: 512, + }), + role: pwire::PayloadRole::Weights as i32, + }), + }], + prepared_weights: Some(prior_catalog), + ..Default::default() + }; + let mut output = RankOutput { + index: wire::ModelIndex::default(), + payload: vec![], + allocations: vec![], + module_globals: vec![], + external: vec![], + staging: None, + weight_payload: None, + hardware: None, + payload_leases: Default::default(), + }; + output.index.ranks.push(wire::BundleIndex { + allocations: vec![wire::Allocation { + name: "new-embed".into(), + nbytes: 256, + ..Default::default() + }], + rebuild_weights: Some(wire::RebuildWeights { + version: 1, + tensors: vec![wire::RebuildTensor { + name: "embed_tokens".into(), + dtype: "bfloat16".into(), + element_bytes: 2, + shape: vec![128], + stride: vec![1], + layout_type: String::new(), + storage: Some(wire::Reference { + allocation: "new-embed".into(), + offset: 0, + }), + }], + unavailable: vec![], + }), + ..Default::default() + }); + let catalog = weight_payload::WeightPayloadCatalog { + groups: vec![weight_payload::WeightGroupPayload { + name: "embed".into(), + storage: weight_payload::StorageClass::Stable, + nbytes: 256, + spans: vec![weight_payload::PayloadSpan { + payload_offset: 0, + allocation: "new-embed".into(), + destination_offset: 0, + nbytes: 256, + }], + }], + state: weight_payload::WeightGroupPayload { + name: "initial-state".into(), + storage: weight_payload::StorageClass::State, + nbytes: 0, + spans: vec![], + }, + aliases: vec![], + }; + let views = WeightPayloadSources { + views: vec![WeightPayloadView { + name: "embed_tokens".into(), + group: "embed".into(), + storage: "stable".into(), + sources: vec![], + packing: String::new(), + packing_parameters: None, + statistics_domain: String::new(), + }], + ..Default::default() + }; + + let groups = super::map_groups(&previous, &payloads, &output, &catalog, &views).unwrap(); + assert_eq!(groups.len(), 1); + assert_eq!(groups[0].name, "embed"); + assert_eq!(groups[0].payload_id, embed_id); + assert_eq!(groups[0].spans.len(), 1); + assert_eq!(groups[0].spans[0].allocation, "new-embed"); + assert_eq!(groups[0].spans[0].destination_offset, 0); + assert_eq!(groups[0].spans[0].source_offset, 0); + assert_eq!(groups[0].spans[0].nbytes, 256); + } } diff --git a/heliopause/src/processes.rs b/heliopause/src/processes.rs index 215de7ed8..95558dc87 100644 --- a/heliopause/src/processes.rs +++ b/heliopause/src/processes.rs @@ -92,7 +92,7 @@ struct Control { pub struct RankSupervisor { peers: Arc>, control: Arc>, - thread: Option>, + thread: Mutex>>, } fn exited(peer: &OwnedFd) -> io::Result { @@ -218,7 +218,7 @@ impl RankSupervisor { Ok(Self { peers, control, - thread: Some(thread), + thread: Mutex::new(Some(thread)), }) } @@ -237,7 +237,7 @@ impl RankSupervisor { Ok(()) } - pub fn finish_shutdown(&mut self) -> io::Result<()> { + pub fn finish_shutdown(&self) -> io::Result<()> { if self .control .lock() @@ -270,9 +270,9 @@ impl RankSupervisor { abort_group(&self.peers, reason) } - fn stop(&mut self) { + fn stop(&self) { self.control.lock().unwrap_or_else(|e| e.into_inner()).stop = true; - if let Some(thread) = self.thread.take() { + if let Some(thread) = self.thread.lock().unwrap_or_else(|e| e.into_inner()).take() { let _ = thread.join(); } } @@ -280,7 +280,7 @@ impl RankSupervisor { impl Drop for RankSupervisor { fn drop(&mut self) { - if self.thread.is_some() { + if self.thread.get_mut().unwrap_or_else(|e| e.into_inner()).is_some() { terminate(&self.peers); self.stop(); } diff --git a/heliopause/src/python.rs b/heliopause/src/python.rs index 4b6bff73c..0040cb562 100644 --- a/heliopause/src/python.rs +++ b/heliopause/src/python.rs @@ -565,7 +565,7 @@ fn serve_tensor_parallel_rank( #[cfg(target_os = "linux")] #[pyclass(name = "RankSupervisor", module = "flare_heliopause")] struct NativeRankSupervisor { - supervisor: Mutex, + supervisor: crate::processes::RankSupervisor, } #[cfg(target_os = "linux")] @@ -574,37 +574,24 @@ impl NativeRankSupervisor { #[new] fn new(pids: Vec) -> PyResult { Ok(Self { - supervisor: Mutex::new( - crate::processes::RankSupervisor::new(&pids) - .map_err(|e| PyValueError::new_err(e.to_string()))?, - ), + supervisor: crate::processes::RankSupervisor::new(&pids) + .map_err(|e| PyValueError::new_err(e.to_string()))?, }) } #[pyo3(signature = (timeout_ms=30000))] - fn begin_shutdown(&self, timeout_ms: u64) -> PyResult<()> { - self.supervisor - .lock() - .unwrap_or_else(|e| e.into_inner()) - .begin_shutdown(Duration::from_millis(timeout_ms)) + fn begin_shutdown(&self, py: Python<'_>, timeout_ms: u64) -> PyResult<()> { + py.detach(|| self.supervisor.begin_shutdown(Duration::from_millis(timeout_ms))) .map_err(|e| PyValueError::new_err(e.to_string())) } fn finish_shutdown(&self, py: Python<'_>) -> PyResult<()> { - py.detach(|| { - self.supervisor - .lock() - .unwrap_or_else(|e| e.into_inner()) - .finish_shutdown() - }) - .map_err(|e| PyRuntimeError::new_err(e.to_string())) + py.detach(|| self.supervisor.finish_shutdown()) + .map_err(|e| PyRuntimeError::new_err(e.to_string())) } - fn abort(&self, reason: &str) { - self.supervisor - .lock() - .unwrap_or_else(|e| e.into_inner()) - .abort(reason) + fn abort(&self, py: Python<'_>, reason: &str) { + py.detach(|| self.supervisor.abort(reason)) } } diff --git a/helios/src/core/conversion.rs b/helios/src/core/conversion.rs index a1cd532e1..9f76c0326 100644 --- a/helios/src/core/conversion.rs +++ b/helios/src/core/conversion.rs @@ -2177,29 +2177,55 @@ fn inject_dependency_descriptors( public_key: [u8; 32], recipes: &[derivation::Derivation], ) -> Result<()> { - use crate::core::protection::EnvelopeBuilder; + inject_dependency_descriptors_with_limit( + staging, + key, + core_id, + public_key, + recipes, + schema::MAX_ENVELOPE, + ) +} + +fn inject_dependency_descriptors_with_limit( + staging: &Path, + key: &ring::signature::Ed25519KeyPair, + core_id: [u8; 32], + public_key: [u8; 32], + recipes: &[derivation::Derivation], + inline_limit: usize, +) -> Result<()> { let metadata = Metadata::open(staging)?; let envelope = protection::envelope(&metadata.envelope)?; + let body_store = metadata.body_store(); let mut core = wire::CoreBody::decode(envelope.core_body.as_slice()) .map_err(|e| invalid(format!("invalid core body: {e}")))?; let mut catalog = schema::validate_core(&core)?; - // Source descriptors may live in any deployment or rank body. Build the complete published - // catalog first so dependency injection cannot depend on body ordering. - for signed in &envelope.deployments { - let body = wire::DeploymentBody::decode(signed.body.as_slice()) + // Source descriptors may live in any deployment or rank body. Decode and + // index every body once (resolving externalized bodies via `body_store`) so + // dependency injection cannot depend on body ordering or inline storage. + let mut deployments: Vec<(u32, wire::DeploymentBody)> = + Vec::with_capacity(envelope.deployments.len()); + for (position, signed) in envelope.deployments.iter().enumerate() { + let raw = protection::read_deployment_body(signed, Some(body_store.as_ref()))?; + let body = wire::DeploymentBody::decode(raw.as_ref()) .map_err(|e| invalid(format!("invalid deployment body: {e}")))?; catalog.insert_all(&body.payloads)?; + deployments.push((position as u32, body)); } + let mut ranks_by_deployment: BTreeMap> = BTreeMap::new(); for rank in &envelope.ranks { - let body = crate::core::schema::wire::RankBody::decode(rank.body.as_slice()) + let raw = protection::read_rank_body(rank, Some(body_store.as_ref()))?; + let body = crate::core::schema::wire::RankBody::decode(raw.as_ref()) .map_err(|e| invalid(format!("invalid rank body: {e}")))?; catalog.insert_all(&body.payloads)?; + ranks_by_deployment + .entry(rank.deployment) + .or_default() + .push(body); } - let mut bodies: Vec<(u32, Vec)> = Vec::new(); - for (position, signed) in envelope.deployments.iter().enumerate() { - let mut body = wire::DeploymentBody::decode(signed.body.as_slice()) - .map_err(|e| invalid(format!("invalid deployment body: {e}")))?; - catalog.insert_all(&body.payloads)?; + let mut bodies: Vec<(u32, Vec)> = Vec::with_capacity(deployments.len()); + for (position, mut body) in deployments { if let Some(engram) = &body.engram { for id in engram_payload_ids(engram) { if body.payloads.iter().any(|descriptor| descriptor.id == id) { @@ -2218,10 +2244,10 @@ fn inject_dependency_descriptors( by_target.insert(recipe.target, recipe); } let mut targets: BTreeSet> = body.payloads.iter().map(|d| d.id.clone()).collect(); - for rank in envelope.ranks.iter().filter(|rank| rank.deployment == position as u32) { - let rank_body = crate::core::schema::wire::RankBody::decode(rank.body.as_slice()) - .map_err(|e| invalid(format!("invalid rank body: {e}")))?; - targets.extend(rank_body.payloads.iter().map(|d| d.id.clone())); + if let Some(ranks) = ranks_by_deployment.get(&position) { + for rank_body in ranks { + targets.extend(rank_body.payloads.iter().map(|d| d.id.clone())); + } } let mut pending: Vec> = targets.into_iter().collect(); let mut present: BTreeSet> = body.payloads.iter().map(|d| d.id.clone()).collect(); @@ -2240,21 +2266,18 @@ fn inject_dependency_descriptors( } schema::validate_deployment(&body, &mut catalog)?; let encoded = wire::DeploymentBody::encode_to_vec(&body); - core.deployments[position].body_digest = protection::sha256(&encoded).to_vec(); - bodies.push((position as u32, encoded)); + bodies.push((position, encoded)); } - let mut builder = EnvelopeBuilder::new( - wire::CoreBody::encode_to_vec(&core), + let signed = protection::sign_rewritten_envelope_with_limit( + &mut core, + bodies, + &envelope, + Some(body_store.as_ref()), public_key, core_id, + key, + inline_limit, )?; - for (index, body) in &bodies { - builder.deployment(*index, body.clone())?; - } - for rank in &envelope.ranks { - builder.rank(rank.deployment, rank.rank, rank.body.clone())?; - } - let manifest = builder.sign(key)?; let primary = staging.join("model.safetensors"); let temporary = unique_staging(&primary, "manifest")?; let file = OpenOptions::new() @@ -2265,17 +2288,26 @@ fn inject_dependency_descriptors( let guard = TempFile::new(&temporary); let mut writer = Writer::new(file, metadata.primary().format())?; for name in metadata.primary().tensor_names() { - if name.starts_with(container::ALIGNMENT_PREFIX) { - continue; - } - if name == reader::MANIFEST { - writer.add(name, manifest.len() as u64, Source::Bytes(manifest.clone()))?; + if name.starts_with(container::ALIGNMENT_PREFIX) + || name.starts_with(reader::EXTERNAL_BODY_PREFIX) + || name == reader::MANIFEST + { continue; } let slice = metadata.primary().tensor(name)?; writer.add(name, slice.len(), Source::Slice(slice))?; } + writer.add( + reader::MANIFEST, + signed.manifest.len() as u64, + Source::Bytes(signed.manifest), + )?; + for (sha256, bytes) in signed.external_bodies { + let name = reader::external_body_tensor(&sha256); + writer.add(&name, bytes.len() as u64, Source::Bytes(bytes))?; + } writer.finish()?; + drop(metadata); container::sync_file(&temporary) .map_err(|e| invalid(format!("sync rewritten manifest: {e}")))?; fs::rename(&temporary, &primary) @@ -9575,4 +9607,98 @@ mod tests { "source deployments disagree on checkpoint or preparation semantics" ); } + + #[test] + fn inject_dependency_descriptors_and_promote_handle_externalized_bodies() { + let scratch = Scratch::new("external-body-combine"); + let rng = SystemRandom::new(); + let pkcs8 = signature::Ed25519KeyPair::generate_pkcs8(&rng).unwrap(); + let key = signature::Ed25519KeyPair::from_pkcs8(pkcs8.as_ref()).unwrap(); + let public_key: [u8; 32] = key.public_key().as_ref().try_into().unwrap(); + let publisher = Publisher { + name: "Example".into(), + namespace: "example".into(), + public_key, + development: false, + }; + let bytes = vec![0x42u8; 4096]; + let source = publish_source_full( + &scratch, + "src-inline", + 1, + &[bytes.as_slice()], + &[bytes.as_slice()], + &key, + &publisher, + "model", + EngramFixture::None, + None, + None, + false, + ); + // First rewrite with a 1-byte inline limit to externalize both deployment + // and rank bodies into `flare.body.` tensors, then run a second + // pass whose input envelope already has empty inline bodies. + let metadata = Metadata::open(&source).unwrap(); + let envelope = protect::envelope(&metadata.envelope).unwrap(); + let core_id: [u8; 32] = envelope.core_id.as_slice().try_into().unwrap(); + drop(metadata); + + inject_dependency_descriptors_with_limit(&source, &key, core_id, public_key, &[], 1) + .unwrap(); + let spilled = Metadata::open(&source).unwrap(); + let spilled_env = protect::envelope(&spilled.envelope).unwrap(); + assert!(spilled_env.deployments[0].body.is_empty()); + assert!(spilled_env.deployments[0].external_body.is_some()); + assert!(spilled_env.ranks[0].body.is_empty()); + assert!(spilled_env.ranks[0].external_body.is_some()); + assert!( + spilled + .primary() + .tensor_names() + .any(|name| name.starts_with(reader::EXTERNAL_BODY_PREFIX)) + ); + drop(spilled); + + // Re-running inject_dependency_descriptors on an already-externalized core + // must read bodies via `body_store` and emit valid external bodies. + inject_dependency_descriptors_with_limit(&source, &key, core_id, public_key, &[], 1) + .unwrap(); + let re_spilled = Metadata::open(&source).unwrap(); + let verified = protect::verify_metadata( + &re_spilled, + std::slice::from_ref(&publisher), + protect::Selection::Deployment { + deployment: 0, + rank: None, + }, + ) + .unwrap(); + assert_eq!(verified.ranks().len(), 1); + drop(re_spilled); + + // Promoting an external-body core through `promote` -> `combine` succeeds. + let promoted = scratch.join("promoted"); + promote( + &source, + &promoted, + std::slice::from_ref(&publisher), + "example", + "example", + None, + &key, + ) + .unwrap(); + let verified_promoted = Metadata::open(&promoted).unwrap(); + let authorized = protect::verify_metadata( + &verified_promoted, + std::slice::from_ref(&publisher), + protect::Selection::Deployment { + deployment: 0, + rank: None, + }, + ) + .unwrap(); + assert_eq!(authorized.ranks().len(), 1); + } } diff --git a/helios/src/core/conversion/edit.rs b/helios/src/core/conversion/edit.rs index 3304425d0..c50978fe1 100644 --- a/helios/src/core/conversion/edit.rs +++ b/helios/src/core/conversion/edit.rs @@ -179,20 +179,16 @@ pub fn edit(request: &EditRequest<'_>) -> Result<()> { .iter() .map(|(index, body)| (*index, body.encode_to_vec())) .collect(); - for (index, bytes) in &bodies { - core.deployments[*index as usize].body_digest = protection::sha256(bytes).to_vec(); - } - let mut builder = - protection::EnvelopeBuilder::new(core.encode_to_vec(), public_key, core_id)?; - for (index, body) in bodies { - builder.deployment(index, body)?; - } let body_store = metadata.body_store(); - for rank in &envelope.ranks { - let raw = protection::read_rank_body(rank, Some(body_store.as_ref()))?; - builder.rank(rank.deployment, rank.rank, raw.into_owned())?; - } - let signed = builder.sign_envelope(request.key)?; + let signed = protection::sign_rewritten_envelope( + &mut core, + bodies, + &envelope, + Some(body_store.as_ref()), + public_key, + core_id, + request.key, + )?; schema::validate_locations(&locations)?; let staging = unique_staging(request.output, "edit")?; fs::create_dir(&staging).map_err(|e| invalid(format!("create edit staging: {e}")))?; diff --git a/helios/src/core/protection.rs b/helios/src/core/protection.rs index e7934d07e..e7059f30e 100644 --- a/helios/src/core/protection.rs +++ b/helios/src/core/protection.rs @@ -1501,6 +1501,58 @@ impl EnvelopeBuilder { } } +/// Rebuild and sign a core envelope after updating `core` and deployment bodies, +/// preserving every rank body from `envelope` whether stored inline or in `body_store`. +pub fn sign_rewritten_envelope( + core: &mut wire::CoreBody, + deployments: Vec<(u32, Vec)>, + envelope: &wire::ProtectedCore, + body_store: Option<&dyn BodyStore>, + public_key: [u8; 32], + core_id: [u8; 32], + key: &signature::Ed25519KeyPair, +) -> Result { + sign_rewritten_envelope_with_limit( + core, + deployments, + envelope, + body_store, + public_key, + core_id, + key, + schema::MAX_ENVELOPE, + ) +} + +pub(crate) fn sign_rewritten_envelope_with_limit( + core: &mut wire::CoreBody, + deployments: Vec<(u32, Vec)>, + envelope: &wire::ProtectedCore, + body_store: Option<&dyn BodyStore>, + public_key: [u8; 32], + core_id: [u8; 32], + key: &signature::Ed25519KeyPair, + inline_limit: usize, +) -> Result { + for (index, bytes) in &deployments { + let entry = core + .deployments + .get_mut(*index as usize) + .ok_or_else(|| invalid("deployment index out of range in core body"))?; + entry.body_digest = sha256(bytes).to_vec(); + } + let mut builder = EnvelopeBuilder::new(core.encode_to_vec(), public_key, core_id)? + .with_inline_limit(inline_limit); + for (index, body) in deployments { + builder.deployment(index, body)?; + } + for rank in &envelope.ranks { + let raw = read_rank_body(rank, body_store)?; + builder.rank(rank.deployment, rank.rank, raw.into_owned())?; + } + builder.sign_envelope(key) +} + /// Compression metadata for one executable resource. #[derive(Clone, Debug, PartialEq, Eq)] pub struct CompressedResource { diff --git a/ignition/preparation/aot.py b/ignition/preparation/aot.py index a84b45eca..fb181eaf8 100644 --- a/ignition/preparation/aot.py +++ b/ignition/preparation/aot.py @@ -769,23 +769,32 @@ def finish(rank, extra=0): assigned[idlest].append(assigned[busiest].pop()) -def _share_artifacts(owned, group, ranks): - """Copy every rank's compiled forwards to ranks on other hosts, which load them by the same path. +def _resolve_shared_path(root, name): + candidate = Path(name) + if root is None: + return candidate + if candidate.is_absolute() or ".." in candidate.parts: + raise ValueError(f"shared forward artifact path must stay relative to cache root: {name!r}") + return Path(root) / candidate - `owned[i]` lists the artifacts rank `ranks[i]` compiled. Each rank keeps its own cache - directory; a rank receives only artifacts it lacks or whose contents differ from their - compiler's. + +def _share_artifacts(owned, group, ranks, root=None): + """Copy every rank's compiled forwards to ranks on other hosts, resolved under each host's `root`. + + `owned[i]` lists the artifacts rank `ranks[i]` compiled. When `root` is provided, + entries are cache-root-relative POSIX paths so hosts with different cache directories + exchange artifacts without assuming identical absolute paths. """ import torch.distributed as dist me = ranks.index(dist.get_rank()) digests = [None] * len(ranks) - dist.all_gather_object(digests, {path: hashlib.sha256(Path(path).read_bytes()).hexdigest() + dist.all_gather_object(digests, {path: hashlib.sha256(_resolve_shared_path(root, path).read_bytes()).hexdigest() for path in owned[me]}, group=group) def current(path, digest): try: - return hashlib.sha256(Path(path).read_bytes()).hexdigest() == digest + return hashlib.sha256(_resolve_shared_path(root, path).read_bytes()).hexdigest() == digest except OSError: return False @@ -796,10 +805,10 @@ def current(path, digest): wanted = set().union(*wanted) for index, compiled in enumerate(digests): for path in sorted(wanted.intersection(compiled)): - payload = [Path(path).read_bytes() if index == me else None] + payload = [_resolve_shared_path(root, path).read_bytes() if index == me else None] dist.broadcast_object_list(payload, src=ranks[index], group=group) if path in missing: - target = Path(path) + target = _resolve_shared_path(root, path) target.parent.mkdir(parents=True, exist_ok=True) with tempfile.NamedTemporaryFile(dir=target.parent, suffix=".tmp", delete=False) as file: file.write(payload[0]) @@ -1119,7 +1128,7 @@ def _prepare_ranks(self, functions, signatures, coordinator, *, progress, materi temporary.unlink(missing_ok=True) sent.append((borrower, str(job))) # The borrower compiles it before every rank gathers the outcome below. - paths[name, variant] = str(path), True + paths[name, variant] = path.relative_to(self.root).as_posix(), True except Exception as failure: error = error or f"{type(failure).__name__}: {failure}" mailed = [None] * len(ranks) @@ -1138,8 +1147,8 @@ def finish(): # Restored and bound to this rank's own forward already. selected[name] = bound if name is not None: - # Each forward's path, and whether this launch compiled it rather than restoring it. - paths[name, variant] = str(path), bound.pending is not None + # Each forward's cache-relative path, and whether this launch compiled it rather than restoring it. + paths[name, variant] = Path(path).relative_to(self.root).as_posix(), bound.pending is not None stage.update(advance=1) for index, (name, variant, forward) in enumerate(work): @@ -1148,7 +1157,7 @@ def finish(): if index in restored: bound, path = restored[index] if stream: - paths[name, variant] = str(path), False + paths[name, variant] = Path(path).relative_to(self.root).as_posix(), False stage.update(advance=1) continue else: @@ -1191,7 +1200,7 @@ def finish(): # Ranks on one host compiled into its cache directory; only other hosts lack their shares. if coordinator.spans_hosts: _share_artifacts([sorted({path for path, _ in compiled.values()}) for compiled, _ in outcomes], - group, ranks) + group, ranks, root=self.root) error, sizes = None, None try: release_unused() @@ -1200,7 +1209,8 @@ def finish(): sizes = { name: (selected[name].capture_allocation_sizes if name in selected else sizes_cache[name] if name in sizes_cache - else self._allocation_sizes(paths[name, getattr(forward, "compilation_variant", "shared")][0])) + else self._allocation_sizes( + _resolve_shared_path(self.root, paths[name, getattr(forward, "compilation_variant", "shared")][0]))) for name, forward in functions.items() } except Exception as failure: @@ -1224,9 +1234,10 @@ def finish(): if name in selected: bound = selected.pop(name) else: - path, compiled = paths[name, variant] + rel_path, compiled = paths[name, variant] + local_path = _resolve_shared_path(self.root, rel_path) with _guard_code_cache(self.root / 'guards'): - bound = self._load(forward, Path(path), required=True, + bound = self._load(forward, local_path, required=True, before_run=call_before_run) bound.cache_hit = not compiled selections.register(bound) @@ -1245,15 +1256,16 @@ def finish(): failure = None try: selections.freeze(bound) - path, _ = paths[name, variant] + rel_path, _ = paths[name, variant] + local_path = _resolve_shared_path(self.root, rel_path) if compilers[name, variant] == share: - bound.artifact.save_compiled_function(path) - published.append(path) + bound.artifact.save_compiled_function(str(local_path)) + published.append(rel_path) if stream: selected[name] = DeferredCompiledForward( cache=self, owner=forward, - path=Path(path), + path=local_path, cache_hit=bound.cache_hit, capture_allocation_sizes=bound.capture_allocation_sizes, before_run=call_before_run, @@ -1278,7 +1290,7 @@ def finish(): stage.update(f"{released >> 20} MiB portable state released; guards and kernel owners retained") release_unused() if coordinator.spans_hosts: - _share_artifacts(selections._gather(published), group, ranks) + _share_artifacts(selections._gather(published), group, ranks, root=self.root) return selected def _allocation_sizes(self, path): diff --git a/ignition/preparation/compilation.py b/ignition/preparation/compilation.py index 72910e154..82784a435 100644 --- a/ignition/preparation/compilation.py +++ b/ignition/preparation/compilation.py @@ -172,6 +172,7 @@ def _storage_regions(nodes, keys): """Partition persistent storage only where every traced tensor view is disjoint.""" persistent = {keys[node] for node in nodes if node.op == 'get_attr' and node in keys} ranges = {} + limits = {} for node, key in keys.items(): if key not in persistent: continue @@ -179,18 +180,37 @@ def _storage_regions(nodes, keys): begin = int(value.storage_offset()) * value.element_size() span = 0 if not value.numel() else 1 + sum( (int(size) - 1) * int(stride) for size, stride in zip(value.shape, value.stride())) - ranges.setdefault(key, []).append((begin, begin + span * value.element_size(), node)) + end = begin + span * value.element_size() + ranges.setdefault(key, []).append((begin, end, node)) + storage_nbytes = int(value.untyped_storage().nbytes()) + limits[key] = max(limits.get(key, 0), storage_nbytes, end) regions = {} for key, spans in ranges.items(): - alignment = max(node.meta['val'].element_size() for _, _, node in spans) + storage_nbytes = limits[key] groups = [] for begin, end, node in sorted(spans, key=lambda item: (item[0], item[1])): - begin, end = begin // alignment * alignment, (end + alignment - 1) // alignment * alignment if groups and begin < groups[-1][1]: groups[-1][1] = max(groups[-1][1], end) groups[-1][2].append(node) else: groups.append([begin, end, [node]]) + # Align each group to its own widest element size, clamping to storage_nbytes + # and merging adjacent groups whose aligned extents overlap. + while True: + aligned = [] + for begin, end, members in groups: + alignment = max(node.meta['val'].element_size() for node in members) + a_begin = begin // alignment * alignment + a_end = min(storage_nbytes, (end + alignment - 1) // alignment * alignment) + if aligned and a_begin < aligned[-1][1]: + aligned[-1][1] = max(aligned[-1][1], a_end) + aligned[-1][2].extend(members) + else: + aligned.append([a_begin, a_end, list(members)]) + if len(aligned) == len(groups): + groups = aligned + break + groups = aligned for index, (begin, end, members) in enumerate(groups): region = (key, index) regions[region] = (begin, end) @@ -665,8 +685,13 @@ def tensor_operands(node): shape = tuple(map(int, value.shape)) stride = tuple(map(int, value.stride())) offset = int(value.storage_offset()) - regions[key_for(node)][0] // value.element_size() + region_bytes = regions[key_for(node)][1] - regions[key_for(node)][0] + base_node = bases[key_for(node)] with graph.inserting_before(node): - typed = graph.call_function(torch.ops.aten.view.dtype, (bases[key_for(node)], value.dtype)) + if len(dtypes[key_for(node)]) > 1 and region_bytes % value.element_size() != 0: + usable = region_bytes // value.element_size() * value.element_size() + base_node = graph.call_function(torch.ops.aten.slice.Tensor, (base_node, 0, 0, usable)) + typed = graph.call_function(torch.ops.aten.view.dtype, (base_node, value.dtype)) if value.is_contiguous(): sliced = graph.call_function(torch.ops.aten.slice.Tensor, (typed, 0, offset, offset + math.prod(shape))) @@ -746,9 +771,16 @@ def forget(value, pending): for previous in affected: if last_use[previous] > index: required.setdefault(previous, []).append(node) - pending = live.pop(previous) - forget(previous, pending) - pending.clear() + pending = live[previous] + cleared = pending & mutations[node] + pending -= cleared + for key in cleared: + values = fresh_by_storage[key] + values.remove(previous) + if not values: + del fresh_by_storage[key] + if not pending: + del live[previous] for value in expires[index]: pending = live.pop(value, None) if pending: diff --git a/ignition/preparation/core_storage.py b/ignition/preparation/core_storage.py index a3e13e826..02bcb0b05 100644 --- a/ignition/preparation/core_storage.py +++ b/ignition/preparation/core_storage.py @@ -100,6 +100,7 @@ def __init__(self, *, rank=0, world=1, device=0, local_ranks=None, device_window self.cuda.call("cuDeviceGetAttribute", C.byref(gpudirect), C.c_int(116), C.c_int(device)) self.gpudirect = bool(gpudirect.value) and not self.integrated self.HOST_BASE = layout["host_base"] + self.HOST_RESERVATION_BYTES = layout.get("host_extent", self.HOST_RESERVATION_BYTES) self._host_cursor = self.HOST_BASE self.low_reservations = [] # WDDM retains its low allocation pool; export rejects retained storage below the floor. @@ -615,6 +616,9 @@ def grow(self, nbytes): return cuda, device = self.cuda, self.device address, size = self.address + self.nbytes, nbytes - self.nbytes + import torch + + stream = torch.cuda.current_stream(device).cuda_stream handle = C.c_uint64() properties = _Properties(1, 0 if os.name == "nt" else 1, _Location(1, device), None, (C.c_ubyte * 8)(0, int(self.gpudirect), 0, 0, 0, 0, 0, 0)) @@ -628,7 +632,7 @@ def grow(self, nbytes): cuda.call("cuMemRelease", handle) access = _Access(_Location(1, device), 3) cuda.call("cuMemSetAccess", C.c_uint64(address), C.c_size_t(size), C.byref(access), C.c_size_t(1)) - cuda.call("cuMemsetD8_v2", C.c_uint64(address), C.c_ubyte(0), C.c_size_t(size)) + cuda.call("cuMemsetD8Async", C.c_uint64(address), C.c_ubyte(0), C.c_size_t(size), C.c_void_p(stream)) except BaseException: if mapped: cuda.call("cuMemUnmap", C.c_uint64(address), C.c_size_t(size)) diff --git a/ignition/preparation/kv_codec.py b/ignition/preparation/kv_codec.py index 9450acdb0..0687365b3 100644 --- a/ignition/preparation/kv_codec.py +++ b/ignition/preparation/kv_codec.py @@ -47,6 +47,7 @@ def _target_arch(capability: tuple[int, int]) -> str: def compile_gpu_codec_cubin( capability: tuple[int, int] | None = None, *, + device: int | None = None, cache_dir: Path | None = None, ) -> Path: """Compile `kv_codec_gpu.cu` into a target-architecture ELF cubin and return its path. @@ -58,7 +59,7 @@ def compile_gpu_codec_cubin( if capability is None: import torch - capability = tuple(int(x) for x in torch.cuda.get_device_capability()) + capability = tuple(int(x) for x in torch.cuda.get_device_capability(device)) cache_key = (capability, None if cache_dir is None else Path(cache_dir)) cached = _CACHE.get(cache_key) if cached is not None and cached.is_file(): diff --git a/ignition/preparation/kv_codec_gpu.cu b/ignition/preparation/kv_codec_gpu.cu index 68075844d..c323e6ea6 100644 --- a/ignition/preparation/kv_codec_gpu.cu +++ b/ignition/preparation/kv_codec_gpu.cu @@ -863,10 +863,10 @@ __global__ void kv_crc32_finish_gpu( U *crc_out ) { int tid = threadIdx.x; // 0..255 - __shared__ U gf2_pow[30][32]; + __shared__ U gf2_pow[64][32]; __shared__ U sh_crc[CRC_BLOCKS]; __shared__ uint64_t sh_len[CRC_BLOCKS]; - init_gf2_pow_sh(gf2_pow, 30, tid); + init_gf2_pow_sh(gf2_pow, 64, tid); sh_crc[tid] = partials[tid]; sh_len[tid] = part_lens[tid]; __syncthreads(); @@ -875,7 +875,7 @@ __global__ void kv_crc32_finish_gpu( if ((tid & (2 * stride - 1)) == 0) { U c2 = sh_crc[tid + stride]; uint64_t l2 = sh_len[tid + stride]; - sh_crc[tid] = crc32_combine_dev(gf2_pow, 30, sh_crc[tid], c2, l2); + sh_crc[tid] = crc32_combine_dev(gf2_pow, 64, sh_crc[tid], c2, l2); sh_len[tid] += l2; } __syncthreads(); @@ -1565,41 +1565,41 @@ __global__ void kv_build_packet_plan_gpu( U num_mats ) { if (threadIdx.x != 0 || blockIdx.x != 0) return; - U total_lanes = num_mats * 4u; - U meta = (U)HEADER_BYTES + num_chunks * 4u + total_lanes * 2u; + uint64_t total_lanes = (uint64_t)num_mats * 4ull; + uint64_t meta = (uint64_t)HEADER_BYTES + (uint64_t)num_chunks * 4ull + total_lanes * 2ull; - U pos = meta; + uint64_t pos = meta; for (U i = 0; i < num_chunks; ++i) { U w = chunk_words[i]; U len = w & ~RAW_FLAG; - chunk_pkt_offs[i] = pos; - pos += len; + chunk_pkt_offs[i] = (U)pos; + pos += (uint64_t)len; } - U low_base = pos; - U low_bytes = 0u; - for (U i = 0; i < total_lanes; ++i) { - lane_byte_offs[i] = low_bytes; - low_bytes += (U)lane_u32s[i] * 4u; + uint64_t low_base = pos; + uint64_t low_bytes = 0ull; + for (uint64_t i = 0; i < total_lanes; ++i) { + lane_byte_offs[i] = (U)low_bytes; + low_bytes += (uint64_t)lane_u32s[i] * 4ull; } - U total_pkt = low_base + low_bytes; - *total_pkt_out = (uint64_t)total_pkt; - *low_base_out = low_base; + uint64_t total_pkt = low_base + low_bytes; + *total_pkt_out = total_pkt; + *low_base_out = (total_pkt < (uint64_t)orig_bytes) ? (U)low_base : 0u; - if (total_pkt >= orig_bytes) return; + if (total_pkt >= (uint64_t)orig_bytes) return; store_u32_le(d_pkt + 0, GKV1_MAGIC); store_u32_le(d_pkt + 4, GKV1_VERSION); store_u32_le(d_pkt + 8, orig_bytes); store_u32_le(d_pkt + 12, num_chunks); store_u32_le(d_pkt + 16, num_mats); - store_u32_le(d_pkt + 20, low_bytes); + store_u32_le(d_pkt + 20, (U)low_bytes); - U dir_end = (U)HEADER_BYTES + num_chunks * 4u; + size_t dir_end = (size_t)HEADER_BYTES + (size_t)num_chunks * 4u; for (U i = 0; i < num_chunks; ++i) { - store_u32_le(d_pkt + HEADER_BYTES + i * 4u, chunk_words[i]); + store_u32_le(d_pkt + (size_t)HEADER_BYTES + (size_t)i * 4u, chunk_words[i]); } - for (U i = 0; i < total_lanes; ++i) { - store_u16_le(d_pkt + dir_end + i * 2u, lane_u32s[i]); + for (uint64_t i = 0; i < total_lanes; ++i) { + store_u16_le(d_pkt + dir_end + (size_t)i * 2u, lane_u32s[i]); } } @@ -1632,15 +1632,15 @@ __global__ void kv_compact_packet_gpu( U nwords = (U)lane_u32s[lane_id]; if (nwords == 0u) return; const B *src = reinterpret_cast(low_padded_in + (size_t)lane_id * LANE_STRIDE); - B *dst = d_pkt + (size_t)(*low_base_ptr + lane_byte_offs[lane_id]); + B *dst = d_pkt + (size_t)(*low_base_ptr) + (size_t)lane_byte_offs[lane_id]; copy_span_cta(dst, src, (size_t)nwords * 4u); } } // Multi-page batched packet plan builder for non-matrix page batches (`grid = 1`, `block = 1..64`). -// Strides across `blockDim.x` so both `block = 64` (parallel) and `block = 1` (older binaries) -// pack all `batch` (<= 64) packets contiguously into `d_pkt` (leaving `orig_bytes` literal slots -// for incompressible pages), computing per-page directories and writing `GKV1/v2` headers. +// Strides across `blockDim.x` so any `batch` size packs contiguously into `d_pkt` (leaving +// `orig_bytes` literal slots for incompressible pages), computing per-page directories and +// writing `GKV1/v2` headers without a fixed shared-memory batch cap. __global__ void kv_build_packet_plan_batch_gpu( B *d_pkt, const U *chunk_words, @@ -1653,41 +1653,36 @@ __global__ void kv_build_packet_plan_batch_gpu( int batch ) { if (blockIdx.x != 0) return; - __shared__ uint64_t page_used_sh[64]; - __shared__ uint64_t page_off_sh[64]; - __shared__ U page_pos_sh[64]; - U meta = (U)HEADER_BYTES + num_chunks_per_page * 4u; + uint64_t meta = (uint64_t)HEADER_BYTES + (uint64_t)num_chunks_per_page * 4ull; for (int p = threadIdx.x; p < batch; p += blockDim.x) { - U pos = meta; - U base_c = (U)p * num_chunks_per_page; + uint64_t pos = meta; + size_t base_c = (size_t)p * (size_t)num_chunks_per_page; for (U c = 0; c < num_chunks_per_page; ++c) { U w = chunk_words[base_c + c]; U len = w & ~RAW_FLAG; - chunk_pkt_offs[base_c + c] = pos; - pos += len; + chunk_pkt_offs[base_c + c] = (U)pos; + pos += (uint64_t)len; } - total_pkt_arr[p] = (uint64_t)pos; - page_pos_sh[p] = pos; - page_used_sh[p] = (pos < orig_bytes) ? (uint64_t)pos : (uint64_t)orig_bytes; + total_pkt_arr[p] = pos; } __syncthreads(); if (threadIdx.x == 0) { uint64_t batch_pos = 0ull; for (int i = 0; i < batch; ++i) { - page_off_sh[i] = batch_pos; - batch_pos += page_used_sh[i]; + pkt_out_offs[i] = batch_pos; + uint64_t pos = total_pkt_arr[i]; + batch_pos += (pos < (uint64_t)orig_bytes) ? pos : (uint64_t)orig_bytes; } *total_batch_bytes_out = batch_pos; } __syncthreads(); for (int p = threadIdx.x; p < batch; p += blockDim.x) { - uint64_t out_off = page_off_sh[p]; - pkt_out_offs[p] = out_off; - if (page_pos_sh[p] < orig_bytes) { - U base_c = (U)p * num_chunks_per_page; + uint64_t out_off = pkt_out_offs[p]; + if (total_pkt_arr[p] < (uint64_t)orig_bytes) { + size_t base_c = (size_t)p * (size_t)num_chunks_per_page; B *hdr = d_pkt + out_off; store_u32_le(hdr + 0, GKV1_MAGIC); store_u32_le(hdr + 4, GKV1_VERSION); @@ -1696,7 +1691,7 @@ __global__ void kv_build_packet_plan_batch_gpu( store_u32_le(hdr + 16, 0u); store_u32_le(hdr + 20, 0u); for (U c = 0; c < num_chunks_per_page; ++c) { - store_u32_le(hdr + HEADER_BYTES + c * 4u, chunk_words[base_c + c]); + store_u32_le(hdr + (size_t)HEADER_BYTES + (size_t)c * 4u, chunk_words[base_c + c]); } } } diff --git a/ignition/preparation/peer_storage.py b/ignition/preparation/peer_storage.py index 1419a538d..1bb6ea2a8 100644 --- a/ignition/preparation/peer_storage.py +++ b/ignition/preparation/peer_storage.py @@ -22,7 +22,7 @@ class _Location(C.Structure): class _Access(C.Structure): - _fields_ = [("location", _Location), ("flags", C.c_uint64)] + _fields_ = [("location", _Location), ("flags", C.c_uint32)] class PeerStorage(CudaRTLibrary): diff --git a/ignition/preparation/runtime_core.py b/ignition/preparation/runtime_core.py index def53ff3d..1067a4d9f 100644 --- a/ignition/preparation/runtime_core.py +++ b/ignition/preparation/runtime_core.py @@ -403,7 +403,8 @@ def export_model(prepared, images, storage, path, *, options, progress=None, pub from .kv_codec import GPU_CODEC_MODULE_NAME, compile_gpu_codec_cubin cubin_path = compile_gpu_codec_cubin( - cache_dir=None if cache is None else cache.kernel_cache + device=storage.device, + cache_dir=None if cache is None else cache.kernel_cache, ) extra_modules[GPU_CODEC_MODULE_NAME] = str(cubin_path) if server is not None: diff --git a/ignition/preparation/tuning.py b/ignition/preparation/tuning.py index 4899b701e..973bd3604 100644 --- a/ignition/preparation/tuning.py +++ b/ignition/preparation/tuning.py @@ -417,6 +417,7 @@ def tune(self, *, progress=None, show_progress=False, console=None): raise RuntimeError("full serving preparation requires enabled, uncancelled b12x tuning") requests = tuple(self._recorded_requests.values()) partial_shards = False + shard_rank = None if self.tuning_replica is not None: import torch.distributed as dist from .tuning_replicas import ReplicaPreparation @@ -438,12 +439,16 @@ def tune(self, *, progress=None, show_progress=False, console=None): # Candidate shards must cover the same local races on every rank. self._sharded = self._coordinator.same_on_every_rank( (torch.cuda.get_device_properties(self.device.ordinal).name, _local_tuning_catalog(requests))) + # Seed every host with rank zero's cached selections before tuning, + # whether the catalog is fully sharded or partially sharded, so + # independent host caches cannot diverge on warm retries. + if self._coordinator.spans_hosts: + self._coordinator.share_selections(self.selection_cache()) if self._sharded: - self.configure_tuning_shard(dist.get_rank(), self._coordinator.ranks) + shard_rank = dist.get_rank() + self.configure_tuning_shard(shard_rank, self._coordinator.ranks) else: partial_shards = True - if self._coordinator.spans_hosts: - self._coordinator.share_selections(self.selection_cache()) scratch_arena = self._reserve_scratch(requests) if partial_shards: device = self.device @@ -497,14 +502,20 @@ def update(status): if self.is_cancelled(): raise RuntimeError("b12x tuning was cancelled before serving preparation completed") if (self._coordinator is not None and len(self._coordinator.ranks) > 1 - and not self._sharded and self._replica_coordinator is None): + and self._replica_coordinator is None): configs, changed = self._coordinator.reconcile_selections(requests) if changed: - for job in self._jobs(requests): - plans = {plan for request in job for plan in iter_plans(request)} - results.append(self._coordinator.prepare(self, job, progress=progress, - autotune=self.autotune, - selected_configs={plan: config for plan, config in configs.items() if plan in plans})) + if self._sharded: + self.configure_tuning_shard(0, (0,)) + try: + for job in self._jobs(requests): + plans = {plan for request in job for plan in iter_plans(request)} + results.append(self._coordinator.prepare(self, job, progress=progress, + autotune=self.autotune, + selected_configs={plan: config for plan, config in configs.items() if plan in plans})) + finally: + if self._sharded: + self.configure_tuning_shard(shard_rank, self._coordinator.ranks) selections = [] coverage = {name: value for result in results for name, value in result.coverage.items()} for request in requests: diff --git a/tests/preparation/test_forward_artifact_sharing.py b/tests/preparation/test_forward_artifact_sharing.py index 425660929..8c67f54ab 100644 --- a/tests/preparation/test_forward_artifact_sharing.py +++ b/tests/preparation/test_forward_artifact_sharing.py @@ -61,6 +61,42 @@ def test_every_rank_receives_what_it_lacks_from_the_rank_that_compiled_it(tmp_pa assert results == {rank: expected for rank in range(3)} +def _rank_distinct_roots(rank, world, store, cache_root, owned, outcome): + import torch.distributed as dist + + from ignition.preparation.aot import _share_artifacts + + try: + dist.init_process_group("gloo", init_method=f"file://{store}", rank=rank, world_size=world) + _share_artifacts(owned, dist.group.WORLD, tuple(range(world)), root=cache_root) + outcome.put((rank, {name: (cache_root / name).read_bytes() for name in ("a.bin", "b.bin")})) + dist.destroy_process_group() + except Exception as error: # noqa: BLE001 - The parent reports every rank's failure. + outcome.put((rank, repr(error))) + + +def test_share_artifacts_resolves_relative_paths_against_each_hosts_own_root(tmp_path): + context = multiprocessing.get_context("fork") + roots = [tmp_path / "alice_cache" / "forwards", tmp_path / "bob_cache" / "forwards"] + for root in roots: + root.mkdir(parents=True) + (roots[0] / "a.bin").write_bytes(b"host-a") + (roots[1] / "b.bin").write_bytes(b"host-b") + owned = [["a.bin"], ["b.bin"]] + outcome = context.Queue() + processes = [context.Process(target=_rank_distinct_roots, + args=(rank, 2, tmp_path / "store", roots[rank], owned, outcome)) + for rank in range(2)] + for process in processes: + process.start() + results = dict(outcome.get(timeout=60) for _ in processes) + for process in processes: + process.join(timeout=60) + assert process.exitcode == 0 + expected = {"a.bin": b"host-a", "b.bin": b"host-b"} + assert results == {0: expected, 1: expected} + + def test_ranks_lend_missing_compilations_until_lending_finishes_no_sooner(): from ignition.preparation.aot import _balance_compilations diff --git a/tests/preparation/test_peer_storage_groups.py b/tests/preparation/test_peer_storage_groups.py index 59af015fd..d8acd97e2 100644 --- a/tests/preparation/test_peer_storage_groups.py +++ b/tests/preparation/test_peer_storage_groups.py @@ -91,3 +91,8 @@ def call(self, name, *arguments): assert pointer not in owner.owned finally: os.close(descriptor) + + +def test_cuda_mem_access_desc_ctypes_layout_matches_abi(): + assert C.sizeof(peer_storage._Location) == 8 + assert C.sizeof(peer_storage._Access) == 12 diff --git a/tests/preparation/test_persistent.py b/tests/preparation/test_persistent.py index dd089d85d..1eb372aff 100644 --- a/tests/preparation/test_persistent.py +++ b/tests/preparation/test_persistent.py @@ -37,7 +37,9 @@ def call(self, name, *args): address, size = args[0].value, args[1].value assert self.address <= address < address + size <= self.address + self.capacity self.mapped.append((address, size)) - elif name == "cuMemsetD8_v2": + elif name == "cuMemsetD8Async": + assert len(args) == 4 + assert args[3].value == 0x1234 C.memset(args[0].value, args[1].value, args[2].value) elif name == "cuMemUnmap": self.mapped.remove((args[0].value, args[1].value)) @@ -53,6 +55,10 @@ def packed_storage(monkeypatch): memory = Memory() storage = CoreStorage.__new__(CoreStorage) storage.device, storage.rank, storage.world = 0, 0, 1 + def fake_current_stream(device=None): + assert device == storage.device + return SimpleNamespace(cuda_stream=0x1234) + monkeypatch.setattr(torch.cuda, "current_stream", fake_current_stream) storage.cuda, storage.granularity, storage.gpudirect = memory, 128, True storage.DEVICE_BASE = memory.address storage.RESERVATION_BYTES = memory.capacity * 2 @@ -114,7 +120,7 @@ def test_state_transfer_pointer_tables_use_packed_storage_without_numeric_regist storage.close() -@pytest.mark.parametrize("failure", ["cuMemMap", "cuMemSetAccess", "cuMemsetD8_v2"]) +@pytest.mark.parametrize("failure", ["cuMemMap", "cuMemSetAccess", "cuMemsetD8Async"]) def test_mapping_failure_preserves_existing_destinations(packed_storage, failure): storage = packed_storage with storage: diff --git a/tests/preparation/test_storage_lifetimes.py b/tests/preparation/test_storage_lifetimes.py index 6714c7d39..ca1ec95d9 100644 --- a/tests/preparation/test_storage_lifetimes.py +++ b/tests/preparation/test_storage_lifetimes.py @@ -35,7 +35,7 @@ def reference_reads_across_mutations(nodes, keys, mutations): for previous, pending in live.items(): if previous in fresh and last_use[previous] > index and pending & mutations[node]: required.setdefault(previous, []).append(node) - pending.clear() + pending -= mutations[node] live = {value: pending for value, pending in live.items() if pending and last_use[value] > index} if (node.op == 'call_function' and isinstance(node.target, torch._ops.OpOverload) and node.target.namespace == 'aten'): @@ -134,17 +134,18 @@ def test_reads_precede_mutation_and_last_use_expiry(): assert assert_matches_reference(graph, keys, {write: [source]}) == {} -def test_snapshot_clears_all_pending_storage_dependencies(): +def test_snapshot_tracks_each_disjoint_pending_storage_dependency(): graph = torch.fx.Graph() left, right = graph.placeholder('left'), graph.placeholder('right') saved = graph.call_function(torch.ops.aten.add.Tensor, (left, right)) first = graph.call_function(torch.ops.aten.zero_.default, (left,)) second = graph.call_function(torch.ops.aten.zero_.default, (right,)) + third = graph.call_function(torch.ops.aten.zero_.default, (left,)) consumed = graph.call_function(torch.ops.aten.sin.default, (saved,)) graph.output(consumed) - keys = {left: 0, right: 1, saved: 2, first: 0, second: 1, consumed: 3} - actual = assert_matches_reference(graph, keys, {first: [left], second: [right]}) - assert actual == {saved: [first]} + keys = {left: 0, right: 1, saved: 2, first: 0, second: 1, third: 0, consumed: 3} + actual = assert_matches_reference(graph, keys, {first: [left], second: [right], third: [left]}) + assert actual == {saved: [first, second]} def test_mutation_reads_propagate_before_snapshot_clears(): @@ -622,3 +623,39 @@ def mutated_computed_temp(): assert len(copy_nodes2) == 1 assert copy_nodes2[0].args[1].target is torch.ops.aten.add.Tensor + +def test_reads_across_mutations_orders_against_all_disjoint_input_mutations(): + # A computed value reading two distinct mutable storages must be ordered before + # both mutations; clearing all pending keys on the first mutation leaves the + # second mutation free to reorder ahead of the snapshot. + graph = torch.fx.Graph() + buf_a = graph.placeholder('buf_a') + buf_b = graph.placeholder('buf_b') + added = graph.call_function(torch.ops.aten.add.Tensor, (buf_a, buf_b)) + write_a = graph.call_function(torch.ops.aten.zero_.default, (buf_a,)) + write_b = graph.call_function(torch.ops.aten.zero_.default, (buf_b,)) + out = graph.call_function(torch.ops.aten.mul.Tensor, (added, 2.0)) + graph.output(out) + keys = {buf_a: 0, buf_b: 1, added: 2, write_a: 0, write_b: 1, out: 3} + result = assert_matches_reference(graph, keys, {write_a: [buf_a], write_b: [buf_b]}) + assert result == {added: [write_a, write_b]} + + +def test_storage_regions_align_per_group_without_exceeding_storage_length(): + from torch.fx.experimental.proxy_tensor import make_fx + + # A 5-byte backing storage with float32 at [0..4) and uint8 at [4..5) must keep + # the two views disjoint and never round the uint8 tail past storage.nbytes(). + backing = torch.empty(5, dtype=torch.uint8) + f32_view = backing[:4].view(torch.float32) + u8_view = backing[4:5] + + def forward(): + return f32_view + 1.0, u8_view + 1 + + mod = make_fx(forward)() + compilation._lower_storage(mod) + storage_buffers = [buf for name, buf in mod.named_buffers() if name.startswith('_storage_')] + assert len(storage_buffers) == 2 + assert sorted(buf.nbytes for buf in storage_buffers) == [1, 4] + diff --git a/tests/preparation/test_tuning_shards.py b/tests/preparation/test_tuning_shards.py index 3bd6f7891..938d89819 100644 --- a/tests/preparation/test_tuning_shards.py +++ b/tests/preparation/test_tuning_shards.py @@ -160,3 +160,102 @@ def test_mixed_tuning_batches_shard_common_components_and_run_remainders_over_gl assert [p.exitcode for p in procs] == [0, 0] results = dict(queue.get(timeout=5) for _ in range(2)) assert results == {0: "ok", 1: "ok"} + + +def test_sharded_multihost_tune_shares_cache_and_reconciles_divergent_selections(monkeypatch): + from contextlib import nullcontext + import torch.distributed as dist + from ignition.preparation.tuning import RecordedPreparationSession + + req = request("decode1.layer0.moe.experts", 32) + object.__setattr__( + req.plan, + "_prepared", + SimpleNamespace(closed=False, selection=SimpleNamespace(source="autotuned", config=1)), + ) + events = [] + shard_calls = [] + + class _FakeCoordinator: + ranks = (0, 1) + local_ranks = 1 + spans_hosts = True + group = object() + + def same_on_every_rank(self, value): + return True + + def share_selections(self, cache): + events.append(("share_selections", cache)) + + def prepare(self, session, job, *, progress=None, autotune=None, selected_configs=None): + events.append(("prepare", bool(selected_configs), shard_calls[-1] if shard_calls else None)) + if selected_configs: + for plan, config in selected_configs.items(): + object.__setattr__( + plan, + "_prepared", + SimpleNamespace(closed=False, selection=SimpleNamespace(source="autotuned", config=config)), + ) + return SimpleNamespace( + coverage={}, cache_hits=0, benchmarked_candidates=0, restored_candidates=0, + rejected_candidates=0, elapsed_seconds=0.0, parent_cute_compilations=0, + parent_triton_compilations=0, close=lambda: None, + ) + + def reconcile_selections(self, requests): + events.append(("reconcile_selections", len(requests))) + return {req.plan: 2}, True + + def agree_selections(self, selections): + events.append(("agree_selections", [item["config"] for item in selections])) + + monkeypatch.setattr(dist, "get_rank", lambda: 1) + monkeypatch.setattr( + torch.cuda, + "get_device_properties", + lambda ordinal: SimpleNamespace(name="GB10", is_integrated=False, major=12, minor=1), + ) + monkeypatch.setattr(torch.cuda, "device", lambda ordinal: nullcontext()) + monkeypatch.setattr(torch.cuda, "empty_cache", lambda: None) + monkeypatch.setattr(torch.accelerator.memory, "empty_host_cache", lambda: None) + monkeypatch.setattr("ignition.preparation.tuning.release_unused", lambda: None) + monkeypatch.setattr("ignition.preparation.tuning.tuning_limits", lambda *a, **kw: (1, 1 << 20)) + + session = object.__new__(RecordedPreparationSession) + session._require_collecting = lambda: None + session._recorded_requests = {req.name: req} + session.is_cancelled = lambda: False + session.tuning_replica = None + session._replica_coordinator = None + session.autotune = True + session._coordinator = _FakeCoordinator() + session.device = DEVICE + session.selection_cache = lambda: "rank-cache" + session.configure_tuning_shard = lambda rank, ranks: shard_calls.append((rank, tuple(ranks))) + session._reserve_scratch = lambda reqs: {} + session.requested_compile_workers = None + session.compile_workers = 1 + session.configure_compile_workers = lambda count: None + session.headroom_bytes = 0 + session.race_budget = None + session.lock_gpu_clocks = False + session._scratch_arena = None + session._finalizers = [] + session.synchronize = lambda: None + session._workload_schema = 1 + session.namespace = SimpleNamespace(to_dict=lambda: {}) + session.autotune_effort = "default" + session.native_dense_activations = False + session._benchmark_resources = {} + session._benchmark_restorers = {} + session._restore_benchmark_resources = lambda: None + session._search_limits = {} + + session.tune() + + assert ("share_selections", "rank-cache") in events + assert ("reconcile_selections", 1) in events + assert ("prepare", True, (0, (0,))) in events + assert ("agree_selections", [{"width": 2}]) in events + assert shard_calls == [(1, (0, 1)), (0, (0,)), (1, (0, 1))]