pub struct Plan { /* private fields */ }Implementations§
Source§impl Plan
impl Plan
Sourcepub fn new(tasks: Vec<Task>) -> Result<Self, &'static str>
pub fn new(tasks: Vec<Task>) -> Result<Self, &'static str>
Examples found in repository?
examples/hash_assets.rs (lines 37-45)
14fn main() -> Result<(), Box<dyn std::error::Error>> {
15 let start = Instant::now();
16 let mut args = std::env::args_os().skip(1);
17 let directory = PathBuf::from(args.next().ok_or("missing input directory")?);
18 let workers: usize = args
19 .next()
20 .ok_or("missing worker count")?
21 .to_string_lossy()
22 .parse()?;
23 if workers == 0 {
24 return Err("worker count must be positive".into());
25 }
26 let mut files = Vec::new();
27 for entry in fs::read_dir(directory)? {
28 let entry = entry?;
29 if entry.file_type()?.is_file() {
30 files.push(entry.path());
31 }
32 }
33 files.sort();
34 let outputs: Vec<OnceLock<[u8; 32]>> = (0..files.len()).map(|_| OnceLock::new()).collect();
35 let next = AtomicUsize::new(0);
36 let workers = workers.min(files.len());
37 let plan = Plan::new(
38 (0..workers)
39 .map(|_| Task {
40 dependencies: Vec::new(),
41 device: Device::Cpu,
42 memory_bytes: 128 * 1024,
43 })
44 .collect(),
45 )?;
46 plan.execute(
47 Limits {
48 cpu: workers,
49 gpu: 0,
50 memory_bytes: workers * 128 * 1024,
51 },
52 |_, _| {
53 let mut buffer = vec![0; 64 * 1024];
54 loop {
55 let index = next.fetch_add(1, Ordering::Relaxed);
56 let Some(path) = files.get(index) else { break };
57 let mut reader = BufReader::with_capacity(
58 buffer.len(),
59 fs::File::open(path).map_err(|e| e.to_string())?,
60 );
61 let mut hash = Sha256::new();
62 loop {
63 let size = reader.read(&mut buffer).map_err(|e| e.to_string())?;
64 if size == 0 {
65 break;
66 }
67 hash.update(&buffer[..size]);
68 }
69 outputs[index]
70 .set(hash.finalize().into())
71 .map_err(|_| "duplicate output")?;
72 }
73 Ok(())
74 },
75 )?;
76 let mut manifest = Sha256::new();
77 for (file, hash) in files.iter().zip(outputs) {
78 let name = file.file_name().unwrap().as_encoded_bytes();
79 manifest.update((name.len() as u64).to_le_bytes());
80 manifest.update(name);
81 manifest.update(hash.into_inner().unwrap());
82 }
83 println!(
84 "files={} manifest={:x} elapsed_ns={}",
85 files.len(),
86 manifest.finalize(),
87 start.elapsed().as_nanos()
88 );
89 Ok(())
90}More examples
examples/propagate.rs (lines 27-43)
8fn main() -> Result<(), Box<dyn std::error::Error>> {
9 let mut args = std::env::args().skip(1);
10 let input = std::fs::read_to_string(args.next().ok_or("missing graph")?)?;
11 let hybrid = args.next().as_deref() == Some("hybrid");
12 let total = Instant::now();
13 let mut offsets = vec![0];
14 let mut sources = Vec::new();
15 let mut seeds = Vec::new();
16 for line in input.lines() {
17 let mut fields = line.split_whitespace();
18 seeds.push(fields.next().ok_or("missing seed")?.parse::<u32>()?);
19 for field in fields {
20 sources.push(field.parse::<u32>()?);
21 }
22 offsets.push(u32::try_from(sources.len())?);
23 }
24 let graph = Graph::new(offsets.clone(), sources.clone())?;
25 let verified = OnceLock::new();
26 let output = OnceLock::new();
27 let jobs = Plan::new(vec![
28 Task {
29 dependencies: vec![],
30 device: Device::Cpu,
31 memory_bytes: 16 << 20,
32 },
33 Task {
34 dependencies: vec![],
35 device: if hybrid { Device::Gpu } else { Device::Cpu },
36 memory_bytes: 16 << 20,
37 },
38 Task {
39 dependencies: vec![0, 1],
40 device: Device::Cpu,
41 memory_bytes: 0,
42 },
43 ])?;
44 let timings = jobs.execute(
45 Limits {
46 cpu: 2,
47 gpu: 1,
48 memory_bytes: 32 << 20,
49 },
50 |task, device| {
51 match task {
52 0 => {
53 verified
54 .set(graph.cpu(&seeds, true)?)
55 .map_err(|_| "duplicate reference")?;
56 }
57 1 => {
58 let mut session = ResidentGraph::new(
59 Graph::new(offsets.clone(), sources.clone())?,
60 match device {
61 Device::Cpu => Backend::Cpu,
62 Device::Gpu => Backend::Cuda,
63 },
64 );
65 #[cfg(all(windows, target_arch = "x86_64"))]
66 eprintln!("device_init={:?}", session.device_info());
67 let result = session.solve(&seeds)?;
68 output.set(result).map_err(|_| "duplicate result")?;
69 }
70 2 => {
71 if verified.get().unwrap() != &output.get().unwrap().facts {
72 return Err("device and CPU results differ".into());
73 }
74 }
75 _ => unreachable!(),
76 }
77 Ok(())
78 },
79 )?;
80 let result = output.get().unwrap();
81 println!(
82 "nodes={} backend={:?} fallback={:?} solve_ns={} setup_through_parity_ns={} timings={timings:?}",
83 seeds.len(),
84 result.backend,
85 result.fallback,
86 result.wall_ns,
87 total.elapsed().as_nanos()
88 );
89 if hybrid && !matches!(result.backend, Backend::Cuda) {
90 return Err("CUDA did not execute".into());
91 }
92 Ok(())
93}Sourcepub fn critical_path(
&self,
completed: &[Timing],
) -> Result<Duration, &'static str>
pub fn critical_path( &self, completed: &[Timing], ) -> Result<Duration, &'static str>
Longest dependency chain weighted by actual task durations. The completion order returned by execute is a topological order.
Sourcepub fn execute<F>(&self, limits: Limits, work: F) -> Result<Vec<Timing>, String>
pub fn execute<F>(&self, limits: Limits, work: F) -> Result<Vec<Timing>, String>
Each worker owns its state. The callback may use a device session for multiple operations. Limits reserve declared working memory, which includes any device buffers charged by the caller.
Examples found in repository?
examples/hash_assets.rs (lines 46-75)
14fn main() -> Result<(), Box<dyn std::error::Error>> {
15 let start = Instant::now();
16 let mut args = std::env::args_os().skip(1);
17 let directory = PathBuf::from(args.next().ok_or("missing input directory")?);
18 let workers: usize = args
19 .next()
20 .ok_or("missing worker count")?
21 .to_string_lossy()
22 .parse()?;
23 if workers == 0 {
24 return Err("worker count must be positive".into());
25 }
26 let mut files = Vec::new();
27 for entry in fs::read_dir(directory)? {
28 let entry = entry?;
29 if entry.file_type()?.is_file() {
30 files.push(entry.path());
31 }
32 }
33 files.sort();
34 let outputs: Vec<OnceLock<[u8; 32]>> = (0..files.len()).map(|_| OnceLock::new()).collect();
35 let next = AtomicUsize::new(0);
36 let workers = workers.min(files.len());
37 let plan = Plan::new(
38 (0..workers)
39 .map(|_| Task {
40 dependencies: Vec::new(),
41 device: Device::Cpu,
42 memory_bytes: 128 * 1024,
43 })
44 .collect(),
45 )?;
46 plan.execute(
47 Limits {
48 cpu: workers,
49 gpu: 0,
50 memory_bytes: workers * 128 * 1024,
51 },
52 |_, _| {
53 let mut buffer = vec![0; 64 * 1024];
54 loop {
55 let index = next.fetch_add(1, Ordering::Relaxed);
56 let Some(path) = files.get(index) else { break };
57 let mut reader = BufReader::with_capacity(
58 buffer.len(),
59 fs::File::open(path).map_err(|e| e.to_string())?,
60 );
61 let mut hash = Sha256::new();
62 loop {
63 let size = reader.read(&mut buffer).map_err(|e| e.to_string())?;
64 if size == 0 {
65 break;
66 }
67 hash.update(&buffer[..size]);
68 }
69 outputs[index]
70 .set(hash.finalize().into())
71 .map_err(|_| "duplicate output")?;
72 }
73 Ok(())
74 },
75 )?;
76 let mut manifest = Sha256::new();
77 for (file, hash) in files.iter().zip(outputs) {
78 let name = file.file_name().unwrap().as_encoded_bytes();
79 manifest.update((name.len() as u64).to_le_bytes());
80 manifest.update(name);
81 manifest.update(hash.into_inner().unwrap());
82 }
83 println!(
84 "files={} manifest={:x} elapsed_ns={}",
85 files.len(),
86 manifest.finalize(),
87 start.elapsed().as_nanos()
88 );
89 Ok(())
90}More examples
examples/propagate.rs (lines 44-79)
8fn main() -> Result<(), Box<dyn std::error::Error>> {
9 let mut args = std::env::args().skip(1);
10 let input = std::fs::read_to_string(args.next().ok_or("missing graph")?)?;
11 let hybrid = args.next().as_deref() == Some("hybrid");
12 let total = Instant::now();
13 let mut offsets = vec![0];
14 let mut sources = Vec::new();
15 let mut seeds = Vec::new();
16 for line in input.lines() {
17 let mut fields = line.split_whitespace();
18 seeds.push(fields.next().ok_or("missing seed")?.parse::<u32>()?);
19 for field in fields {
20 sources.push(field.parse::<u32>()?);
21 }
22 offsets.push(u32::try_from(sources.len())?);
23 }
24 let graph = Graph::new(offsets.clone(), sources.clone())?;
25 let verified = OnceLock::new();
26 let output = OnceLock::new();
27 let jobs = Plan::new(vec![
28 Task {
29 dependencies: vec![],
30 device: Device::Cpu,
31 memory_bytes: 16 << 20,
32 },
33 Task {
34 dependencies: vec![],
35 device: if hybrid { Device::Gpu } else { Device::Cpu },
36 memory_bytes: 16 << 20,
37 },
38 Task {
39 dependencies: vec![0, 1],
40 device: Device::Cpu,
41 memory_bytes: 0,
42 },
43 ])?;
44 let timings = jobs.execute(
45 Limits {
46 cpu: 2,
47 gpu: 1,
48 memory_bytes: 32 << 20,
49 },
50 |task, device| {
51 match task {
52 0 => {
53 verified
54 .set(graph.cpu(&seeds, true)?)
55 .map_err(|_| "duplicate reference")?;
56 }
57 1 => {
58 let mut session = ResidentGraph::new(
59 Graph::new(offsets.clone(), sources.clone())?,
60 match device {
61 Device::Cpu => Backend::Cpu,
62 Device::Gpu => Backend::Cuda,
63 },
64 );
65 #[cfg(all(windows, target_arch = "x86_64"))]
66 eprintln!("device_init={:?}", session.device_info());
67 let result = session.solve(&seeds)?;
68 output.set(result).map_err(|_| "duplicate result")?;
69 }
70 2 => {
71 if verified.get().unwrap() != &output.get().unwrap().facts {
72 return Err("device and CPU results differ".into());
73 }
74 }
75 _ => unreachable!(),
76 }
77 Ok(())
78 },
79 )?;
80 let result = output.get().unwrap();
81 println!(
82 "nodes={} backend={:?} fallback={:?} solve_ns={} setup_through_parity_ns={} timings={timings:?}",
83 seeds.len(),
84 result.backend,
85 result.fallback,
86 result.wall_ns,
87 total.elapsed().as_nanos()
88 );
89 if hybrid && !matches!(result.backend, Backend::Cuda) {
90 return Err("CUDA did not execute".into());
91 }
92 Ok(())
93}Auto Trait Implementations§
impl Forget for Plan
impl Freeze for Plan
impl Move for Plan
impl RefUnwindSafe for Plan
impl Send for Plan
impl Sync for Plan
impl Unpin for Plan
impl UnsafeUnpin for Plan
impl UnwindSafe for Plan
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more