diff --git a/helios/src/runtime_core/format.rs b/helios/src/runtime_core/format.rs index 9d610c502..bc42e5821 100644 --- a/helios/src/runtime_core/format.rs +++ b/helios/src/runtime_core/format.rs @@ -864,4 +864,17 @@ mod tests { value.allocations[0].data_spans = vec![[0, 4000]]; assert!(value.validate().is_err()); } + + #[test] + fn graph_instantiation_flags_accept_auto_free_and_node_priority_only() { + let mut value = core(); + for flags in [0, 1, 8, 9] { + value.graphs[0].flags = flags; + assert!(value.validate().is_ok(), "flags={flags}"); + } + for flags in [2, 4, 16, u64::MAX] { + value.graphs[0].flags = flags; + assert!(value.validate().is_err(), "flags={flags}"); + } + } } diff --git a/helios/src/runtime_core/mod.rs b/helios/src/runtime_core/mod.rs index 8b104e571..5039bf13b 100644 --- a/helios/src/runtime_core/mod.rs +++ b/helios/src/runtime_core/mod.rs @@ -24,6 +24,8 @@ mod host; mod limits; mod metadata; #[cfg(test)] +mod node_priority_tests; +#[cfg(test)] mod programmatic_edge_tests; pub use metadata::{unverified_metadata, unverified_metadata_selected}; mod memory; diff --git a/helios/src/runtime_core/node_priority_tests.rs b/helios/src/runtime_core/node_priority_tests.rs new file mode 100644 index 000000000..9a0946120 --- /dev/null +++ b/helios/src/runtime_core/node_priority_tests.rs @@ -0,0 +1,356 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 Flare community contributors + * SPDX-License-Identifier: Apache-2.0 + */ + +use super::{payload::Files, protection::AuthorizedKind, *}; +use crate::ReplayWorker; +use std::ffi::{CStr, c_char, c_int, c_void}; +use std::sync::Mutex; +use std::time::Duration; + +#[repr(C)] +struct CallbackData { + site: c_int, + name: *const c_char, + params: *const c_void, + return_value: *const c_int, +} + +#[repr(C)] +struct GraphInstantiateWithFlagsParams { + executable: *const Handle, + graph: Handle, + flags: u64, +} + +type CuptiCallback = unsafe extern "C" fn(Handle, c_int, u32, *const CallbackData); + +unsafe extern "C" fn record_graph_instantiate( + user: Handle, + domain: c_int, + _: u32, + data: *const CallbackData, +) { + if domain != 1 || data.is_null() { + return; + } + let data = unsafe { &*data }; + if data.site != 1 || data.name.is_null() || data.params.is_null() || data.return_value.is_null() + { + return; + } + let name = unsafe { CStr::from_ptr(data.name) }.to_bytes(); + if name != b"cuGraphInstantiateWithFlags" || unsafe { *data.return_value } != 0 { + return; + } + let params = unsafe { &*data.params.cast::() }; + if params.executable.is_null() { + return; + } + let handle = unsafe { *params.executable } as usize; + let recorded = unsafe { &*user.cast::>>() }; + recorded.lock().unwrap().push((handle, params.flags)); +} + +struct InstantiateWatch { + library: Option, + subscriber: Handle, + unsubscribe: unsafe extern "C" fn(Handle) -> c_int, + calls: Box>>, +} + +impl InstantiateWatch { + fn new() -> Self { + let cupti_path = std::env::var_os("FLARE_NODE_PRIORITY_CUPTI_PATH") + .unwrap_or_else(|| "libcupti.so".into()); + unsafe { + let library = libloading::Library::new(cupti_path).unwrap(); + let subscribe = library + .get:: c_int>( + b"cuptiSubscribe\0", + ) + .unwrap(); + let enable = library + .get:: c_int>(b"cuptiEnableDomain\0") + .unwrap(); + let unsubscribe = *library + .get:: c_int>(b"cuptiUnsubscribe\0") + .unwrap(); + let calls = Box::new(Mutex::new(Vec::new())); + let mut subscriber = std::ptr::null_mut(); + assert_eq!( + subscribe( + &mut subscriber, + record_graph_instantiate, + (&*calls as *const Mutex>) + .cast_mut() + .cast(), + ), + 0 + ); + assert_eq!(enable(1, subscriber, 1), 0); + Self { + library: Some(library), + subscriber, + unsubscribe, + calls, + } + } + } + + fn take(&self) -> Vec<(usize, u64)> { + std::mem::take(&mut *self.calls.lock().unwrap()) + } +} + +impl Drop for InstantiateWatch { + fn drop(&mut self) { + unsafe { + (self.unsubscribe)(self.subscriber); + } + // Keep libcupti mapped after unsubscription so the CUDA driver never jumps into unmapped pages. + std::mem::forget(self.library.take()); + } +} + +#[test] +#[ignore = "requires FLARE_NODE_PRIORITY_TEST_CORE exported by node_priority_core_fixture.py on the assigned GPU"] +fn exported_node_priority_core_instantiates_and_replays_in_helios() { + let root = + std::path::PathBuf::from(std::env::var_os("FLARE_NODE_PRIORITY_TEST_CORE").unwrap()); + let authorized = test_support::authorize(root.join("core")); + let AuthorizedKind::Payload(payload) = authorized.kind else { + panic!("node priority fixture must publish a payload core"); + }; + let (archive, mut cores) = payload.into_parts(); + let core = cores.remove(0); + core.validate().unwrap(); + archive.validate(&core).unwrap(); + let flags_by_name: HashMap<_, _> = core + .graphs + .iter() + .map(|graph| (graph.name.as_str(), graph.flags)) + .collect(); + assert_eq!(flags_by_name.get("decode").copied(), Some(9)); + assert_eq!(flags_by_name.get("tune").copied(), Some(1)); + + let decode_graph = core + .graphs + .iter() + .find(|graph| graph.name == "decode") + .unwrap(); + let mut records = archive.records(&core, &decode_graph.resource).unwrap(); + let mut priorities = Vec::new(); + for _ in 0..decode_graph.node_count { + let node = protobuf::node(records.read().unwrap()).unwrap(); + if let Node::Kernel { attributes, .. } = node { + for attribute in attributes { + if attribute.id == 8 { + let priority = + i32::from_ne_bytes(attribute.value.data[..4].try_into().unwrap()); + priorities.push(priority); + } + } + } + } + assert!( + priorities.iter().any(|&priority| priority < 0) + && priorities.iter().any(|&priority| priority == 0), + "decode graph must record both auxiliary-stream (< 0) and main-stream (0) kernel priorities: {priorities:?}" + ); + + let watch = InstantiateWatch::new(); + let owner = + unsafe { NativeResources::load(test_support::authorize(root.join("core")), 0).unwrap() }; + let instantiated: HashMap = watch.take().into_iter().collect(); + + let decode_index = owner + .graph_names() + .iter() + .position(|name| name == "decode") + .unwrap(); + let tune_index = owner + .graph_names() + .iter() + .position(|name| name == "tune") + .unwrap(); + assert_eq!( + instantiated + .get(&(owner.executables[decode_index] as usize)) + .copied(), + Some(9) + ); + assert_eq!( + instantiated + .get(&(owner.executables[tune_index] as usize)) + .copied(), + Some(1) + ); + + unsafe { + let library = crate::os::cuda_library().unwrap(); + let exec_get_flags: libloading::Symbol< + '_, + unsafe extern "C" fn(Handle, *mut u64) -> c_int, + > = library.get(b"cuGraphExecGetFlags\0").unwrap(); + owner + .driver + .check("cuCtxSetCurrent", (owner.driver.context_set)(owner.context)) + .unwrap(); + let (mut decode_flags, mut tune_flags) = (0u64, 0u64); + owner + .driver + .check( + "cuGraphExecGetFlags(decode)", + exec_get_flags(owner.executables[decode_index], &mut decode_flags), + ) + .unwrap(); + owner + .driver + .check( + "cuGraphExecGetFlags(tune)", + exec_get_flags(owner.executables[tune_index], &mut tune_flags), + ) + .unwrap(); + // CUDA consumes USE_NODE_PRIORITY (8) during cuGraphInstantiateWithFlags and + // retains AUTO_FREE_ON_LAUNCH (1) on the resulting CUgraphExec handle. + assert_eq!(decode_flags, 1); + assert_eq!(tune_flags, 1); + } + + let manifest = owner.execution_manifest().unwrap(); + manifest.validate().unwrap(); + let source = manifest.buffer("source").unwrap().clone(); + let main_output = manifest.buffer("main_output").unwrap().clone(); + let aux_output = manifest.buffer("aux_output").unwrap().clone(); + let selector = manifest.buffer("selector").unwrap().clone(); + + let worker = unsafe { ReplayWorker::new(owner.graph_bundle(), 1).unwrap() }; + unsafe { + owner + .driver + .check("cuCtxSetCurrent", (owner.driver.context_set)(owner.context)) + .unwrap(); + owner + .driver + .check( + "cuMemsetD8_v2", + (owner.driver.zero)(selector.address as u64, 0, selector.nbytes), + ) + .unwrap(); + owner + .driver + .check("cuCtxSynchronize", (owner.driver.context_sync)()) + .unwrap(); + } + let tune_ticket = worker.submit(tune_index, 1).unwrap(); + let tuned = worker.poll(Duration::from_secs(10)).unwrap().unwrap(); + assert_eq!(tuned.ticket, tune_ticket); + assert!(tuned.error.is_none(), "{:?}", tuned.error); + let mut selector_bytes = [0u8; 4]; + unsafe { + owner + .driver + .check("cuCtxSetCurrent", (owner.driver.context_set)(owner.context)) + .unwrap(); + owner + .driver + .check("cuCtxSynchronize", (owner.driver.context_sync)()) + .unwrap(); + owner + .driver + .check( + "cuMemcpyDtoH_v2", + (owner.driver.download)( + selector_bytes.as_mut_ptr().cast(), + selector.address as u64, + selector_bytes.len(), + ), + ) + .unwrap(); + } + assert_eq!(i32::from_le_bytes(selector_bytes), 7); + + for (repetitions, scale) in [(2u32, 1.0f32), (3u32, -2.5f32)] { + let inputs: Vec = (0..1024).map(|index| index as f32 * scale + 0.5).collect(); + let input_bytes: Vec = inputs.iter().flat_map(|value| value.to_le_bytes()).collect(); + assert_eq!(input_bytes.len(), source.nbytes); + unsafe { + owner + .driver + .check("cuCtxSetCurrent", (owner.driver.context_set)(owner.context)) + .unwrap(); + for span in [&main_output, &aux_output] { + owner + .driver + .check( + "cuMemsetD8_v2", + (owner.driver.zero)(span.address as u64, 0xff, span.nbytes), + ) + .unwrap(); + } + owner + .driver + .check( + "cuMemcpyHtoD_v2", + (owner.driver.upload)( + source.address as u64, + input_bytes.as_ptr().cast(), + input_bytes.len(), + ), + ) + .unwrap(); + owner + .driver + .check("cuCtxSynchronize", (owner.driver.context_sync)()) + .unwrap(); + } + let ticket = worker.submit(decode_index, repetitions).unwrap(); + let completed = worker.poll(Duration::from_secs(10)).unwrap().unwrap(); + assert_eq!(completed.ticket, ticket); + assert!(completed.error.is_none(), "{:?}", completed.error); + let mut main_bytes = vec![0u8; main_output.nbytes]; + let mut aux_bytes = vec![0u8; aux_output.nbytes]; + unsafe { + owner + .driver + .check("cuCtxSetCurrent", (owner.driver.context_set)(owner.context)) + .unwrap(); + owner + .driver + .check("cuCtxSynchronize", (owner.driver.context_sync)()) + .unwrap(); + owner + .driver + .check( + "cuMemcpyDtoH_v2", + (owner.driver.download)( + main_bytes.as_mut_ptr().cast(), + main_output.address as u64, + main_bytes.len(), + ), + ) + .unwrap(); + owner + .driver + .check( + "cuMemcpyDtoH_v2", + (owner.driver.download)( + aux_bytes.as_mut_ptr().cast(), + aux_output.address as u64, + aux_bytes.len(), + ), + ) + .unwrap(); + } + for (index, &x) in inputs.iter().enumerate() { + let offset = index * 4; + let actual_main = u32::from_le_bytes(main_bytes[offset..offset + 4].try_into().unwrap()); + let actual_aux = u32::from_le_bytes(aux_bytes[offset..offset + 4].try_into().unwrap()); + assert_eq!(actual_main, (x * 3.0 + 4.0).to_bits(), "main_output[{index}]"); + assert_eq!(actual_aux, (x * 2.0 - 5.0).to_bits(), "aux_output[{index}]"); + } + } + assert!(worker.close().drained); +} diff --git a/helios/tests/node_priority_core_fixture.py b/helios/tests/node_priority_core_fixture.py new file mode 100644 index 000000000..01dd91271 --- /dev/null +++ b/helios/tests/node_priority_core_fixture.py @@ -0,0 +1,92 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 Flare community contributors +# SPDX-License-Identifier: Apache-2.0 + +"""Export a signed single-rank core with node-priority serving and startup tuning graphs.""" + +from contextlib import nullcontext +from pathlib import Path +import sys +from types import SimpleNamespace + +import torch + +from fixture_frontend import server_config +from signing import publisher +from ignition.preparation.capture import capture_forwards +from ignition.preparation.core_storage import CoreStorage +from ignition.preparation.execution import GraphSignature, PreparedExecution, TuningGraph +from ignition.preparation.module_images import ModuleImages +from ignition.preparation.runtime_core import capture_graph, export_model, instantiate_graph +from ignition.preparation.scratch import ScratchArena + + +@torch.no_grad() +def prepare(root: Path) -> None: + root.mkdir(parents=True, exist_ok=True) + torch.cuda.set_device(0) + with ModuleImages() as images, CoreStorage() as storage: + scratch = ScratchArena(device=0, overlap=True) + source = torch.arange(1024, device="cuda", dtype=torch.float32) + main_output = torch.zeros_like(source) + aux_output = torch.zeros_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) + selector = torch.zeros(1, device="cuda", dtype=torch.int32) + status = torch.ones(1, device="cuda", dtype=torch.int32) + aux = scratch.auxiliary_stream + + def forward(): + current = torch.cuda.current_stream() + aux.wait_stream(current) + with torch.cuda.stream(aux): + aux_output.copy_(source * 2.0 - 5.0) + main_output.copy_(source * 3.0 + 4.0) + current.wait_stream(aux) + + stream = torch.cuda.Stream() + graphs, _ = capture_forwards( + {"decode": forward}, + {"decode": GraphSignature("decode", 1, 1, ("source",))}, + session=SimpleNamespace(capture=nullcontext), + device=0, + stream=stream, + pool=storage.graph_pool.id, + warmup_storage=storage, + retain_graphs=True, + compile_decoder=False, + ) + tuner = capture_graph(retain_graphs=True) + with torch.cuda.graph(tuner, pool=storage.graph_pool.id, stream=stream): + selector.fill_(7) + instantiate_graph(tuner) + try: + buffers = dict( + source=source, + main_output=main_output, + aux_output=aux_output, + frame_index=frame, + submission_sequence=sequence, + completion_records=records, + selector=selector, + status=status, + ) + prepared = PreparedExecution( + device=0, + graphs=graphs, + buffers=buffers, + max_active=1, + signatures={"decode": GraphSignature("decode", 1, 1, ("source",))}, + tuning_graphs={"tune": TuningGraph(tuner, ("selector",), "status")}, + resources=(storage, scratch), + ) + prepared.server_config = server_config(root) + prepared.core_data = None + export_model(prepared, images, storage, root / "core", options={}, publisher=publisher()) + finally: + graphs["decode"].reset() + tuner.reset() + + +if __name__ == "__main__": + prepare(Path(sys.argv[1])) diff --git a/ignition/preparation/runtime_core.py b/ignition/preparation/runtime_core.py index 0a439dd64..def53ff3d 100644 --- a/ignition/preparation/runtime_core.py +++ b/ignition/preparation/runtime_core.py @@ -8,7 +8,7 @@ import ctypes as C from dataclasses import asdict, dataclass -from functools import partial +from functools import lru_cache, partial import os import json from pathlib import Path @@ -90,6 +90,11 @@ def check(self, name, status): raise RuntimeError(f"{name}: CUDA {status}: {message.value!r}") +@lru_cache(maxsize=1) +def _cuda_driver() -> _Cuda: + return _Cuda() + + class RuntimeCore: """Metadata adapter retaining captured graph and allocation owners during native export.""" @@ -189,12 +194,56 @@ def reset(self): self.owners = () -def record_export_graph(graph, storage, *, owners=()): +CUDA_GRAPH_INSTANTIATE_FLAG_AUTO_FREE_ON_LAUNCH = 1 +CUDA_GRAPH_INSTANTIATE_FLAG_USE_NODE_PRIORITY = 8 +PERMITTED_CUDA_GRAPH_INSTANTIATE_FLAGS = ( + CUDA_GRAPH_INSTANTIATE_FLAG_AUTO_FREE_ON_LAUNCH + | CUDA_GRAPH_INSTANTIATE_FLAG_USE_NODE_PRIORITY +) + + +def _executable_instantiation_flags(graph) -> int: + """Read the CUDA instantiation bitmask recorded on a live ``CUgraphExec`` handle.""" + executable = int(graph.raw_cuda_graph_exec()) + flags = C.c_uint64(0) + _cuda_driver().call("cuGraphExecGetFlags", C.c_void_p(executable), C.byref(flags)) + return int(flags.value) + + +def record_export_graph( + graph, + storage, + *, + owners=(), + instantiation_flags=CUDA_GRAPH_INSTANTIATE_FLAG_USE_NODE_PRIORITY, +): """Retain a captured template, its executable and external export resources. Owners must not reference the graph: Torch's destruction finalizer retains them independently. Native replay callers must drain before resetting graphs. + When ``instantiation_flags`` is an integer bitmask, the graph must retain a + live CUDA template without post-instantiation release metadata; export + combines ``instantiation_flags`` with any permitted flags already present on + the instantiated executable so Helios instantiates the graph with matching + flags while honoring per-node stream priorities. Passing ``None`` clears any + prior ``_flare_instantiation_flags`` override so export reads flags from the + live executable or recorded metadata. """ + if instantiation_flags is not None: + if ( + type(instantiation_flags) is not int + or instantiation_flags < 0 + or instantiation_flags & ~PERMITTED_CUDA_GRAPH_INSTANTIATE_FLAGS + ): + raise ValueError("graph instantiation flags may only select automatic free and node priority") + if getattr(graph, "_flare_graph_metadata", None) is not None: + raise ValueError("graph instantiation flags require a retained CUDA graph template") + try: + template = int(graph.raw_cuda_graph()) + except RuntimeError as error: + raise ValueError("graph instantiation flags require a retained CUDA graph template") from error + if not template: + raise ValueError("graph instantiation flags require a retained CUDA graph template") pools = (storage.pool, storage.graph_pool) owned = {pool.id for pool in pools} if not set(graph.pools()) <= owned: @@ -203,6 +252,17 @@ def record_export_graph(graph, storage, *, owners=()): # Release these references only when the graph is reset or collected. graph.retain_object((pools, tuple(owners)), synchronize_before_release=True) instantiate_graph(graph) + if hasattr(graph, "_flare_instantiation_flags"): + delattr(graph, "_flare_instantiation_flags") + if instantiation_flags is not None: + prior_flags = _executable_instantiation_flags(graph) + if ( + type(prior_flags) is not int + or prior_flags < 0 + or prior_flags & ~PERMITTED_CUDA_GRAPH_INSTANTIATE_FLAGS + ): + raise ValueError("captured graph executable carries unsupported CUDA instantiation flags") + graph._flare_instantiation_flags = prior_flags | instantiation_flags return graph @@ -244,9 +304,12 @@ def _graphs(graphs, *, recorder=None): continue flags = getattr(graph, "_flare_instantiation_flags", None) if flags is not None: - if type(flags) is not int or flags < 0 or flags & ~9: + if type(flags) is not int or flags < 0 or flags & ~PERMITTED_CUDA_GRAPH_INSTANTIATE_FLAGS: raise ValueError("graph instantiation flags may only select automatic free and node priority") - result.append(dict(name=name, graph=int(graph.raw_cuda_graph()), instantiate_flags=flags)) + template = int(graph.raw_cuda_graph()) + if not template: + raise ValueError("graph instantiation flags require a retained CUDA graph template") + result.append(dict(name=name, graph=template, instantiate_flags=flags)) continue executable = int(graph.raw_cuda_graph_exec()) metadata = getattr(graph, "_flare_graph_metadata", None) diff --git a/tests/preparation/test_capture_graph_metadata.py b/tests/preparation/test_capture_graph_metadata.py index 7bdc3ed59..aa85a1259 100644 --- a/tests/preparation/test_capture_graph_metadata.py +++ b/tests/preparation/test_capture_graph_metadata.py @@ -14,9 +14,11 @@ import torch from torch.cuda.graphs import CUDAGraph, _RetainedCallbacks -from ignition.preparation import capture +from ignition.preparation import capture, runtime_core from ignition.preparation.module_images import ModuleImages from ignition.preparation.runtime_core import ( + CUDA_GRAPH_INSTANTIATE_FLAG_AUTO_FREE_ON_LAUNCH, + CUDA_GRAPH_INSTANTIATE_FLAG_USE_NODE_PRIORITY, RecordedExportGraph, _graphs, capture_graph, instantiate_graph, record_export_graph, ) @@ -26,8 +28,9 @@ class Graph: register_destroy_callback = CUDAGraph.register_destroy_callback retain_object = CUDAGraph.retain_object - def __init__(self, keep_graph=False): + def __init__(self, keep_graph=False, exec_flags=CUDA_GRAPH_INSTANTIATE_FLAG_AUTO_FREE_ON_LAUNCH): self.keep_graph = keep_graph + self.exec_flags = exec_flags self._post_instantiate_hooks = OrderedDict() self._arm() self.template = self.executable = 0 @@ -107,6 +110,7 @@ def recorder(monkeypatch): monkeypatch.setattr(Graph, "_handles", itertools.count(12), raising=False) monkeypatch.setattr(torch.cuda, "CUDAGraph", Graph) monkeypatch.setattr(ModuleImages, "current", classmethod(lambda cls: SimpleNamespace(native=native))) + monkeypatch.setattr(runtime_core, "_executable_instantiation_flags", lambda graph: graph.exec_flags) return native @@ -200,14 +204,168 @@ def test_export_instantiates_and_retains_executable(monkeypatch, recorder): graph.capture_end() kernel_owner = SimpleNamespace() returned = record_export_graph(graph, storage, owners=(kernel_owner,)) + expected_combined = ( + CUDA_GRAPH_INSTANTIATE_FLAG_AUTO_FREE_ON_LAUNCH + | CUDA_GRAPH_INSTANTIATE_FLAG_USE_NODE_PRIORITY + ) assert returned is graph assert graph.instantiations == 1 assert graph.template == 11 assert graph.executable == 12 - assert _graphs({"decode": graph}) == [dict(name="decode", graph=11, executable=12)] + assert graph._flare_instantiation_flags == expected_combined + assert _graphs({"decode": graph}) == [ + dict(name="decode", graph=11, instantiate_flags=expected_combined) + ] assert not recorder.templates assert recorder.events == [] + no_autofree = Graph(keep_graph=True, exec_flags=0) + no_autofree.pools = lambda: [(0, 2)] + no_autofree.capture_end() + record_export_graph(no_autofree, storage, owners=(kernel_owner,)) + assert no_autofree._flare_instantiation_flags == CUDA_GRAPH_INSTANTIATE_FLAG_USE_NODE_PRIORITY + assert _graphs({"decode": no_autofree}) == [ + dict(name="decode", graph=11, instantiate_flags=CUDA_GRAPH_INSTANTIATE_FLAG_USE_NODE_PRIORITY) + ] + + preserved_only = Graph(keep_graph=True, exec_flags=CUDA_GRAPH_INSTANTIATE_FLAG_AUTO_FREE_ON_LAUNCH) + preserved_only.pools = lambda: [(0, 2)] + preserved_only.capture_end() + record_export_graph(preserved_only, storage, owners=(kernel_owner,), instantiation_flags=0) + assert preserved_only._flare_instantiation_flags == CUDA_GRAPH_INSTANTIATE_FLAG_AUTO_FREE_ON_LAUNCH + + plain = Graph(keep_graph=True) + plain.pools = lambda: [(0, 2)] + plain.capture_end() + record_export_graph(plain, storage, owners=(kernel_owner,)) + assert plain._flare_instantiation_flags == expected_combined + record_export_graph(plain, storage, owners=(kernel_owner,), instantiation_flags=None) + assert not hasattr(plain, "_flare_instantiation_flags") + assert _graphs({"decode": plain}) == [dict(name="decode", graph=11, executable=plain.executable)] + + recorded_meta = capture_graph(retain_graphs=True) + recorded_meta.pools = lambda: [(0, 2)] + recorded_meta.capture_end() + with pytest.raises(ValueError, match="retained CUDA graph template"): + record_export_graph(recorded_meta, storage, owners=(kernel_owner,)) + assert recorded_meta.instantiations == 1 and not recorded_meta._retained.objects + assert not hasattr(recorded_meta, "_flare_instantiation_flags") + recorded_meta._flare_instantiation_flags = expected_combined + record_export_graph(recorded_meta, storage, owners=(kernel_owner,), instantiation_flags=None) + assert not hasattr(recorded_meta, "_flare_instantiation_flags") + assert _graphs({"decode": recorded_meta}) == [ + dict(name="decode", graph=0, executable=recorded_meta.executable) + ] + + released = Graph(keep_graph=False) + released.pools = lambda: [(0, 2)] + released.capture_end() + with pytest.raises(ValueError, match="retained CUDA graph template"): + record_export_graph(released, storage, owners=(kernel_owner,)) + assert released.instantiations == 1 and not released._retained.objects + assert not hasattr(released, "_flare_instantiation_flags") + + zero_template = Graph(keep_graph=True) + zero_template.pools = lambda: [(0, 2)] + zero_template.raw_cuda_graph = lambda: 0 + with pytest.raises(ValueError, match="retained CUDA graph template"): + record_export_graph(zero_template, storage, owners=(kernel_owner,)) + assert zero_template.instantiations == 0 and not zero_template._retained.objects + assert not hasattr(zero_template, "_flare_instantiation_flags") + + unsupported_exec = Graph(keep_graph=True, exec_flags=2) + unsupported_exec.pools = lambda: [(0, 2)] + unsupported_exec.capture_end() + unsupported_exec._flare_instantiation_flags = expected_combined + with pytest.raises(ValueError, match="unsupported CUDA instantiation flags"): + record_export_graph(unsupported_exec, storage, owners=(kernel_owner,)) + assert not hasattr(unsupported_exec, "_flare_instantiation_flags") + + bad = Graph(keep_graph=True) + bad.pools = lambda: [(0, 2)] + bad.capture_end() + with pytest.raises(ValueError, match="instantiation flags"): + record_export_graph(bad, storage, instantiation_flags=2) + assert bad.instantiations == 0 and not bad._retained.objects + + +def test_executable_instantiation_flags_reuses_cached_cuda_driver(monkeypatch): + import ctypes as C + + inits = 0 + observed_handles = [] + flags_by_handle = {21: 1, 22: 9} + + class FakeCuda: + def __init__(self): + nonlocal inits + inits += 1 + + def call(self, name, executable, out_flags): + assert name == "cuGraphExecGetFlags" + handle = int(executable.value) + observed_handles.append(handle) + C.cast(out_flags, C.POINTER(C.c_uint64))[0] = flags_by_handle[handle] + + runtime_core._cuda_driver.cache_clear() + try: + monkeypatch.setattr(runtime_core, "_Cuda", FakeCuda) + first = SimpleNamespace(raw_cuda_graph_exec=lambda: 21) + second = SimpleNamespace(raw_cuda_graph_exec=lambda: 22) + assert runtime_core._executable_instantiation_flags(first) == 1 + assert runtime_core._executable_instantiation_flags(second) == 9 + assert inits == 1 + assert observed_handles == [21, 22] + finally: + runtime_core._cuda_driver.cache_clear() + + +def test_capture_forwards_export_sets_node_priority_instantiation_flag(monkeypatch, recorder): + stream = SimpleNamespace(wait_stream=lambda other: None, synchronize=lambda: None) + storage = SimpleNamespace( + pool=SimpleNamespace(id=(0, 1)), + graph_pool=SimpleNamespace(id=(0, 2)), + transient=nullcontext, + retain_transient_backing=nullcontext, + ) + + class ExportGraph(Graph): + def pools(self): + return [(0, 2)] + + @contextmanager + def graph_scope(graph, **kwargs): + yield + graph.capture_end() + + monkeypatch.setattr(torch.cuda, "CUDAGraph", ExportGraph) + for name, value in dict(current_stream=lambda device: stream, stream=lambda stream: nullcontext(), + synchronize=lambda device: None, graph=graph_scope, + mem_get_info=lambda device: (1024, 2048), memory_allocated=lambda device: 0, + memory_reserved=lambda device: 0).items(): + monkeypatch.setattr(torch.cuda, name, value) + monkeypatch.setattr(capture, "_warmup_stream", lambda device: stream) + monkeypatch.setattr(capture, "_seed_warmup_workspaces", lambda stream, device: None) + graphs, _ = capture.capture_forwards( + {"prefill": lambda: None, "decode": lambda: None}, + {"prefill": SimpleNamespace(kind="prefill"), "decode": SimpleNamespace(kind="decode")}, + session=SimpleNamespace(capture=nullcontext), + device="cpu", + stream=stream, + pool=(0, 2), + compile_decoder=False, + retain_graphs=True, + warmup_storage=storage, + ) + expected_combined = ( + CUDA_GRAPH_INSTANTIATE_FLAG_AUTO_FREE_ON_LAUNCH + | CUDA_GRAPH_INSTANTIATE_FLAG_USE_NODE_PRIORITY + ) + assert _graphs(graphs) == [ + dict(name="prefill", graph=11, instantiate_flags=expected_combined), + dict(name="decode", graph=11, instantiate_flags=expected_combined), + ] + @pytest.mark.parametrize("release", ("reset", "collection")) def test_export_graph_retains_external_owners_until_release(recorder, release): diff --git a/tests/preparation/test_recorded_export_graph_cuda.py b/tests/preparation/test_recorded_export_graph_cuda.py index eb5376d79..537379291 100644 --- a/tests/preparation/test_recorded_export_graph_cuda.py +++ b/tests/preparation/test_recorded_export_graph_cuda.py @@ -82,9 +82,31 @@ def forward(): recorder=images.native, owners=(bundle, storage)) package.write(path, bundle.graphs, execution=manifest, sources=True) index, _ = read_sources(path) - assert index.ranks[0].graphs[0].flags == 1 - assert index.ranks[0].graphs[0].node_count > 0 - assert {value.name for value in index.ranks[0].graphs} == {"decode", "tune"} + flags_by_name = {value.name: value.flags for value in index.ranks[0].graphs} + assert flags_by_name == {"decode": 9, "tune": 1} + assert all(value.node_count > 0 for value in index.ranks[0].graphs) graph.reset() graph.reset() tuner.reset() + + +@pytest.mark.skipif(os.environ.get("FLARE_RUN_CUDA_TESTS") != "1", reason="requires explicit CUDA test opt-in") +def test_exported_node_priority_core_loads_and_replays_in_helios(tmp_path): + from ignition.preparation.module_images import cupti_library + + root = Path(__file__).resolve().parents[2] + fixture_env = {**os.environ, "PYTHONPATH": os.pathsep.join( + filter(None, [str(root), str(root / "helios/tests"), os.environ.get("PYTHONPATH")]))} + subprocess.run([ + sys.executable, str(root / "helios/tests/node_priority_core_fixture.py"), str(tmp_path), + ], check=True, cwd=root, timeout=120, env=fixture_env) + subprocess.run([ + "cargo", "test", "--locked", "--release", "--manifest-path", str(root / "helios/Cargo.toml"), + "--no-default-features", "--features", "runtime-core", "--lib", + "exported_node_priority_core_instantiates_and_replays_in_helios", "--", "--ignored", + ], check=True, cwd=root, timeout=180, + env={ + **os.environ, + "FLARE_NODE_PRIORITY_TEST_CORE": str(tmp_path), + "FLARE_NODE_PRIORITY_CUPTI_PATH": str(cupti_library()), + }) diff --git a/tests/preparation/test_runtime_core.py b/tests/preparation/test_runtime_core.py index ca5ef481a..54a8a0a59 100644 --- a/tests/preparation/test_runtime_core.py +++ b/tests/preparation/test_runtime_core.py @@ -37,6 +37,14 @@ def test_template_export_rejects_unsupported_flags(flags): _graphs({"decode": SimpleNamespace(_flare_instantiation_flags=flags)}) +def test_template_export_rejects_released_zero_template(): + from types import SimpleNamespace + from ignition.preparation.runtime_core import _graphs + + with pytest.raises(ValueError, match="retained CUDA graph template"): + _graphs({"decode": SimpleNamespace(raw_cuda_graph=lambda: 0, _flare_instantiation_flags=8)}) + + @pytest.mark.parametrize("graph", [dict(name="decode"), dict(name="decode", recorded=1, graph=1), dict(name="decode", recorded=1, executable=1), dict(name="decode", recorded=1, instantiate_flags=1), dict(name="decode", graph=1, executable=1, instantiate_flags=1),