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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions helios/src/runtime_core/format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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}");
}
}
}
2 changes: 2 additions & 0 deletions helios/src/runtime_core/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
356 changes: 356 additions & 0 deletions helios/src/runtime_core/node_priority_tests.rs
Original file line number Diff line number Diff line change
@@ -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::<GraphInstantiateWithFlagsParams>() };
if params.executable.is_null() {
return;
}
let handle = unsafe { *params.executable } as usize;
let recorded = unsafe { &*user.cast::<Mutex<Vec<(usize, u64)>>>() };
recorded.lock().unwrap().push((handle, params.flags));
}

struct InstantiateWatch {
library: Option<libloading::Library>,
subscriber: Handle,
unsubscribe: unsafe extern "C" fn(Handle) -> c_int,
calls: Box<Mutex<Vec<(usize, u64)>>>,
}

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::<unsafe extern "C" fn(*mut Handle, CuptiCallback, Handle) -> c_int>(
b"cuptiSubscribe\0",
)
.unwrap();
let enable = library
.get::<unsafe extern "C" fn(u32, Handle, c_int) -> c_int>(b"cuptiEnableDomain\0")
.unwrap();
let unsubscribe = *library
.get::<unsafe extern "C" fn(Handle) -> 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<Vec<(usize, u64)>>)
.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<usize, u64> = 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<f32> = (0..1024).map(|index| index as f32 * scale + 0.5).collect();
let input_bytes: Vec<u8> = 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);
}
Loading