From 1f9eb4c67d9a647bbbf5c25b47e557460efae022 Mon Sep 17 00:00:00 2001 From: Luke Alonso Date: Fri, 4 Dec 2026 08:49:13 -0800 Subject: [PATCH 1/3] feat(heliopause): add unresolved-address diagnostics to export reachability When core export encounters a graph node argument pointing outside every declared allocation, Reachability previously reported only the raw device address. Diagnosing whether an unresolved pointer came from transient warmup storage, an unowned CUDA pool, or a missing buffer declaration required manually tracing kernel arguments back to CUDA graph nodes. What changed: - Added `Reachability::unresolved_report` and supporting node-context reporting in `heliopause/src/export/reachability.rs`, with Rust unit tests covering unresolved pointer diagnostics and transitive closure. - Wired `heliopause/src/export/capture.rs` to format export reachability failures through the structured report. - Updated `docs/runtime-core-design.md` and `docs/TODO.txt` to document the export reachability diagnostic contract. Claimed benefit and measured results: Export-time dangling pointer failures immediately identify the offending graph, kernel, argument offset, and unresolved address instead of failing with an opaque address or deferring to replay-time illegal memory access. Supporting evidence and limitations: - Rust library tests: `cargo test --locked --release --manifest-path heliopause/Cargo.toml --lib` -> 250 passed, 0 failed, 6 ignored (CUDA device tests). Note that `.github/workflows/python-cpu.yml` lines 34-41 already run this test command in CI. - CUDA export verification (`FLARE_RUN_CUDA_TESTS=1`, SM120 GPU 2): `tests/preparation/test_recorded_export_graph_cuda.py` and `tests/preparation/test_capture_cublas_workspace_cuda.py` passed (4/4). - Limitations: ignored CUDA-device unit tests inside `heliopause --lib` were not run directly via cargo. Design-Signed-Off-By: Antigravity; design-review=2e5b Signed-off-by: Luke Alonso --- docs/TODO.txt | 6 + docs/runtime-core-design.md | 10 +- heliopause/src/export/capture.rs | 5 +- heliopause/src/export/reachability.rs | 765 +++++++++++++++++++++++++- 4 files changed, 756 insertions(+), 30 deletions(-) diff --git a/docs/TODO.txt b/docs/TODO.txt index b5e1413f5..2d0297e02 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -377,3 +377,9 @@ [ ] Guard or stride the 65,535 * 1024 (~64 MiB/uint8 row) gridDim.y ceiling in ignition/components/state.py row kernels. + +[ ] Measure the unresolved kernel-argument diagnostic on a four-GPU DeepSeek + V4.1 export (issue #266) and an eight-GPU W4A8 MoE export, recording + per-rank aligned occurrence and distinct-address counts. Close when both + exports have run on four-GPU and eight-GPU hardware and the per-rank + counts and printed per-kernel examples have been reviewed. diff --git a/docs/runtime-core-design.md b/docs/runtime-core-design.md index a79e26df5..c1fde53bf 100644 --- a/docs/runtime-core-design.md +++ b/docs/runtime-core-design.md @@ -163,7 +163,11 @@ conversions, inline assembly, or opaque calls retain conservative argument scanning. Untyped structs, tensor maps, globals, and integer/byte storage without a numeric role are scanned for address candidates. This can retain false positives and retains complete backing segments, including unused bytes within -a reachable segment. The preparation metadata does not enter the serving index. +a reachable segment. Argument-relative 8-byte-aligned kernel-argument values +inside the recorded address envelope that resolve to no active recorded +allocation (a gap between allocations or an inactive range) are reported on +stderr per rank as a non-blocking diagnostic without retaining inactive storage. +The preparation metadata does not enter the serving index. Omitted arena allocations keep their virtual ranges reserved and physically unmapped, so an unexpected access faults instead of reaching another allocation. @@ -356,7 +360,9 @@ compresses, hashes, and syncs each rank's archive before publication. Native stderr rows omit the Flare banner. Rank-zero capture reports storage clearing, graph inspection and serialization, module/global capture, storage scans, -weight materialization, and frontend assets. Coordinators report export peer waits, +weight materialization, and frontend assets. Each rank also writes a bounded +stderr summary when kernel-argument reachability scanning finds aligned +unresolved address candidates. Coordinators report export peer waits, rank transfers, and preparation-resource release before publication. Publication reports payload assembly, validation, frontend verification, each rank's executable compression and installation, each rank's data verification and diff --git a/heliopause/src/export/capture.rs b/heliopause/src/export/capture.rs index e1224a177..2768ecc2d 100644 --- a/heliopause/src/export/capture.rs +++ b/heliopause/src/export/capture.rs @@ -3379,7 +3379,7 @@ pub(crate) fn capture_rank( &indices, &request.events, )?; - reach.graph(&nodes, &kernels)?; + reach.graph(&graph.name, &nodes, &kernels)?; let file = format!("graph-{index}.bin"); let path = stage.path.join(&file); let mut writer = BufWriter::new(File::create(&path)?); @@ -3414,6 +3414,9 @@ pub(crate) fn capture_rank( "{} graphs, {graph_bytes} bytes", request.graphs.len() )); + for line in reach.unresolved_report(&output.index.ranks[0].functions) { + eprintln!("export: rank {}: {line}", request.rank); + } let module_phase = progress.phase("Capture compiled modules and globals", None); let mut module_bytes = 0u64; let mut downloader = Downloader::new(&cuda)?; diff --git a/heliopause/src/export/reachability.rs b/heliopause/src/export/reachability.rs index 2409f9836..326e66919 100644 --- a/heliopause/src/export/reachability.rs +++ b/heliopause/src/export/reachability.rs @@ -42,6 +42,39 @@ pub(crate) fn subtract_ranges(start: u64, end: u64, excluded: &[(u64, u64)]) -> spans } +/// An 8-byte-aligned kernel argument value inside the recorded address envelope +/// that resolves to no active recorded allocation (a gap between allocations or +/// an inactive range). Such a value may be a stale pointer or a numeric constant; +/// argument typing cannot yet distinguish the two, so export reports these for +/// operator review. +pub(crate) struct UnresolvedCandidate { + pub graph: String, + pub node: usize, + pub function: usize, + pub argument: usize, + pub offset: usize, +} + +struct UnresolvedEntry { + first: UnresolvedCandidate, + order: usize, + occurrences: usize, +} + +/// The call site a kernel argument blob was scanned for. Every occurrence of +/// the same argument bytes is recorded separately so a report can name the +/// graph, node, kernel, and parameter that carried an unresolved candidate. +pub(crate) struct Site<'a> { + pub graph: &'a str, + pub node: usize, + pub function: usize, + pub argument: usize, +} + +/// The number of distinct addresses shown in a rank's report. The examples +/// retain the first call site for each address in graph and node order. +const UNRESOLVED_EXAMPLES: usize = 10; + pub(crate) struct Reachability { allocations: HashMap, intervals: Vec<(u64, u64, String)>, @@ -49,7 +82,8 @@ pub(crate) struct Reachability { inactive: Vec<(u64, u64)>, pub(crate) reached: HashSet, pending: VecDeque, - blobs: HashSet<(Vec, Vec<(usize, usize)>)>, + blobs: HashMap<(Vec, Vec<(usize, usize)>), Vec<(usize, u64)>>, + unresolved: HashMap, tail: Option<(String, u64, Vec)>, } @@ -74,7 +108,8 @@ impl Reachability { inactive: merge_ranges(inactive.to_vec()), reached: HashSet::new(), pending: VecDeque::new(), - blobs: HashSet::new(), + blobs: HashMap::new(), + unresolved: HashMap::new(), tail: None, }; this.intervals.sort_unstable(); @@ -124,10 +159,13 @@ impl Reachability { Ok(()) } - pub(crate) fn pointer(&mut self, value: u64) -> ExportResult<()> { + /// Retains the live recorded allocation containing `value`. Returns `true` + /// only when `value` resolves to a live allocation; inactive ranges and + /// gaps between allocations both return `false` without retaining storage. + fn candidate(&mut self, value: u64) -> ExportResult { let inactive = self.inactive.partition_point(|&(start, _)| start <= value); if inactive > 0 && value < self.inactive[inactive - 1].1 { - return Ok(()); + return Ok(false); } let index = self .intervals @@ -135,12 +173,39 @@ impl Reachability { if index > 0 && value < self.intervals[index - 1].1 { let name = self.intervals[index - 1].2.clone(); self.reference(&name)?; + return Ok(true); + } + Ok(false) + } + + fn record_unresolved( + unresolved: &mut HashMap, + misses: &[(usize, u64)], + site: &Site, + ) { + for &(offset, address) in misses { + let order = unresolved.len(); + unresolved + .entry(address) + .and_modify(|entry| entry.occurrences += 1) + .or_insert_with(|| UnresolvedEntry { + first: UnresolvedCandidate { + graph: site.graph.to_owned(), + node: site.node, + function: site.function, + argument: site.argument, + offset, + }, + order, + occurrences: 1, + }); } - Ok(()) } - pub(crate) fn blob(&mut self, data: &[u8], numeric: &[(usize, usize)]) -> ExportResult<()> { - if !self.blobs.insert((data.to_vec(), numeric.to_vec())) { + fn blob(&mut self, data: &[u8], numeric: &[(usize, usize)], site: &Site) -> ExportResult<()> { + let key = (data.to_vec(), numeric.to_vec()); + if let Some(misses) = self.blobs.get(&key) { + Self::record_unresolved(&mut self.unresolved, misses, site); return Ok(()); } let excluded = merge_ranges( @@ -149,30 +214,148 @@ impl Reachability { .map(|&(start, end)| (start as u64, end as u64)) .collect(), ); + let mut misses = Vec::new(); for (start, end) in subtract_ranges(0, data.len() as u64, &excluded) { - self.scan(&data[start as usize..end as usize])?; + self.scan( + &data[start as usize..end as usize], + start as usize, + Some(&mut misses), + )?; } + Self::record_unresolved(&mut self.unresolved, &misses, site); + self.blobs.insert(key, misses); Ok(()) } - fn scan(&mut self, data: &[u8]) -> ExportResult<()> { + pub(crate) fn unresolved_count(&self) -> usize { + self.unresolved + .values() + .map(|entry| entry.occurrences) + .sum() + } + + pub(crate) fn unresolved_unique_addresses(&self) -> usize { + self.unresolved.len() + } + + /// Lines describing the unresolved candidates: a summary line, one line per + /// distinct address up to the example limit (prioritizing one example per + /// distinct kernel symbol before backfilling in encounter order), and a + /// trailing line when more distinct addresses were recorded than shown. The + /// caller supplies the recorded functions and adds the export prefix. + pub(crate) fn unresolved_report(&self, functions: &[wire::Function]) -> Vec { + let mut lines = Vec::new(); + let occurrences = self.unresolved_count(); + if occurrences == 0 { + return lines; + } + lines.push(format!( + "kernel argument scan: {} and {} fall inside the recorded address envelope but \ + resolve to no active recorded allocation (gap or inactive range), so each may be a \ + stale pointer or a numeric constant", + with_count(occurrences, "occurrence", "occurrences"), + with_count( + self.unresolved_unique_addresses(), + "distinct address", + "distinct addresses" + ), + )); + let mut examples: Vec<_> = self.unresolved.iter().collect(); + examples.sort_unstable_by_key(|(_, entry)| entry.order); + let limit = UNRESOLVED_EXAMPLES.min(examples.len()); + let mut selected = Vec::with_capacity(limit); + let mut chosen = vec![false; examples.len()]; + let mut seen_symbols = HashSet::with_capacity(limit); + for (index, &(_, entry)) in examples.iter().enumerate() { + if selected.len() == limit { + break; + } + let symbol_key = functions + .get(entry.first.function) + .map_or(Err(entry.first.function), |function| { + Ok(function.symbol.as_str()) + }); + if seen_symbols.insert(symbol_key) { + selected.push(index); + chosen[index] = true; + } + } + for (index, already) in chosen.iter().enumerate() { + if selected.len() == limit { + break; + } + if !already { + selected.push(index); + } + } + selected.sort_unstable(); + let mut shown_occurrences = 0usize; + for index in &selected { + let (address, entry) = examples[*index]; + let address = *address; + shown_occurrences += entry.occurrences; + let candidate = &entry.first; + let function = functions.get(candidate.function); + lines.push(format!( + " graph {:?} node {} kernel {} ({}), argument {}, offset {}: {address:#x} ({})", + candidate.graph, + candidate.node, + function.map_or("unknown", |function| function.symbol.as_str()), + function.map_or("unknown", |function| function.module.as_str()), + candidate.argument, + candidate.offset, + with_count(entry.occurrences, "occurrence", "occurrences"), + )); + } + if examples.len() > selected.len() { + let hidden_addresses = examples.len() - selected.len(); + let hidden_occurrences = occurrences - shown_occurrences; + lines.push(format!( + " … {} ({}) not shown", + with_count( + hidden_addresses, + "more distinct address", + "more distinct addresses" + ), + with_count(hidden_occurrences, "occurrence", "occurrences"), + )); + } + lines + } + + fn scan( + &mut self, + data: &[u8], + base: usize, + mut misses: Option<&mut Vec<(usize, u64)>>, + ) -> ExportResult<()> { if self.intervals.is_empty() { return Ok(()); } let floor = self.intervals[0].0; let ceiling = self.intervals.last().unwrap().1; - for bytes in data.windows(8) { + for (offset, bytes) in data.windows(8).enumerate() { let pointer = u64::from_le_bytes(bytes.try_into().unwrap()); - if pointer >= floor && pointer < ceiling { - self.pointer(pointer)?; + if pointer >= floor + && pointer < ceiling + && !self.candidate(pointer)? + && let Some(misses) = misses.as_deref_mut() + && (base + offset).is_multiple_of(8) + { + misses.push((base + offset, pointer)); } } Ok(()) } - pub(crate) fn graph(&mut self, nodes: &[wire::Node], kernels: &[Kernel]) -> ExportResult<()> { + pub(crate) fn graph( + &mut self, + name: &str, + nodes: &[wire::Node], + kernels: &[Kernel], + ) -> ExportResult<()> { use wire::node::Operation; - for node in nodes { + for (node_index, node) in nodes.iter().enumerate() { match node .operation .as_ref() @@ -185,7 +368,9 @@ impl Reachability { if node.arguments.len() != kernel.arguments.len() { return Err(invalid("kernel argument count differs from its function")); } - for (blob, argument) in node.arguments.iter().zip(&kernel.arguments) { + for (position, (blob, argument)) in + node.arguments.iter().zip(&kernel.arguments).enumerate() + { for relocation in &blob.relocations { self.reference( &relocation @@ -195,7 +380,16 @@ impl Reachability { .allocation, )?; } - self.blob(&blob.data, &argument.numeric)?; + self.blob( + &blob.data, + &argument.numeric, + &Site { + graph: name, + node: node_index, + function: node.function as usize, + argument: position, + }, + )?; } for attribute in &node.attributes { if let Some(value) = &attribute.value { @@ -248,11 +442,15 @@ impl Reachability { .checked_add(data.len() as u64) .ok_or_else(|| invalid("allocation scan extent overflow"))?; for (start, stop) in subtract_ranges(address, end, &self.numeric) { - self.scan(&data[(start - address) as usize..(stop - address) as usize])?; + self.scan( + &data[(start - address) as usize..(stop - address) as usize], + 0, + None, + )?; } Ok(()) } else { - self.scan(data) + self.scan(data, 0, None) } } @@ -329,6 +527,14 @@ impl Reachability { } } +fn with_count(count: usize, one: &str, many: &str) -> String { + if count == 1 { + format!("1 {one}") + } else { + format!("{count} {many}") + } +} + #[cfg(test)] mod tests { use super::*; @@ -439,7 +645,7 @@ mod tests { let allocations = [allocation("target", 0x2000)]; let mut reach = Reachability::new(&allocations, &[], &[], &[]).unwrap(); let bytes = [0x2000u64.to_le_bytes(), 0x2000u64.to_le_bytes()].concat(); - reach.blob(&bytes, &[(0, 8)]).unwrap(); + reach.blob(&bytes, &[(0, 8)], &SITE).unwrap(); assert!(reach.reached.contains("target")); } @@ -491,8 +697,8 @@ mod tests { let bytes = target.address.to_le_bytes(); let mut reach = Reachability::new(&[source.clone(), target.clone()], &[], &[], &[]).unwrap(); - reach.blob(&bytes[..4], &[]).unwrap(); - reach.blob(&bytes[4..], &[]).unwrap(); + reach.blob(&bytes[..4], &[], &SITE).unwrap(); + reach.blob(&bytes[4..], &[], &SITE).unwrap(); reach.contents(&source, 0, &bytes[..4]).unwrap(); reach.contents(&source, 128, &bytes[4..]).unwrap(); assert!(reach.reached.is_empty()); @@ -500,6 +706,7 @@ mod tests { .blob( &[b"abc".as_slice(), bytes.as_slice(), b"xyz".as_slice()].concat(), &[], + &SITE, ) .unwrap(); assert_eq!(reach.reached, HashSet::from([target.name])); @@ -542,6 +749,7 @@ mod tests { let mut reach = Reachability::new(&[scalar.clone(), input.clone()], &[], &[], &[]).unwrap(); reach .graph( + "graph", &[wire::Node { operation: Some(wire::node::Operation::Kernel(node.clone())), }], @@ -552,6 +760,7 @@ mod tests { node.arguments[1].data = node.arguments[0].data.clone(); reach .graph( + "graph", &[wire::Node { operation: Some(wire::node::Operation::Kernel(node)), }], @@ -561,8 +770,481 @@ mod tests { assert_eq!(reach.reached, HashSet::from([input.name, scalar.name])); } + fn kernel_graph(argument_data: &[u8], numeric: Vec<(usize, usize)>) -> (wire::Node, Kernel) { + let kernel = Kernel { + function: 1, + module: "module".into(), + arguments: vec![super::super::Argument { + size: argument_data.len(), + relocations: vec![], + numeric, + }], + }; + let node = wire::Node { + operation: Some(wire::node::Operation::Kernel(wire::Kernel { + function: 0, + arguments: vec![wire::Blob { + data: argument_data.to_vec(), + relocations: vec![], + }], + ..Default::default() + })), + }; + (node, kernel) + } + + const SITE: Site = Site { + graph: "graph", + node: 0, + function: 0, + argument: 0, + }; + + fn first(reach: &Reachability, address: u64) -> &UnresolvedCandidate { + &reach.unresolved[&address].first + } + + #[test] + fn kernel_argument_gap_candidate_is_reported_with_site_context() { + let low = allocation("low", 0x2000); + let high = allocation("high", 0x4000); + let (node, kernel) = kernel_graph(&0x3008u64.to_le_bytes(), vec![]); + let mut reach = Reachability::new(&[low, high], &[], &[], &[]).unwrap(); + reach.graph("prefill-4096", &[node], &[kernel]).unwrap(); + assert_eq!(reach.unresolved_count(), 1); + assert_eq!(reach.unresolved.len(), 1); + let candidate = first(&reach, 0x3008); + assert_eq!(candidate.graph, "prefill-4096"); + assert_eq!(candidate.node, 0); + assert_eq!(candidate.function, 0); + assert_eq!(candidate.argument, 0); + assert_eq!(candidate.offset, 0); + assert_eq!(reach.unresolved_unique_addresses(), 1); + } + + #[test] + fn unresolved_records_every_distinct_address_in_encounter_order() { + let low = allocation("low", 0x2000); + let high = allocation("high", 0x4000); + let data: Vec = (0..12u64) + .flat_map(|index| (0x3000 + 8 * index).to_le_bytes()) + .collect(); + let (node, kernel) = kernel_graph(&data, vec![]); + let mut reach = Reachability::new(&[low, high], &[], &[], &[]).unwrap(); + reach.graph("graph", &[node], &[kernel]).unwrap(); + assert_eq!(reach.unresolved_count(), 12); + assert_eq!(reach.unresolved.len(), 12); + assert_eq!(reach.unresolved_unique_addresses(), 12); + for index in 0..12 { + let address = 0x3000 + 8 * index as u64; + assert_eq!(first(&reach, address).graph, "graph"); + assert_eq!(first(&reach, address).offset, 8 * index); + assert_eq!(reach.unresolved[&address].order, index); + assert_eq!(reach.unresolved[&address].occurrences, 1); + } + } + + #[test] + fn kernel_argument_candidate_offset_counts_from_the_argument_start() { + let low = allocation("low", 0x2000); + let high = allocation("high", 0x4000); + let data = [ + 0x3008u64.to_le_bytes().as_slice(), + &[0u8; 8], + 0x3010u64.to_le_bytes().as_slice(), + ] + .concat(); + let (node, kernel) = kernel_graph(&data, vec![(0, 8)]); + let mut reach = Reachability::new(&[low, high], &[], &[], &[]).unwrap(); + reach.graph("graph", &[node], &[kernel]).unwrap(); + assert_eq!(reach.unresolved_count(), 1); + let candidate = first(&reach, 0x3010); + assert_eq!(candidate.offset, 16); + assert_eq!(candidate.argument, 0); + assert_eq!(candidate.node, 0); + } + #[test] - fn freed_interval_boundaries_exclude_candidates_but_not_explicit_bindings() { + fn shared_argument_bytes_record_one_example_per_address() { + let low = allocation("low", 0x2000); + let high = allocation("high", 0x4000); + let (node, kernel) = kernel_graph(&0x3008u64.to_le_bytes(), vec![]); + let mut reach = Reachability::new(&[low, high], &[], &[], &[]).unwrap(); + reach + .graph("graph-a", &[node.clone()], &[kernel.clone()]) + .unwrap(); + reach.graph("graph-b", &[node], &[kernel]).unwrap(); + assert_eq!(reach.unresolved_count(), 2); + assert_eq!(reach.unresolved.len(), 1); + assert_eq!(first(&reach, 0x3008).graph, "graph-a"); + assert_eq!(reach.unresolved[&0x3008].occurrences, 2); + assert_eq!(reach.unresolved_unique_addresses(), 1); + } + + #[test] + fn unresolved_report_names_the_kernel_and_its_symbol() { + let low = allocation("low", 0x2000); + let high = allocation("high", 0x4000); + let (node, kernel) = kernel_graph(&0x3008u64.to_le_bytes(), vec![]); + let mut reach = Reachability::new(&[low, high], &[], &[], &[]).unwrap(); + reach.graph("prefill-8192", &[node], &[kernel]).unwrap(); + let functions = vec![ + wire::Function { + module: "module".into(), + symbol: "cublasLt::splitKreduce_kernel".into(), + parameter_sizes: vec![8], + attributes: vec![], + }, + wire::Function { + module: "wrong-module".into(), + symbol: "wrong-symbol".into(), + parameter_sizes: vec![8], + attributes: vec![], + }, + ]; + assert_eq!( + reach.unresolved_report(&functions), + vec![ + "kernel argument scan: 1 occurrence and 1 distinct address fall inside the \ + recorded address envelope but resolve to no active recorded allocation (gap or \ + inactive range), so each may be a stale pointer or a numeric constant" + .to_owned(), + " graph \"prefill-8192\" node 0 kernel cublasLt::splitKreduce_kernel (module), \ + argument 0, offset 0: 0x3008 (1 occurrence)" + .to_owned(), + ] + ); + } + + #[test] + fn unresolved_report_bounds_examples_and_counts_hidden_occurrences() { + let low = allocation("low", 0x2000); + let high = allocation("high", 0x4000); + let data: Vec = (0..12u64) + .rev() + .flat_map(|index| (0x3000 + 8 * index).to_le_bytes()) + .collect(); + let (node, kernel) = kernel_graph(&data, vec![]); + let mut reach = Reachability::new(&[low, high], &[], &[], &[]).unwrap(); + reach + .graph("graph-a", &[node.clone()], &[kernel.clone()]) + .unwrap(); + reach.graph("graph-b", &[node], &[kernel]).unwrap(); + let lines = reach.unresolved_report(&[]); + assert_eq!(lines.len(), 12); + assert_eq!( + lines[0], + "kernel argument scan: 24 occurrences and 12 distinct addresses fall inside the \ + recorded address envelope but resolve to no active recorded allocation (gap or \ + inactive range), so each may be a stale pointer or a numeric constant" + ); + assert!(lines[1].contains("graph \"graph-a\" node 0 kernel unknown (unknown)")); + assert!(lines[1].ends_with("0x3058 (2 occurrences)")); + assert!(lines[10].ends_with("0x3010 (2 occurrences)")); + assert_eq!( + lines[11], + " … 2 more distinct addresses (4 occurrences) not shown" + ); + } + + #[test] + fn unresolved_report_omits_hidden_line_when_all_distinct_addresses_are_shown() { + let low = allocation("low", 0x2000); + let high = allocation("high", 0x4000); + + let (single_node, single_kernel) = kernel_graph(&0x3008u64.to_le_bytes(), vec![]); + let mut single = Reachability::new(&[low.clone(), high.clone()], &[], &[], &[]).unwrap(); + for index in 0..5 { + single + .graph( + &format!("graph-{index}"), + &[single_node.clone()], + &[single_kernel.clone()], + ) + .unwrap(); + } + let single_lines = single.unresolved_report(&[]); + assert_eq!(single_lines.len(), 2); + assert!(single_lines[1].ends_with("0x3008 (5 occurrences)")); + assert!(single_lines.iter().all(|line| !line.contains("not shown"))); + + let ten_data: Vec = (0..10u64) + .flat_map(|index| (0x3000 + 8 * index).to_le_bytes()) + .collect(); + let (ten_node, ten_kernel) = kernel_graph(&ten_data, vec![]); + let mut ten = Reachability::new(&[low, high], &[], &[], &[]).unwrap(); + ten.graph("graph-a", &[ten_node.clone()], &[ten_kernel.clone()]) + .unwrap(); + ten.graph("graph-b", &[ten_node], &[ten_kernel]).unwrap(); + let ten_lines = ten.unresolved_report(&[]); + assert_eq!(ten_lines.len(), 11); + for line in &ten_lines[1..11] { + assert!(line.ends_with("(2 occurrences)"), "line was: {line}"); + } + assert!(ten_lines.iter().all(|line| !line.contains("not shown"))); + } + + #[test] + fn unresolved_report_hidden_line_sums_omitted_address_occurrences() { + let low = allocation("low", 0x2000); + let high = allocation("high", 0x4000); + let mut reach = Reachability::new(&[low, high], &[], &[], &[]).unwrap(); + let ten_data: Vec = (0..10u64) + .flat_map(|index| (0x3000 + 8 * index).to_le_bytes()) + .collect(); + let (ten_node, ten_kernel) = kernel_graph(&ten_data, vec![]); + for index in 0..3 { + reach + .graph( + &format!("head-{index}"), + &[ten_node.clone()], + &[ten_kernel.clone()], + ) + .unwrap(); + } + let (eleventh_node, eleventh_kernel) = kernel_graph(&0x3050u64.to_le_bytes(), vec![]); + reach + .graph("tail-one", &[eleventh_node], &[eleventh_kernel]) + .unwrap(); + let (twelfth_node, twelfth_kernel) = kernel_graph(&0x3058u64.to_le_bytes(), vec![]); + for index in 0..4 { + reach + .graph( + &format!("tail-four-{index}"), + &[twelfth_node.clone()], + &[twelfth_kernel.clone()], + ) + .unwrap(); + } + let lines = reach.unresolved_report(&[]); + assert_eq!(lines.len(), 12); + assert!( + lines[0].starts_with("kernel argument scan: 35 occurrences and 12 distinct addresses") + ); + assert!(lines[1].ends_with("(3 occurrences)")); + assert!(lines[10].ends_with("(3 occurrences)")); + assert_eq!( + lines[11], + " … 2 more distinct addresses (5 occurrences) not shown" + ); + } + + #[test] + fn unresolved_report_is_empty_without_candidates() { + let reach = Reachability::new(&[allocation("only", 0x2000)], &[], &[], &[]).unwrap(); + assert!(reach.unresolved_report(&[]).is_empty()); + } + + #[test] + fn unresolved_report_prioritizes_distinct_kernel_symbols_before_backfilling() { + let low = allocation("low", 0x2000); + let high = allocation("high", 0x4000); + let make_fn = |name: &str, module: &str| wire::Function { + module: module.into(), + symbol: name.into(), + parameter_sizes: vec![], + attributes: vec![], + }; + let make_node_kernel = |function: usize, data: Vec| { + let size = data.len(); + ( + wire::Node { + operation: Some(wire::node::Operation::Kernel(wire::Kernel { + function: function as u64, + arguments: vec![wire::Blob { + data, + relocations: vec![], + }], + ..Default::default() + })), + }, + Kernel { + function, + module: format!("mod-{function}"), + arguments: vec![super::super::Argument { + size, + relocations: vec![], + numeric: vec![], + }], + }, + ) + }; + + let a_data: Vec = (0..10u64) + .flat_map(|index| (0x3000 + 8 * index).to_le_bytes()) + .collect(); + let b_data: Vec = (0..2u64) + .flat_map(|index| (0x3100 + 8 * index).to_le_bytes()) + .collect(); + let (node_a, kernel_a) = make_node_kernel(0, a_data); + let (node_b, kernel_b) = make_node_kernel(1, b_data); + let kernels = vec![kernel_a, kernel_b]; + + let mut two_sym = Reachability::new(&[low.clone(), high.clone()], &[], &[], &[]).unwrap(); + two_sym + .graph("g-a-0", std::slice::from_ref(&node_a), &kernels) + .unwrap(); + two_sym.graph("g-a-1", &[node_a], &kernels).unwrap(); + for idx in 0..3 { + two_sym + .graph( + &format!("g-b-{idx}"), + std::slice::from_ref(&node_b), + &kernels, + ) + .unwrap(); + } + let functions = vec![make_fn("kernel_a", "mod_a"), make_fn("kernel_b", "mod_b")]; + let lines = two_sym.unresolved_report(&functions); + assert_eq!(lines.len(), 12); + assert!( + lines[0].starts_with("kernel argument scan: 26 occurrences and 12 distinct addresses") + ); + assert!(lines.iter().any(|line| { + line.contains("kernel kernel_b (mod_b)") && line.contains("0x3100 (3 occurrences)") + })); + assert!( + lines[1..11] + .iter() + .all(|line| !line.contains("0x3048") && !line.contains("0x3108")) + ); + assert_eq!( + lines[11], + " … 2 more distinct addresses (5 occurrences) not shown" + ); + + let mut many_sym = Reachability::new(&[low, high], &[], &[], &[]).unwrap(); + let mut many_nodes = Vec::with_capacity(12); + let mut many_kernels = Vec::with_capacity(12); + let mut many_functions = Vec::with_capacity(12); + for sym_idx in 0..12usize { + let bytes = (0x3000 + 8 * sym_idx as u64).to_le_bytes().to_vec(); + let (node, kernel) = make_node_kernel(sym_idx, bytes); + many_nodes.push(node); + many_kernels.push(kernel); + many_functions.push(make_fn( + &format!("sym_{sym_idx:02}"), + &format!("mod_{sym_idx:02}"), + )); + } + many_sym + .graph("all-unique", &many_nodes, &many_kernels) + .unwrap(); + let many_lines = many_sym.unresolved_report(&many_functions); + assert_eq!(many_lines.len(), 12); + for (idx, line) in many_lines[1..11].iter().enumerate() { + assert!( + line.contains(&format!("kernel sym_{idx:02} (mod_{idx:02})")), + "line {idx}: {line}" + ); + } + assert!( + many_lines[1..11] + .iter() + .all(|line| !line.contains("sym_10") && !line.contains("sym_11")) + ); + assert_eq!( + many_lines[11], + " … 2 more distinct addresses (2 occurrences) not shown" + ); + } + + #[test] + fn kernel_argument_boundaries_and_external_values_follow_the_recorded_contract() { + let low = allocation("low", 0x2000); + let high = allocation("high", 0x4000); + for (value, reported) in [ + (low.address, false), + (low.address + 255, false), + (low.address + 256, true), + (high.address - 1, true), + (high.address, false), + (0x1000, false), + (high.address + 256, false), + ] { + let (node, kernel) = kernel_graph(&value.to_le_bytes(), vec![]); + let mut reach = Reachability::new(&[low.clone(), high.clone()], &[], &[], &[]).unwrap(); + reach.graph("graph", &[node], &[kernel]).unwrap(); + assert_eq!( + reach.unresolved.contains_key(&value), + reported, + "value {value:#x}" + ); + } + } + + #[test] + fn kernel_argument_inactive_ranges_are_reported_but_numeric_ranges_stay_lenient() { + let low = allocation("low", 0x2000); + let high = allocation("high", 0x4000); + let (node, kernel) = kernel_graph(&0x3008u64.to_le_bytes(), vec![]); + let mut reach = + Reachability::new(&[low.clone(), high.clone()], &[], &[(0x3000, 0x3100)], &[]).unwrap(); + reach.graph("graph", &[node], &[kernel]).unwrap(); + assert_eq!(reach.unresolved_count(), 1); + assert!(reach.unresolved.contains_key(&0x3008)); + let (node, kernel) = kernel_graph(&0x3008u64.to_le_bytes(), vec![(0, 8)]); + let mut reach = Reachability::new(&[low, high], &[], &[], &[]).unwrap(); + reach.graph("graph", &[node], &[kernel]).unwrap(); + assert!(reach.unresolved.is_empty()); + } + + #[test] + fn allocation_contents_still_tolerate_gap_candidates() { + let low = allocation("low", 0x2000); + let high = allocation("high", 0x4000); + let mut reach = Reachability::new(&[low.clone(), high], &[], &[], &[]).unwrap(); + reach.contents(&low, 0, &0x3008u64.to_le_bytes()).unwrap(); + assert!(reach.reached.is_empty()); + assert!(reach.unresolved.is_empty()); + } + + #[test] + fn unaligned_straddling_window_is_not_reported_while_aligned_stale_pointer_is() { + let low = allocation("low", 0x0000_0800_0000_0000); + let high = allocation("high", 0x0000_2000_0000_0000); + let small = 0x0000_1000u64; + let stale = 0x0000_1800_0000_0000u64; + let data = [ + low.address.to_le_bytes().as_slice(), + small.to_le_bytes().as_slice(), + stale.to_le_bytes().as_slice(), + ] + .concat(); + let straddling = u64::from_le_bytes(data[4..12].try_into().unwrap()); + assert_eq!(straddling, 0x0000_1000_0000_0800); + assert!(straddling >= low.address + low.nbytes && straddling < high.address); + let (node, kernel) = kernel_graph(&data, vec![]); + let mut reach = Reachability::new(&[low, high], &[], &[], &[]).unwrap(); + reach.graph("prefill4096", &[node], &[kernel]).unwrap(); + assert!(reach.reached.contains("low")); + assert!(!reach.unresolved.contains_key(&straddling)); + assert!(reach.unresolved.contains_key(&stale)); + assert_eq!(first(&reach, stale).offset, 16); + assert_eq!(reach.unresolved_count(), 1); + assert_eq!(reach.unresolved_unique_addresses(), 1); + } + + #[test] + fn aligned_reporting_checks_argument_relative_offset_after_unaligned_numeric_prefix() { + let low = allocation("low", 0x2000); + let high = allocation("high", 0x0001_0000_0000_0000); + let data = [[0u8; 8].as_slice(), 0x3008u64.to_le_bytes().as_slice()].concat(); + let straddling = u64::from_le_bytes(data[4..12].try_into().unwrap()); + assert_eq!(straddling, 0x0000_3008_0000_0000); + assert!(straddling >= low.address + low.nbytes && straddling < high.address); + let (node, kernel) = kernel_graph(&data, vec![(0, 4)]); + let mut reach = Reachability::new(&[low, high], &[], &[], &[]).unwrap(); + reach.graph("prefill4096", &[node], &[kernel]).unwrap(); + assert_eq!(reach.unresolved_count(), 1); + assert_eq!(reach.unresolved_unique_addresses(), 1); + assert!(!reach.unresolved.contains_key(&straddling)); + assert!(reach.unresolved.contains_key(&0x3008)); + assert_eq!(first(&reach, 0x3008).offset, 8); + } + + #[test] + fn freed_interval_boundaries_report_kernel_candidates_without_retaining_storage() { let mut storage = allocation("segment", 0x200000000000); storage.nbytes = 4096; for (offset, retained) in [ @@ -573,14 +1255,14 @@ mod tests { (3071, false), (3072, true), ] { - let mut reach = Reachability::new( + let mut unaligned = Reachability::new( &[storage.clone()], &[], &[(storage.address + 1024, storage.address + 3072)], &[], ) .unwrap(); - reach + unaligned .blob( &[ b"unaligned".as_slice(), @@ -588,11 +1270,40 @@ mod tests { ] .concat(), &[], + &SITE, ) .unwrap(); - assert_eq!(!reach.reached.is_empty(), retained); - reach.reference(&storage.name).unwrap(); - assert!(reach.reached.contains(&storage.name)); + assert_eq!(!unaligned.reached.is_empty(), retained); + assert!(unaligned.unresolved.is_empty()); + + let mut aligned = Reachability::new( + &[storage.clone()], + &[], + &[(storage.address + 1024, storage.address + 3072)], + &[], + ) + .unwrap(); + aligned + .blob( + &[ + [0u8; 8].as_slice(), + (storage.address + offset).to_le_bytes().as_slice(), + ] + .concat(), + &[], + &SITE, + ) + .unwrap(); + assert_eq!(!aligned.reached.is_empty(), retained); + assert_eq!( + aligned.unresolved.contains_key(&(storage.address + offset)), + !retained, + ); + if !retained { + assert_eq!(first(&aligned, storage.address + offset).offset, 8); + } + aligned.reference(&storage.name).unwrap(); + assert!(aligned.reached.contains(&storage.name)); } } From d13d649f4ab0b5bd32a3bf13c06bd84caff0f62a Mon Sep 17 00:00:00 2001 From: Luke Alonso Date: Fri, 4 Dec 2026 08:49:13 -0800 Subject: [PATCH 2/3] fix(capture): own export warmup cuBLAS pool in CoreStorage and seed auxiliary streams `capture.py` previously seeded warmup-stream cuBLAS workspaces into an unowned module-level `torch.cuda.MemPool()`, outside `CoreStorage` mappings, and did not seed auxiliary overlap streams before warmups. If a warmup-stream or auxiliary-stream cuBLAS workspace lands in transient warmup storage or outside declared export mappings, graph capture and native replay can reference unmapped or undeclared device addresses. What changed: - Added `CoreStorage.warmup_pool()` in `ignition/preparation/core_storage.py` to lazily create one persistent `torch.cuda.MemPool` backed by `CoreStorage`'s allocator and registered in `_preparation_pools`. - Updated `_seed_warmup_workspaces(stream, device, pool=None)` and `capture_forwards` in `ignition/preparation/capture.py` to seed the warmup stream (`mm` and `addmm`) into `warmup_storage.warmup_pool()` when provided, keeping the 2-argument module-pool path for non-export callers. - Added `_seed_auxiliary_workspaces(session, device, *, warmup_storage)` in `ignition/preparation/capture.py` to seed an auxiliary scratch-arena stream's `mm`, `addmm`, and `bmm` cuBLAS workspaces inside `warmup_storage.graph_pool` before warmups and capture. - Updated `docs/preparation-development.md` and added CPU/CUDA tests in `tests/preparation/test_core_storage.py`, `tests/preparation/test_capture_cublas_workspace_cuda.py`, and `tests/preparation/test_capture_stream_isolation.py`. Claimed benefit and measured results: Export-mode cuBLAS warmup workspaces stay inside declared `CoreStorage` mappings while remaining disjoint from transient and graph pools, and auxiliary overlap streams bind persistent graph-pool workspaces across warmup, capture, and native replay. Supporting evidence and limitations: - CPU tests: `tests/preparation/test_core_storage.py` (18 passed, 1 Windows-only skipped) and `tests/preparation/test_capture_stream_isolation.py` (3 passed). - CUDA tests (`FLARE_RUN_CUDA_TESTS=1`, RTX PRO 6000 Blackwell SM120): `tests/preparation/test_capture_cublas_workspace_cuda.py` passed in both forward (GPU 2) and reversed (GPU 3) test orders (2/2), verifying the seeded warmup workspace resides inside `CoreStorage.mappings`, leaves `_capture._warmup_pools` empty, and passes full `RuntimeCore.write()` export reachability. - Limitations: multi-rank export with a live auxiliary overlap model graph was not benchmarked end-to-end here. Design-Signed-Off-By: Antigravity; design-review=2e5b Signed-off-by: Luke Alonso --- docs/preparation-development.md | 5 +- ignition/preparation/capture.py | 52 ++++++- ignition/preparation/core_storage.py | 12 ++ .../test_capture_cublas_workspace_cuda.py | 134 ++++++++++++++++++ .../test_capture_stream_isolation.py | 45 ++++++ tests/preparation/test_core_storage.py | 25 ++++ 6 files changed, 265 insertions(+), 8 deletions(-) diff --git a/docs/preparation-development.md b/docs/preparation-development.md index e877cd20a..0da40a7bd 100644 --- a/docs/preparation-development.md +++ b/docs/preparation-development.md @@ -88,7 +88,10 @@ before the session's capture guard forbids further kernel resolution. When `capture_forwards` receives `warmup_storage`, the preparation's `CoreStorage` (`ignition/preparation/core_storage.py`), eager warmups allocate from its transient pools and release them before capture, so - their workspaces do not coexist with retained graph intermediates. Ranks + their workspaces do not coexist with retained graph intermediates, while + cuBLAS warmup workspaces are seeded into `CoreStorage.warmup_pool()` so they + stay outside transient and graph pools while remaining inside declared core + mappings. Ranks synchronize before each warmup and each capture. Retain compiled kernel owners until native replay has drained. Compiled forwards retain Inductor memory-pool planning, storage reuse, and default peak-memory operation reordering; callers diff --git a/ignition/preparation/capture.py b/ignition/preparation/capture.py index 9b1614f20..f71133b12 100644 --- a/ignition/preparation/capture.py +++ b/ignition/preparation/capture.py @@ -50,22 +50,26 @@ def _warmup_stream(device): return stream -def _seed_warmup_workspaces(stream, device): +def _seed_warmup_workspaces(stream, device, pool=None): """Seed the calling thread's warmup-stream workspace in a dedicated pool. Workspaces are cached per thread's cuBLAS handle, so seeding runs on each capture call under the ambient BLAS backend, the backend the warmups use. A workspace created inside transient storage keeps its address in the cache after the transient backing is released, and a - later call could reuse it; a dedicated pool keeps the seed's backing - mapped for the life of the cache entry, outside transient storage, - any caller-owned pool, and the exported graph pool. + later call could reuse it. When ``pool`` is omitted, seeding uses a + module-level pool outside transient storage, caller-owned pools, and + the exported graph pool. When an export storage supplies + ``warmup_pool()``, seeding uses that persistent pool instead so the + backing stays mapped outside transient storage, ``storage.pool``, and + ``storage.graph_pool`` while remaining inside declared core mappings. """ with torch.cuda.device(device): index = torch.cuda.current_device() - pool = _warmup_pools.get(index) if pool is None: - pool = _warmup_pools[index] = torch.cuda.MemPool() + pool = _warmup_pools.get(index) + if pool is None: + pool = _warmup_pools[index] = torch.cuda.MemPool() with torch.cuda.device(index), torch.cuda.stream(stream), torch.cuda.use_mem_pool(pool): operand = torch.empty((512, 512), dtype=torch.bfloat16, device=device) bias = torch.empty((512,), dtype=torch.bfloat16, device=device) @@ -75,6 +79,34 @@ def _seed_warmup_workspaces(stream, device): stream.synchronize() +def _seed_auxiliary_workspaces(session, device, *, warmup_storage): + """Seed an overlap stream's cuBLAS workspace outside transient warmup storage. + + An auxiliary stream that runs cuBLAS ops during both eager warmups and + graph capture cannot allocate its cached workspace from transient warmup + storage, which is unmapped after warmup, nor from an unexported warmup pool + during core export. Seeding inside the exported graph pool keeps the cached + workspace mapped across warmups, graph capture, and native replay. + """ + arena = getattr(session, "_scratch_arena", None) + aux = getattr(arena, "_auxiliary_stream", None) + if aux is None: + return + with torch.cuda.device(device): + index = torch.cuda.current_device() + graph_pool = getattr(warmup_storage, "graph_pool", None) + pool_ctx = nullcontext() if graph_pool is None else torch.cuda.use_mem_pool(graph_pool) + with torch.cuda.device(index), torch.cuda.stream(aux), pool_ctx: + operand = torch.empty((512, 512), dtype=torch.bfloat16, device=device) + bias = torch.empty((512,), dtype=torch.bfloat16, device=device) + out = torch.empty_like(operand) + torch.mm(operand, operand, out=out) + torch.addmm(bias, operand, operand, out=out) + batched = operand.view(1, 512, 512) + torch.bmm(batched, batched, out=out.view(1, 512, 512)) + aux.synchronize() + + def _capture_order(names, compiled, coordinator): sizes = {name: forward.capture_allocation_sizes for name, forward in compiled.items()} return allocation_order(names, sizes, coordinator) @@ -116,7 +148,13 @@ def capture_forwards(functions, signatures, *, session, device, stream, pool, graphs, compiled = {}, {} warmup = nullcontext if warmup_storage is None else warmup_storage.transient warm = _warmup_stream(device) - _seed_warmup_workspaces(warm, device) + warmup_pool = warmup_storage.warmup_pool() if hasattr(warmup_storage, "warmup_pool") else None + if warmup_pool is not None: + _seed_warmup_workspaces(warm, device, warmup_pool) + else: + # Keep the 2-argument call for non-export callers and existing test stubs. + _seed_warmup_workspaces(warm, device) + _seed_auxiliary_workspaces(session, device, warmup_storage=warmup_storage) with ExitStack() as capture_scope: if compile_decoder: cache = ForwardCache(namespace=session.namespace.to_dict(), device=device, root=cache_root, diff --git a/ignition/preparation/core_storage.py b/ignition/preparation/core_storage.py index 577ff897d..74880483d 100644 --- a/ignition/preparation/core_storage.py +++ b/ignition/preparation/core_storage.py @@ -75,6 +75,7 @@ def __init__(self, *, rank=0, world=1, device=0, local_ranks=None, device_window self._persistent_total_bytes = min(properties.total_memory, self.RESERVATION_BYTES // 4) self._retention_scope = False self._retention_pool = None + self._warmup_pool = None window = (self.DEVICE_BASE, self.RESERVATION_BYTES) self.DEVICE_BASE += rank * self.RESERVATION_BYTES self.cuda = _Cuda() @@ -305,6 +306,17 @@ def scratch_pool(self): self._preparation_pools.add(pool.pool.id) return pool + def warmup_pool(self): + """Own a persistent pool for cuBLAS warmup workspaces inside core mappings.""" + import torch + + pool = getattr(self, "_warmup_pool", None) + if pool is None: + pool = torch.cuda.MemPool(self._allocator.allocator()) + self._warmup_pool = pool + self._preparation_pools.add(pool.id) + return pool + def packed_weights(self): """Own aligned immutable weight storage until graph users have drained.""" from .packed_weights import PackedWeights diff --git a/tests/preparation/test_capture_cublas_workspace_cuda.py b/tests/preparation/test_capture_cublas_workspace_cuda.py index b92a602e9..1be31db4b 100644 --- a/tests/preparation/test_capture_cublas_workspace_cuda.py +++ b/tests/preparation/test_capture_cublas_workspace_cuda.py @@ -118,3 +118,137 @@ def capture(stream, before_run=None): graph.reset() finally: torch.backends.cuda.preferred_blas_library(previous_blas) + + +def test_export_warmup_pool_seeds_workspace_inside_core_storage(tmp_path): + """Run export warmup seeding in an isolated subprocess against real CoreStorage. + + Subprocess isolation avoids both process-singleton CoreStorage arena reuse + and cross-test sharing of capture._warmup_streams[0] / cuBLASLt cache state. + """ + from pathlib import Path + import subprocess + import sys + + subprocess.run( + [ + sys.executable, + "-c", + "from pathlib import Path; import sys; " + "from tests.preparation.test_capture_cublas_workspace_cuda import check_export_warmup_pool; " + "check_export_warmup_pool(Path(sys.argv[1]))", + str(tmp_path), + ], + check=True, + timeout=120, + cwd=Path(__file__).resolve().parents[2], + ) + + +def check_export_warmup_pool(tmp_path): + from ignition.preparation import capture as _capture + from ignition.preparation.capture import capture_forwards + from ignition.preparation.core_storage import CoreStorage + from ignition.preparation.execution import GraphSignature, PreparedExecution + from ignition.preparation.module_images import ModuleImages + from ignition.preparation.runtime_core import Allocation, RuntimeCore + + with ModuleImages() as images: + torch.cuda.set_device(0) + previous_blas = torch.backends.cuda.preferred_blas_library() + torch.backends.cuda.preferred_blas_library("cublaslt") + try: + storage = CoreStorage() + with storage: + source = torch.randn((512, 512), device="cuda", dtype=torch.bfloat16) + weight = torch.randn((512, 512), device="cuda", dtype=torch.bfloat16) + output = torch.empty_like(source) + frame = torch.zeros(1, device="cuda", dtype=torch.int32) + sequence = torch.zeros(1, device="cuda", dtype=torch.int64) + records = torch.zeros((2, 1, 24), device="cuda", dtype=torch.int64) + + def forward(): + torch.mm(source, weight, out=output) + + stream = torch.cuda.Stream() + graphs, _ = capture_forwards( + {"decode": forward}, + {"decode": GraphSignature("decode", 1, 1)}, + session=SimpleNamespace(capture=nullcontext), + device=0, + stream=stream, + pool=storage.graph_pool.id, + warmup_storage=storage, + retain_graphs=True, + compile_decoder=False, + ) + try: + # Export seeding must use CoreStorage.warmup_pool(), not the unmanaged module pool. + assert not _capture._warmup_pools + warmup_pool = storage.warmup_pool() + assert warmup_pool.id in storage._preparation_pools + assert _active_pool_blocks(warmup_pool.id), ( + "seeded cuBLASLt workspace did not land inside CoreStorage.warmup_pool()" + ) + warmup_segments = torch.cuda.memory_snapshot( + warmup_pool.id, include_traces=False + ) + assert warmup_segments + mappings = list(storage.mappings.values()) + for segment in warmup_segments: + addr = segment["address"] + size = segment["total_size"] + assert any( + m.address <= addr and addr + size <= m.address + m.nbytes + for m in mappings + ), f"warmup segment {addr:#x}+{size} fell outside CoreStorage.mappings" + assert _active_pool_blocks(storage.graph_pool.id), ( + "captured graph did not bind cuBLASLt workspace in storage.graph_pool" + ) + buffers = dict( + source=source, + weight=weight, + output=output, + frame_index=frame, + submission_sequence=sequence, + completion_records=records, + ) + bundle = PreparedExecution( + device=0, + graphs=graphs, + buffers=buffers, + max_active=1, + signatures={"decode": GraphSignature("decode", 1, 1, ("source",))}, + ) + allocations = [ + Allocation(name, tensor.data_ptr(), tensor.nbytes) + for name, tensor in buffers.items() + ] + allocations.extend( + Allocation( + f"graph-pool-{index}", + segment["address"], + segment["total_size"], + ) + for index, segment in enumerate( + storage.graph_pool.snapshot(include_traces=False) + ) + ) + package = RuntimeCore( + allocations=allocations, + modules={}, + kernels=(), + recorder=images.native, + owners=(bundle, storage), + ) + package.write( + tmp_path / "rank.json", + bundle.graphs, + execution=bundle.export_manifest(), + sources=True, + ) + finally: + for graph in graphs.values(): + graph.reset() + finally: + torch.backends.cuda.preferred_blas_library(previous_blas) diff --git a/tests/preparation/test_capture_stream_isolation.py b/tests/preparation/test_capture_stream_isolation.py index 78349aba2..0bfa77eaa 100644 --- a/tests/preparation/test_capture_stream_isolation.py +++ b/tests/preparation/test_capture_stream_isolation.py @@ -106,3 +106,48 @@ def test_serving_warmup_enters_the_warmup_stream_without_compilation(monkeypatch assert entered and all(value is warm for value in entered), ( "the serving warmup did not run entirely on the warmup stream") assert captured_on and all(value is stream for value in captured_on) + + +def test_seed_auxiliary_workspaces_uses_graph_pool_and_aux_stream(monkeypatch): + events = [] + aux = SimpleNamespace(synchronize=lambda: events.append("sync")) + graph_pool = object() + + @contextmanager + def fake_device(dev): + events.append(("device", dev)) + yield + + @contextmanager + def fake_stream(stream): + events.append(("stream", stream)) + yield + + @contextmanager + def fake_pool(pool): + events.append(("pool", pool)) + yield + + class FakeTensor: + def view(self, *shape): + return self + + monkeypatch.setattr(capture.torch.cuda, "device", fake_device) + monkeypatch.setattr(capture.torch.cuda, "current_device", lambda: 0) + monkeypatch.setattr(capture.torch.cuda, "stream", fake_stream) + monkeypatch.setattr(capture.torch.cuda, "use_mem_pool", fake_pool) + monkeypatch.setattr(capture.torch, "empty", lambda *a, **k: FakeTensor()) + monkeypatch.setattr(capture.torch, "empty_like", lambda t: FakeTensor()) + monkeypatch.setattr(capture.torch, "mm", lambda *a, **k: events.append("mm")) + monkeypatch.setattr(capture.torch, "addmm", lambda *a, **k: events.append("addmm")) + monkeypatch.setattr(capture.torch, "bmm", lambda *a, **k: events.append("bmm")) + + capture._seed_auxiliary_workspaces(SimpleNamespace(), "cuda:0", warmup_storage=None) + assert events == [] + + session = SimpleNamespace(_scratch_arena=SimpleNamespace(_auxiliary_stream=aux)) + storage = SimpleNamespace(graph_pool=graph_pool) + capture._seed_auxiliary_workspaces(session, "cuda:0", warmup_storage=storage) + assert ("stream", aux) in events + assert ("pool", graph_pool) in events + assert ["mm", "addmm", "bmm", "sync"] == [e for e in events if isinstance(e, str)] diff --git a/tests/preparation/test_core_storage.py b/tests/preparation/test_core_storage.py index 5f6a0b36e..53d13c865 100644 --- a/tests/preparation/test_core_storage.py +++ b/tests/preparation/test_core_storage.py @@ -225,3 +225,28 @@ def test_device_request_state_vocab_ids_records_numeric_tensor(): assert numeric.ranges() == [(ids.data_ptr(), ids.data_ptr() + ids.nbytes)] assert ids.dtype == torch.int64 assert torch.equal(ids, torch.arange(16, dtype=torch.int64)) + + +def test_warmup_pool_reuses_one_core_allocator_pool(monkeypatch): + from types import SimpleNamespace + + created = [] + + class FakeMemPool: + def __init__(self, allocator): + self.allocator = allocator + self.id = (0, 99 + len(created)) + created.append(self) + + sentinel_alloc = object() + storage = CoreStorage.__new__(CoreStorage) + storage._allocator = SimpleNamespace(allocator=lambda: sentinel_alloc) + storage._preparation_pools = set() + monkeypatch.setattr(torch.cuda, "MemPool", FakeMemPool) + + first = storage.warmup_pool() + second = storage.warmup_pool() + assert first is second + assert len(created) == 1 + assert first.allocator is sentinel_alloc + assert first.id in storage._preparation_pools From 71af7c999087f2c955e93bec7b23fff397af6d37 Mon Sep 17 00:00:00 2001 From: Luke Alonso Date: Fri, 4 Dec 2026 08:49:13 -0800 Subject: [PATCH 3/3] fix(preparation): unify ForwardCache source hashing and reject unpickleable Triton state Three preparation-cache and AOT serialization gaps caused stale cache hits and late export failures: (1) `ForwardCache.__init__` hashed only `*.py` files, silently reusing stale compiled forwards after edits to `.cu`, `.cuh`, `.c`, `.h`, `.cpp`, `.hpp` files across Ignition, FlashInfer (`data/include`, `data/csrc`), and external recipe roots; (2) `forward_metadata._uses_custom_object_state` and `rebuild_manifest.weight_views` hardcoded `('ignition.', 'b12x.')`, so objects from external recipe packages bound via `source_roots()` did not strip unguarded attributes during `_GuardPickler` serialization (causing late `PicklingError` on Triton 3.8's local `KernelMetadata` namedtuple when in-process fallback pickled a recipe owner holding a live `CompiledKernel`), and `CompilePool` workers did not inherit bound `source_roots`; (3) `inductor_tuning` and `aot._load_inductor` did not prune or reject non-static `TritonCompileResult` entries before `copy.deepcopy` and `pickle.dumps`, nor did `_GuardPickler` fail fast on a directly guarded `triton.compiler.CompiledKernel`. What changed: - Extended `heliopause/src/export/source_identity.rs`, `heliopause/build.rs`, and `heliopause/src/export/binding.rs` (`export_source_identity`) to hash `.cpp` and `.hpp` alongside `.py/.rs/.c/.cu/.cuh/.h` and accept exact `excluded_files` alongside `excluded_directories`. - Added `prepared_module_roots()`, `is_prepared_object_module()`, and `forward_source_identity()` in `ignition/preparation/source_identity.py` backed by `flare_heliopause.export_source_identity` (covering Ignition with presentation/publication exclusions, FlashInfer Python + native `include`/`csrc`, and all bound `_EXTRA_ROOTS`). - Replaced Python-only `rglob('*.py')` hashing in `ForwardCache.__init__` (`ignition/preparation/aot.py`) with `forward_source_identity`. - Generalized `forward_metadata._uses_custom_object_state` and `rebuild_manifest.weight_views` onto `is_prepared_object_module()`, and propagated bound `_EXTRA_ROOTS` from `CompilePool.submit_payload` into spawned `_compile_forward` workers (`ignition/preparation/compile_pool.py`). - Added `_prune_static_compile_results` and `_sanitize_static_bundle` in `ignition/preparation/inductor_tuning.py`, invoked from `_selected`, `_snapshot` (before `copy.deepcopy`), `InductorSelections.freeze` (before `pickle.dumps`), and `aot._load_inductor`, and raised a clear `TypeError` in `_GuardPickler.reducer_override` if a guard references a live `triton.compiler.CompiledKernel`. - Added unit tests in `tests/preparation/{test_source_identity.py, test_forward_cache_sources.py,test_guard_code.py,test_compile_pool.py, test_inductor_prepared_winners.py}`. Claimed benefit and measured results: Native CUDA/C++ edits across Ignition, FlashInfer, and bound recipe packages deterministically invalidate `ForwardCache`; external recipe objects strip unguarded attributes identically in parent and spawned compiler workers without hardcoding recipe names in core Ignition; and non-static `TritonCompileResult` or guarded `CompiledKernel` objects are pruned or rejected with actionable errors before `pickle.dumps`. Supporting evidence and limitations: - Rust library tests: `cargo test --locked --release --manifest-path heliopause/Cargo.toml --lib` -> 250 passed, 0 failed, 6 ignored. - Core boundary and targeted preparation CPU tests (with freshly compiled staged `flare_heliopause` extension): `test_core_boundary.py`, `test_source_identity.py`, `test_forward_cache_sources.py`, `test_guard_code.py`, `test_compile_pool.py`, `test_inductor_prepared_winners.py`, and `tests/cli/test_recipe_injection.py` all passed. - Full CPU suite (`tests/preparation/ tests/cli/`): 1,431 passed, 75 skipped (CUDA/Windows-gated), and 1 pre-existing unrelated failure in `tests/preparation/test_runtime_triton.py::test_replaces_stock_architecture_probe_with_pointer_width_key` (stock Triton 3.8.0 `platform_key()` omits `"ELF"`). - CUDA tests (`FLARE_RUN_CUDA_TESTS=1`, SM120 GPU 2): `test_inductor_tuning_cuda.py` (8 passed, 5 TP2-gated skipped), `test_recorded_export_graph_cuda.py` (2 passed), and cross-repo real Triton 3.8.0 `PreparedResidualMix` worker + direct AOT guard roundtrips and `hyperflare_jetson_recipes/csrc/*.{cu,cuh}` `ForwardCache` invalidation checks all passed. - Limitations: full multi-rank GB10/SM121 Inkling2 export and TP2 distributed Inductor CUDA tests were not run on this host. Design-Signed-Off-By: Antigravity; design-review=2e5b Signed-off-by: Luke Alonso --- heliopause/build.rs | 4 +- heliopause/src/export/binding.rs | 16 ++- heliopause/src/export/source_identity.rs | 37 +++++- ignition/preparation/aot.py | 55 +++++---- ignition/preparation/compile_pool.py | 18 ++- ignition/preparation/forward_metadata.py | 4 +- ignition/preparation/inductor_tuning.py | 54 ++++++++- ignition/preparation/rebuild_manifest.py | 3 +- ignition/preparation/source_identity.py | 111 ++++++++++++++++++ tests/preparation/test_compile_pool.py | 55 +++++++++ .../preparation/test_forward_cache_sources.py | 43 ++++++- tests/preparation/test_guard_code.py | 91 ++++++++++++++ .../test_inductor_prepared_winners.py | 90 ++++++++++++++ tests/preparation/test_source_identity.py | 16 ++- 14 files changed, 550 insertions(+), 47 deletions(-) diff --git a/heliopause/build.rs b/heliopause/build.rs index 47bcc8087..03b1d93fc 100644 --- a/heliopause/build.rs +++ b/heliopause/build.rs @@ -140,7 +140,9 @@ fn collect_sources(directory: &Path, files: &mut Vec) { && path .extension() .and_then(|value| value.to_str()) - .is_some_and(|value| matches!(value, "py" | "rs" | "c" | "cu" | "cuh" | "h")) + .is_some_and(|value| { + matches!(value, "py" | "rs" | "c" | "cpp" | "cu" | "cuh" | "h" | "hpp") + }) { println!("cargo:rerun-if-changed={}", path.display()); files.push(path); diff --git a/heliopause/src/export/binding.rs b/heliopause/src/export/binding.rs index c759973f7..97f0805d4 100644 --- a/heliopause/src/export/binding.rs +++ b/heliopause/src/export/binding.rs @@ -1146,15 +1146,23 @@ mod stage_tests { } } -#[pyfunction(signature = (roots, *, excluded_directories = None))] +#[pyfunction(signature = (roots, *, excluded_directories = None, excluded_files = None))] fn export_source_identity( py: Python<'_>, roots: Vec, excluded_directories: Option>, + excluded_files: Option>, ) -> PyResult { - py.detach(|| match excluded_directories { - Some(excluded) => super::source_identity::source_identity_excluding(&roots, &excluded), - None => super::source_identity::source_identity(&roots), + py.detach(|| { + let mut excluded = excluded_directories.unwrap_or_default(); + if let Some(files) = excluded_files { + excluded.extend(files); + } + if excluded.is_empty() { + super::source_identity::source_identity(&roots) + } else { + super::source_identity::source_identity_excluding(&roots, &excluded) + } }) .map_err(|e| PyRuntimeError::new_err(e.to_string())) } diff --git a/heliopause/src/export/source_identity.rs b/heliopause/src/export/source_identity.rs index 150b3d693..53c6882fe 100644 --- a/heliopause/src/export/source_identity.rs +++ b/heliopause/src/export/source_identity.rs @@ -40,10 +40,13 @@ fn collect(directory: &Path, files: &mut Vec, excluded: &[PathBuf]) -> if entry.file_type()?.is_dir() { collect(&path, files, excluded)?; } else if path.is_file() + && !excluded.iter().any(|excluded_path| excluded_path == &path) && path .extension() .and_then(|value| value.to_str()) - .is_some_and(|value| matches!(value, "py" | "rs" | "c" | "cu" | "cuh" | "h")) + .is_some_and(|value| { + matches!(value, "py" | "rs" | "c" | "cpp" | "cu" | "cuh" | "h" | "hpp") + }) { files.push(path); } @@ -148,6 +151,38 @@ mod tests { ); } + #[test] + fn hashes_cpp_hpp_and_excludes_exact_files_and_directories() { + let directory = tempfile::tempdir().unwrap(); + let root = directory.path().join("pkg"); + let skipped_dir = root.join("cli"); + fs::create_dir_all(&skipped_dir).unwrap(); + fs::write(root.join("kernel.cpp"), b"cpp-v1").unwrap(); + fs::write(root.join("kernel.hpp"), b"hpp-v1").unwrap(); + fs::write(root.join("progress.py"), b"ui-v1").unwrap(); + fs::write(skipped_dir.join("main.py"), b"cli-v1").unwrap(); + + let excluded = vec![root.join("progress.py"), skipped_dir.clone()]; + let baseline = source_identity_excluding(&[root.clone()], &excluded).unwrap(); + + // Excluded file and directory edits do not alter the digest. + fs::write(root.join("progress.py"), b"ui-v2").unwrap(); + fs::write(skipped_dir.join("main.py"), b"cli-v2").unwrap(); + assert_eq!( + source_identity_excluding(&[root.clone()], &excluded).unwrap(), + baseline + ); + + // Included .cpp and .hpp edits each alter the digest. + fs::write(root.join("kernel.cpp"), b"cpp-v2").unwrap(); + let after_cpp = source_identity_excluding(&[root.clone()], &excluded).unwrap(); + assert_ne!(after_cpp, baseline); + + fs::write(root.join("kernel.hpp"), b"hpp-v2").unwrap(); + let after_hpp = source_identity_excluding(&[root], &excluded).unwrap(); + assert_ne!(after_hpp, after_cpp); + } + #[test] fn build_time_source_identities_match_runtime_hashing() { let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")); diff --git a/ignition/preparation/aot.py b/ignition/preparation/aot.py index 7d561d55c..ce83270c1 100644 --- a/ignition/preparation/aot.py +++ b/ignition/preparation/aot.py @@ -122,12 +122,14 @@ def _load_inductor(data, original, *, frozen=False): entry.compiled_fw.result.inductor_post_grad_graph_str = None entry.compiled_fw.result.cache_linemap = None relocate_inductor(entry, original, freeze_tuning=frozen) - if frozen and entry.compiled_fw.result._triton_bundle is not None: - from .inductor_tuning import _materialize_selected_cubin - - for tuner in entry.compiled_fw.result._triton_bundle.static_autotuners: - for result in tuner.kernel.compile_results: - _materialize_selected_cubin(result) + if entry.compiled_fw.result._triton_bundle is not None: + from .inductor_tuning import _materialize_selected_cubin, _sanitize_static_bundle + + _sanitize_static_bundle(entry.compiled_fw.result._triton_bundle, frozen=frozen) + if frozen: + for tuner in entry.compiled_fw.result._triton_bundle.static_autotuners: + for result in tuner.kernel.compile_results: + _materialize_selected_cubin(result) serialized = zlib.compress(pickle.dumps((entry, kernels, constants)), level=1) compiled = deserialize_bundled_cache_entry(entry) serializer = getattr(compiled.serialize, "__self__", None) @@ -218,6 +220,13 @@ def reducer_override(self, obj): return type(self)._unpickle_tensor, args if isinstance(obj, JITFunction): return _deserialize_triton_kernel, (_serialize_triton_kernel(obj),) + from triton.compiler import CompiledKernel + + if isinstance(obj, CompiledKernel): + raise TypeError( + "AOT forward guard cannot serialize a compiled Triton kernel; " + "guard on a pickleable flag instead of a CompiledKernel attribute" + ) from .forward_metadata import _uses_custom_object_state if _uses_custom_object_state(obj): @@ -890,23 +899,23 @@ def __init__(self, *, namespace, device, root=None, headroom_bytes=0, options=No key = hashlib.sha256(pickle.dumps((namespace, options, _b12x_forward_env(), torch_key(), runtime_patches.identity(), properties.name, properties.major, properties.minor, properties.multi_processor_count))) - for source in (Path(__file__).resolve().parents[1], Path(flashinfer.__file__).resolve().parent): - for path in sorted(source.rglob('*.py')): - if source.name == 'ignition' and (path.name == '__main__.py' - or path.relative_to(source).parts[0] in _COMMAND_SOURCES - or path.relative_to(source).as_posix() in _PUBLICATION_SOURCES): - continue - key.update(str(path.relative_to(source)).encode()) - key.update(path.read_bytes()) - from .source_identity import _EXTRA_ROOTS - - for label, extra_root in _EXTRA_ROOTS.get(): - extra_root = Path(extra_root).resolve() - if not extra_root.is_dir(): - raise ValueError(f"bound source root {label!r} does not exist: {extra_root}") - for path in sorted(extra_root.rglob('*.py')): - rel = f'{label}/{path.relative_to(extra_root).as_posix()}'.encode() - key.update(b'\0' + rel + b'\0' + hashlib.sha256(path.read_bytes()).digest()) + from .source_identity import _EXTRA_ROOTS, forward_source_identity + + ignition_root = Path(__file__).resolve().parents[1] + excluded_dirs = [ignition_root / entry for entry in _COMMAND_SOURCES if not entry.endswith('.py')] + excluded_files = [ + ignition_root / '__main__.py', + *(ignition_root / entry for entry in _COMMAND_SOURCES if entry.endswith('.py')), + *(ignition_root / entry for entry in _PUBLICATION_SOURCES), + ] + sources_digest = forward_source_identity( + ignition_root, + Path(flashinfer.__file__).resolve().parent, + excluded_directories=excluded_dirs, + excluded_files=excluded_files, + extra_roots=_EXTRA_ROOTS.get(), + ) + key.update(b'\0sources\0' + bytes.fromhex(sources_digest)) root = DEFAULT_CACHE_ROOT if root is None else Path(root) self.root = root / 'forwards' / key.hexdigest() diff --git a/ignition/preparation/compile_pool.py b/ignition/preparation/compile_pool.py index d7f4c0023..a987477e3 100644 --- a/ignition/preparation/compile_pool.py +++ b/ignition/preparation/compile_pool.py @@ -125,19 +125,23 @@ def allocate_workers(resources, counts, hosts): @_defer_full_collection() -def _compile_forward(payload, device, options, path, num_threads, grad_enabled): +def _compile_forward(payload, device, options, path, num_threads, grad_enabled, extra_roots=()): runtime_patches.apply() from .aot import _save_compiled_function, aot_forward from .device_binding import bind_device from .forward_metadata import loads + from .source_identity import source_roots as bind_source_roots torch.set_num_threads(num_threads) torch.set_grad_enabled(grad_enabled) torch.cuda.set_device(device) - # A lent forward's metadata names its owner's GPU; it loads bound to this worker's. - with bind_device(device): - forward = loads(payload) - artifact = aot_forward(forward, options=options) + # Propagate bound source roots into spawned workers so guard pickling strips + # unguarded attributes on external recipe objects identically to the parent. + with bind_source_roots(extra_roots): + # A lent forward's metadata names its owner's GPU; it loads bound to this worker's. + with bind_device(device): + forward = loads(payload) + artifact = aot_forward(forward, options=options) _save_compiled_function(artifact, path) @@ -165,6 +169,7 @@ def submit(self, forward, path): def submit_payload(self, payload, path): """Compile a forward serialized by `forward_metadata.dumps`, possibly on another rank, into `path`.""" from torch._inductor.compile_worker.subproc_pool import SubprocKind, SubprocPool + from .source_identity import _EXTRA_ROOTS if self.pool is None: runtime_patches.apply() @@ -172,8 +177,9 @@ def submit_payload(self, payload, path): self.pool = ProcessPoolExecutor(self.workers, mp_context=multiprocessing.get_context("spawn")) else: self.pool = SubprocPool(self.workers, kind=SubprocKind.SPAWN) + extra_roots = tuple((label, str(root)) for label, root in _EXTRA_ROOTS.get()) return self.pool.submit(_compile_forward, payload, self.device, self.options, str(path), - torch.get_num_threads(), torch.is_grad_enabled()) + torch.get_num_threads(), torch.is_grad_enabled(), extra_roots) def __enter__(self): return self diff --git a/ignition/preparation/forward_metadata.py b/ignition/preparation/forward_metadata.py index 20920a516..34b4c5289 100644 --- a/ignition/preparation/forward_metadata.py +++ b/ignition/preparation/forward_metadata.py @@ -37,9 +37,11 @@ def _uses_custom_object_state(value): + from .source_identity import is_prepared_object_module + return ( hasattr(value, '__dict__') - and type(value).__module__.startswith(('ignition.', 'b12x.')) + and is_prepared_object_module(type(value).__module__) and not inspect.isclass(value) and not isinstance(value, _NON_OBJECT_NEW_TYPES) ) diff --git a/ignition/preparation/inductor_tuning.py b/ignition/preparation/inductor_tuning.py index fb062daeb..cfc1e9354 100644 --- a/ignition/preparation/inductor_tuning.py +++ b/ignition/preparation/inductor_tuning.py @@ -18,15 +18,57 @@ from .device_binding import _device_source, _freeze_tuning_winners -def _selected(tuner): +def _prune_static_compile_results(tuner, *, require_single=True): + """Prune to the selected static launcher and reject non-static TritonCompileResult entries.""" from torch._inductor.runtime.triton_heuristics import StaticTritonCompileResult + kernel_name = getattr(tuner, "inductor_meta", {}).get("kernel_name", "") + launchers = getattr(tuner, "launchers", ()) + if len(launchers) == 1: + tuner._prune_compile_results_to_launcher(launchers[0]) + results = list(tuner.compile_results) + static_results = [result for result in results if isinstance(result, StaticTritonCompileResult)] + non_static = [ + f"{type(result).__module__}.{type(result).__qualname__}" + for result in results + if not isinstance(result, StaticTritonCompileResult) + ] + if non_static: + if not require_single and static_results: + tuner.compile_results = static_results + results = static_results + else: + raise TypeError( + f"Inductor kernel {kernel_name!r} retained non-static compile result(s) " + f"{non_static}; prepared forwards require a portable StaticTritonCompileResult" + ) + if require_single: + if len(results) != 1: + raise RuntimeError( + f"Inductor kernel {kernel_name!r} must retain one static compile result, " + f"got {len(results)}" + ) + return results[0] + if not results: + raise TypeError( + f"Inductor kernel {kernel_name!r} has no static compile results; " + "prepared forwards require a portable StaticTritonCompileResult" + ) + return results + + +def _sanitize_static_bundle(bundle, *, frozen=True): + """Ensure no non-static TritonCompileResult survives into pickle.dumps.""" + if bundle is None: + return + for entry in bundle.static_autotuners: + _prune_static_compile_results(entry.kernel, require_single=frozen) + + +def _selected(tuner): if len(tuner.launchers) != 1: raise RuntimeError(f"Inductor kernel {tuner.inductor_meta['kernel_name']} has no final launcher") - tuner._prune_compile_results_to_launcher(tuner.launchers[0]) - result, = tuner.compile_results - if not isinstance(result, StaticTritonCompileResult): - raise TypeError("prepared Inductor selections require a portable static kernel") + result = _prune_static_compile_results(tuner, require_single=True) result = copy.copy(result) result.kernel = copy.copy(result.kernel) result._flare_config_state = copy.deepcopy(vars(result.config)) @@ -63,6 +105,7 @@ def _install(tuner, encoded): def _snapshot(entry, tuner): + _prune_static_compile_results(tuner, require_single=True) state = tuner.prepare_for_pickle() try: saved = copy.deepcopy(tuner) @@ -320,6 +363,7 @@ def freeze(self, bound): bundle = graph._triton_bundle if bundle is not None: bundle = replace(bundle, static_autotuners=snapshots) + _sanitize_static_bundle(bundle, frozen=True) _freeze_tuning_winners(bundle) entry, kernels, constants = pickle.loads(zlib.decompress(backend._serialized_artifact)) entry.compiled_fw.result._triton_bundle = bundle diff --git a/ignition/preparation/rebuild_manifest.py b/ignition/preparation/rebuild_manifest.py index b14cead44..e1690cfc5 100644 --- a/ignition/preparation/rebuild_manifest.py +++ b/ignition/preparation/rebuild_manifest.py @@ -345,6 +345,7 @@ def weight_views(roots): each field name; cycles in container ownership do not recurse indefinitely. """ import torch + from .source_identity import is_prepared_object_module def walk(value, name, owner, ancestors): if isinstance(value, torch.Tensor): @@ -365,7 +366,7 @@ def walk(value, name, owner, ancestors): elif is_dataclass(value) and not isinstance(value, type): owner = f'{type(value).__module__}.{type(value).__qualname__}' children = ((f'.{field.name}', getattr(value, field.name)) for field in fields(value)) - elif type(value).__module__.startswith(('b12x.', 'ignition.')) and hasattr(value, '__dict__'): + elif is_prepared_object_module(type(value).__module__) and hasattr(value, '__dict__'): owner = f'{type(value).__module__}.{type(value).__qualname__}' children = ((f'.{key}', child) for key, child in vars(value).items()) else: diff --git a/ignition/preparation/source_identity.py b/ignition/preparation/source_identity.py index 93ebb23fc..16ed29973 100644 --- a/ignition/preparation/source_identity.py +++ b/ignition/preparation/source_identity.py @@ -14,6 +14,9 @@ ) +_BASE_PREPARED_MODULE_ROOTS = ("ignition", "b12x") + + @contextmanager def source_roots(roots=()): """Bind external `(label, path)` source roots for the duration of a CLI invocation.""" @@ -25,6 +28,114 @@ def source_roots(roots=()): _EXTRA_ROOTS.reset(token) +def prepared_module_roots() -> tuple[str, ...]: + """Return top-level Python module prefixes for core packages and bound source roots.""" + roots = list(_BASE_PREPARED_MODULE_ROOTS) + seen = set(roots) + for label, path in _EXTRA_ROOTS.get(): + candidates = [label] + resolved_name = Path(path).name + if resolved_name and resolved_name != label: + candidates.append(resolved_name) + for candidate in candidates: + if ( + candidate + and all(part.isidentifier() for part in candidate.split(".")) + and candidate not in seen + ): + seen.add(candidate) + roots.append(candidate) + return tuple(roots) + + +def is_prepared_object_module(module_name: str) -> bool: + """Return whether `module_name` belongs to Ignition, b12x, or a bound source root.""" + if not module_name: + return False + return any( + module_name == root or module_name.startswith(f"{root}.") + for root in prepared_module_roots() + ) + + +def forward_source_identity( + ignition_root: Path, + flashinfer_package: Path, + *, + excluded_directories=(), + excluded_files=(), + extra_roots=(), +) -> str: + """Hash Python and native execution sources for AOT forward cache keys. + + Delegates directory traversal and SHA-256 hashing to + ``flare_heliopause.export_source_identity`` so ``.py``, ``.rs``, ``.c``, + ``.cpp``, ``.cu``, ``.cuh``, ``.h``, and ``.hpp`` edits across Ignition, + FlashInfer (including ``data/include`` and ``data/csrc``), and every bound + external source root invalidate compiled forward caches. + """ + import flare_heliopause + + ignition_root = Path(ignition_root).resolve() + flashinfer_package = Path(flashinfer_package).resolve() + data = flashinfer_package / "data" + + digest = hashlib.sha256() + + def mix_hex(label: str, hex_digest: str): + digest.update(b"\0" + label.encode("utf-8") + b"\0") + digest.update(bytes.fromhex(hex_digest)) + + mix_hex( + "ignition", + flare_heliopause.export_source_identity( + [ignition_root], + excluded_directories=[Path(path).resolve() for path in excluded_directories], + excluded_files=[Path(path).resolve() for path in excluded_files], + ), + ) + mix_hex( + "flashinfer.python", + flare_heliopause.export_source_identity( + [flashinfer_package], + excluded_directories=[data], + ), + ) + if data.exists(): + for name in ("include", "csrc"): + native = (data / name).resolve() + if not native.is_dir(): + raise RuntimeError( + f"FlashInfer native source directory is unavailable: {data / name}; " + "install the selected FlashInfer package before preparation" + ) + mix_hex( + f"flashinfer.{name}", + flare_heliopause.export_source_identity([native]), + ) + elif (flashinfer_package.parent / "include").is_dir() and ( + flashinfer_package.parent / "csrc" + ).is_dir(): + for name in ("include", "csrc"): + mix_hex( + f"flashinfer.{name}", + flare_heliopause.export_source_identity( + [(flashinfer_package.parent / name).resolve()] + ), + ) + + for label, extra_root in extra_roots: + resolved = Path(extra_root).resolve() + if not resolved.is_dir(): + raise ValueError(f"bound source root {label!r} does not exist: {resolved}") + mix_hex( + f"extra:{label}", + flare_heliopause.export_source_identity([resolved]), + ) + + return digest.hexdigest() + + def source_identity(*, extra_roots=()): """Digest of the Python and native sources every rank must run identically. diff --git a/tests/preparation/test_compile_pool.py b/tests/preparation/test_compile_pool.py index 183cf09b8..c7c9387a0 100644 --- a/tests/preparation/test_compile_pool.py +++ b/tests/preparation/test_compile_pool.py @@ -424,6 +424,61 @@ def shutdown(self): assert executor.closed and compile_pool._OPTIONS["compile_threads"] == 16 +def test_compile_pool_propagates_bound_source_roots_to_workers(monkeypatch, tmp_path): + from concurrent.futures import Future + from torch._inductor.compile_worker import subproc_pool + from ignition.preparation import aot, compile_pool, forward_metadata, host_memory + from ignition.preparation.source_identity import _EXTRA_ROOTS, source_roots + + pkg_dir = tmp_path / "bound_recipe_pkg" + pkg_dir.mkdir() + captured = [] + + class Executor: + def __init__(self, *args, **kwargs): + pass + + def submit(self, function, *arguments): + captured.append((function, arguments)) + future = Future() + future.set_result(None) + return future + + def shutdown(self): + pass + + monkeypatch.setattr(torch.cuda, "mem_get_info", lambda device: (48 << 30, 96 << 30)) + monkeypatch.setattr(torch.cuda, "get_device_properties", lambda device: SimpleNamespace(is_integrated=False)) + monkeypatch.setattr(host_memory, "available_bytes", lambda: 64 << 30) + monkeypatch.setattr(subproc_pool, "SubprocPool", Executor) + monkeypatch.setattr(compile_pool, "ProcessPoolExecutor", Executor) + + with source_roots((("bound_recipe_pkg", pkg_dir),)): + with compile_pool.CompilePool("cuda:0", workers=1) as pool: + pool.submit(SimpleNamespace(), tmp_path / "out.bin") + assert len(captured) == 1 + fn, args = captured[0] + assert fn is compile_pool._compile_forward + assert args[6] == (("bound_recipe_pkg", str(pkg_dir)),) + + observed_roots = [] + monkeypatch.setattr(compile_pool.runtime_patches, "apply", lambda: None) + monkeypatch.setattr(torch, "set_num_threads", lambda n: None) + monkeypatch.setattr(torch, "set_grad_enabled", lambda flag: None) + monkeypatch.setattr(torch.cuda, "set_device", lambda dev: None) + monkeypatch.setattr(forward_metadata, "loads", lambda payload: "forward") + + def fake_aot_forward(forward, *, options=None): + observed_roots.append(_EXTRA_ROOTS.get()) + return "artifact" + + monkeypatch.setattr(aot, "aot_forward", fake_aot_forward) + monkeypatch.setattr(aot, "_save_compiled_function", lambda artifact, path: None) + compile_pool._compile_forward(*args) + assert observed_roots == [(("bound_recipe_pkg", pkg_dir),)] + assert _EXTRA_ROOTS.get() == () + + @pytest.mark.parametrize("integrated,workers", [(False, 2), (True, 1)]) def test_compilation_preserves_configured_headroom(monkeypatch, integrated, workers): from ignition.preparation import compile_pool, host_memory diff --git a/tests/preparation/test_forward_cache_sources.py b/tests/preparation/test_forward_cache_sources.py index 125d0d1d1..60ba90461 100644 --- a/tests/preparation/test_forward_cache_sources.py +++ b/tests/preparation/test_forward_cache_sources.py @@ -43,8 +43,13 @@ def test_presentation_edits_preserve_forward_cache_but_execution_edits_invalidat core = tmp_path / "ignition" preparation = core / "preparation" preparation.mkdir(parents=True) + cli = core / "cli" + cli.mkdir() + (cli / "main.py").write_text("cli = 1\n") backend = preparation / "aot.py" backend.write_text("backend = 1\n") + kv_codec_cu = preparation / "kv_codec_gpu.cu" + kv_codec_cu.write_text("__global__ void kv_v1() {}\n") progress = core / "progress.py" progress.write_text("splash = 'sun'\n") entrypoint = core / "__main__.py" @@ -52,13 +57,24 @@ def test_presentation_edits_preserve_forward_cache_but_execution_edits_invalidat publication = preparation / "core_file.py" publication.write_text("threads = 1\n") kernels = tmp_path / "flashinfer" - kernels.mkdir() + (kernels / "data" / "csrc").mkdir(parents=True) + (kernels / "data" / "include").mkdir(parents=True) operator = kernels / "operator.py" operator.write_text("kernel = 1\n") + fi_cu = kernels / "data" / "csrc" / "op.cu" + fi_cu.write_text("void op_v1() {}\n") + fi_cuh = kernels / "data" / "include" / "op.cuh" + fi_cuh.write_text("#define OP_VER 1\n") external = tmp_path / "external_recipes" external.mkdir() recipe = external / "recipe.py" recipe.write_text("recipe = 1\n") + recipe_cu = external / "kernel.cu" + recipe_cu.write_text("void r_v1() {}\n") + recipe_cpp = external / "helper.cpp" + recipe_cpp.write_text("int h_v1() { return 1; }\n") + recipe_hpp = external / "helper.hpp" + recipe_hpp.write_text("#define H_VER 1\n") monkeypatch.setattr(aot, "__file__", str(backend)) monkeypatch.setattr(flashinfer, "__file__", str(kernels / "__init__.py")) monkeypatch.setattr(aot.torch.cuda, "get_device_properties", lambda device: @@ -71,18 +87,37 @@ def root(): progress.write_text("splash = 'solar flare'\n") entrypoint.write_text("port = 8001\n") publication.write_text("threads = 16\n") + (cli / "main.py").write_text("cli = 2\n") assert root() == original backend.write_text("backend = 2\n") changed = root() assert changed != original + kv_codec_cu.write_text("__global__ void kv_v2() {}\n") + after_kv_cu = root() + assert after_kv_cu != changed operator.write_text("kernel = 2\n") after_kernel = root() - assert after_kernel != changed + assert after_kernel != after_kv_cu + fi_cu.write_text("void op_v2() {}\n") + after_fi_cu = root() + assert after_fi_cu != after_kernel + fi_cuh.write_text("#define OP_VER 2\n") + after_fi_cuh = root() + assert after_fi_cuh != after_fi_cu with source_roots((("external_recipes", external),)): with_external = root() - assert with_external != after_kernel + assert with_external != after_fi_cuh recipe.write_text("recipe = 2\n") - assert root() != with_external + after_recipe_py = root() + assert after_recipe_py != with_external + recipe_cu.write_text("void r_v2() {}\n") + after_recipe_cu = root() + assert after_recipe_cu != after_recipe_py + recipe_cpp.write_text("int h_v2() { return 2; }\n") + after_recipe_cpp = root() + assert after_recipe_cpp != after_recipe_cu + recipe_hpp.write_text("#define H_VER 2\n") + assert root() != after_recipe_cpp with source_roots((("missing", tmp_path / "does_not_exist"),)): with pytest.raises(ValueError, match="does not exist"): root() diff --git a/tests/preparation/test_guard_code.py b/tests/preparation/test_guard_code.py index 628a936c6..9583304b5 100644 --- a/tests/preparation/test_guard_code.py +++ b/tests/preparation/test_guard_code.py @@ -247,3 +247,94 @@ def test_guard_serialization_roundtrips_tensor_user_attributes(): wrong_scale.weight.scale = torch.ones((2, 2), dtype=torch.float32) assert restored.guard_check(forward) assert not restored.guard_check(wrong_scale) + + +class _UnpicklableHandle: + def __reduce__(self): + raise TypeError("compiled kernel handles cannot be pickled") + + +class _BoundRecipeKernelOwner: + __module__ = "custom_recipe_pkg.components.synthetic" + + def __init__(self, scale): + self.scale = scale + self.compiled_handle = _UnpicklableHandle() + + def apply(self, value): + return value * self.scale + + +class _BoundRecipeForward: + def __init__(self, scale): + self.value = torch.ones(2) + self.owner = _BoundRecipeKernelOwner(scale) + + def __call__(self): + return self.owner.apply(self.value) + + +def test_guard_pickler_strips_unguarded_attributes_across_bound_source_roots(monkeypatch, tmp_path): + import types + from torch._dynamo.aot_compile_types import GraphModuleSerializableCallable + from ignition.preparation.rebuild_manifest import weight_views + from ignition.preparation.source_identity import source_roots + + pkg_dir = tmp_path / "custom_recipe_pkg" + pkg_dir.mkdir() + root_mod = types.ModuleType("custom_recipe_pkg") + root_mod.__path__ = [str(pkg_dir)] + comp_mod = types.ModuleType("custom_recipe_pkg.components") + comp_mod.__path__ = [str(pkg_dir / "components")] + root_mod.components = comp_mod + module_name = _BoundRecipeKernelOwner.__module__ + synthetic = types.ModuleType(module_name) + synthetic._BoundRecipeKernelOwner = _BoundRecipeKernelOwner + comp_mod.synthetic = synthetic + monkeypatch.setitem(sys.modules, "custom_recipe_pkg", root_mod) + monkeypatch.setitem(sys.modules, "custom_recipe_pkg.components", comp_mod) + monkeypatch.setitem(sys.modules, module_name, synthetic) + + forward = _BoundRecipeForward(3) + # Without source_roots bound, unguarded unpicklable attributes are not stripped. + with pytest.raises(TypeError, match="cannot be pickled"): + with _guard_serialization(): + compiled = torch.compile( + _execute, + backend=lambda graph, inputs: GraphModuleSerializableCallable(graph), + fullgraph=True, + dynamic=False, + ).aot_compile(((forward,), {})) + type(compiled).serialize(compiled) + + with source_roots((("custom_recipe_pkg", pkg_dir),)): + with _guard_serialization(): + compiled = torch.compile( + _execute, + backend=lambda graph, inputs: GraphModuleSerializableCallable(graph), + fullgraph=True, + dynamic=False, + ).aot_compile(((forward,), {})) + data = type(compiled).serialize(compiled).serialized_data + # rebuild_manifest.weight_views also walks objects from bound source_roots. + owner_with_weight = _BoundRecipeKernelOwner(1) + owner_with_weight.weight = torch.ones(4) + views = list(weight_views({"root": owner_with_weight})) + assert any(name == "root.weight" for name, _, _ in views) + + loaded = type(compiled).deserialize(data) + torch.testing.assert_close(loaded(forward), torch.full((2,), 3.0)) + assert loaded.guard_check(forward) is True + forward.owner.scale = 5 + assert loaded.guard_check(forward) is False + forward.owner.scale = 3 + assert loaded.guard_check(forward) is True + + +def test_guard_pickler_rejects_guarded_triton_compiled_kernel(): + from triton.compiler import CompiledKernel + + kernel = CompiledKernel.__new__(CompiledKernel) + kernel.module = None + with pytest.raises(TypeError, match="cannot serialize a compiled Triton kernel"): + _roundtrip_guard(kernel, guard_tree_values={id(kernel): kernel}) diff --git a/tests/preparation/test_inductor_prepared_winners.py b/tests/preparation/test_inductor_prepared_winners.py index aedc4484b..dd97c7710 100644 --- a/tests/preparation/test_inductor_prepared_winners.py +++ b/tests/preparation/test_inductor_prepared_winners.py @@ -312,3 +312,93 @@ def test_effective_last_snapshot_preserves_the_tuned_winner(monkeypatch): assert len(initial.compile_results) == 2 with pytest.raises(ValueError, match="unresolved"): _freeze_tuning_winners(SimpleNamespace(static_autotuners=snapshots[::-1])) + + +def test_snapshot_and_freeze_prune_or_reject_non_static_triton_compile_results(monkeypatch): + import zlib + from torch._inductor.runtime.triton_heuristics import TritonCompileResult + from triton.compiler import CompiledKernel + from ignition.preparation.inductor_tuning import ( + InductorSelections, + _sanitize_static_bundle, + _snapshot, + ) + + # Simulate a Triton 3.8 CompiledKernel whose local KernelMetadata namedtuple cannot be pickled. + def _make_non_static(config): + kernel = CompiledKernel.__new__(CompiledKernel) + LocalKernelMetadata = namedtuple("KernelMetadata", ["name"]) + kernel.metadata = LocalKernelMetadata("triton_unpicklable") + kernel.packed_metadata = None + kernel.module = None + kernel.function = None + return TritonCompileResult(kernel, config, {}, {"kernel_name": "restored_reduction"}) + + tuner, selected = restored_reduction(monkeypatch) + tuner.compile_results[0].kernel.cubin_raw = b"cubin-bytes" + for attr in ("_precompile_worker", "_ensure_kernel_loaded", "_precompile_config", "_make_launchers"): + tuner.__dict__.pop(attr, None) + tuner.fn = SimpleNamespace(fn=None, __globals__={}, used_global_vals=None, repr=str) + tuner.benchmark_failure_reasons = {} + stored = StoredTuner() + stored.compile_results = list(tuner.compile_results) + stored.inductor_meta = dict(tuner.inductor_meta) + stored.triton_meta = {"device": 0} + stored.device_props = DeviceProperties(0) + losing_cfg = triton.Config({"XBLOCK": 16, "R0_BLOCK": 128}, num_warps=4, num_stages=1) + non_static = _make_non_static(losing_cfg) + tuner.compile_results.append(non_static) + tuner.launchers = [SimpleNamespace(config=selected)] + + # When the winning launcher is static, _snapshot prunes away the non-static candidate before deepcopy/pickle. + entry = StoredEntry("reduction-key", stored, "restored_reduction") + snapped = _snapshot(entry, tuner) + assert len(snapped.kernel.compile_results) == 1 + assert isinstance(snapped.kernel.compile_results[0], StaticTritonCompileResult) + # Pickling the snapped bundle succeeds without hitting KernelMetadata PicklingError. + bundle = StoredBundle(static_autotuners=[snapped], kernel_artifacts=[]) + _sanitize_static_bundle(bundle, frozen=True) + _freeze_tuning_winners(bundle) + assert pickle.dumps(bundle) + + # When the winning launcher itself is non-static, _snapshot and freeze reject it with TypeError. + bad_tuner, _ = restored_reduction(monkeypatch) + bad_tuner.compile_results = [_make_non_static(losing_cfg)] + bad_tuner.launchers = [SimpleNamespace(config=losing_cfg)] + with pytest.raises(TypeError, match="non-static compile result.*StaticTritonCompileResult"): + _snapshot(StoredEntry("bad-key", stored, "restored_reduction"), bad_tuner) + + # Unfrozen bundle sanitization drops stray non-static entries when static entries remain, + # and rejects bundles whose only entry is non-static. + mixed_stored = StoredTuner() + mixed_stored.compile_results = [tuner.compile_results[0], _make_non_static(losing_cfg)] + mixed_stored.inductor_meta = dict(tuner.inductor_meta) + mixed_bundle = StoredBundle( + static_autotuners=[StoredEntry("mixed", mixed_stored, "restored_reduction")], + kernel_artifacts=[], + ) + _sanitize_static_bundle(mixed_bundle, frozen=False) + assert len(mixed_stored.compile_results) == 1 + assert isinstance(mixed_stored.compile_results[0], StaticTritonCompileResult) + + only_bad_stored = StoredTuner() + only_bad_stored.compile_results = [_make_non_static(losing_cfg)] + only_bad_stored.inductor_meta = dict(tuner.inductor_meta) + only_bad_bundle = StoredBundle( + static_autotuners=[StoredEntry("bad", only_bad_stored, "restored_reduction")], + kernel_artifacts=[], + ) + with pytest.raises(TypeError, match="non-static compile result"): + _sanitize_static_bundle(only_bad_bundle, frozen=False) + + # End-to-end InductorSelections.freeze rejects a tuner retaining a non-static winner before pickle.dumps. + sel = InductorSelections(torch.device("cpu")) + fake_graph = SimpleNamespace(_triton_bundle=bundle) + fake_backend = SimpleNamespace( + _serialized_artifact=zlib.compress(pickle.dumps((SimpleNamespace(compiled_fw=SimpleNamespace(result=fake_graph)), {}, {}))), + _tuning_frozen=False, + ) + bound = SimpleNamespace() + sel.forwards[id(bound)] = (fake_backend, fake_graph, {"bad-key": ("id", entry, bad_tuner)}) + with pytest.raises(TypeError, match="non-static compile result"): + sel.freeze(bound) diff --git a/tests/preparation/test_source_identity.py b/tests/preparation/test_source_identity.py index 9ac59984f..7cbe4603b 100644 --- a/tests/preparation/test_source_identity.py +++ b/tests/preparation/test_source_identity.py @@ -21,7 +21,7 @@ def reference(roots): digest = hashlib.sha256() for source in roots: for path in sorted(source.rglob("*")): - if path.is_file() and path.suffix in (".py", ".rs", ".c", ".cu", ".cuh", ".h"): + if path.is_file() and path.suffix in (".py", ".rs", ".c", ".cpp", ".cu", ".cuh", ".h", ".hpp"): digest.update(str(path.relative_to(source)).encode()) digest.update(path.read_bytes()) return digest.hexdigest() @@ -32,6 +32,7 @@ def test_native_identity_matches_pathlib_order_suffixes_and_root_order(tmp_path, for root in (first, second): (root / "nested").mkdir(parents=True) for name, contents in (("nested.py", b"root"), ("nested/a.py", b"child"), + ("nested/ext.cpp", b"cpp"), ("nested/ext.hpp", b"hpp"), (".hidden.cu", b"hidden"), ("UPPER.PY", b"excluded"), ("data.bin", b"excluded"), ("μ.cuh", bytes(range(256)) * 1000)): (first / name).write_bytes(contents) @@ -78,6 +79,19 @@ def test_native_exact_directory_exclusion_preserves_other_roots(tmp_path, native assert native_identity([package], excluded_directories=[package / "data"]) == excluded assert native_identity([package, native], excluded_directories=[package / "data"]) != combined + # Exact file exclusion skips named files while keeping siblings and native sources. + skipped = package / "progress.py" + skipped.write_text("ui = 1\n") + before_file_excl = native_identity( + [package], excluded_directories=[package / "data"], excluded_files=[skipped] + ) + skipped.write_text("ui = 2\n") + assert ( + native_identity([package], excluded_directories=[package / "data"], excluded_files=[skipped]) + == before_file_excl + ) + assert native_identity([package], excluded_directories=[package / "data"]) != before_file_excl + def source_trees(root, *, editable): import shutil