1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
use crate::graph::OpKind;
use crate::memory::SizeClassPool;
use crate::tensor::Tensor;
use crate::OnnxError;
use oxionnx_core::{OpContext, Operator};
use std::collections::HashMap;
use std::sync::Mutex;
use super::super::types::NodeProfile;
use super::super::Session;
use super::state::SessionRunState;
#[cfg(not(target_arch = "wasm32"))]
use rayon::prelude::*;
impl Session {
/// Parallel execution: group nodes by topological depth and execute each
/// depth level concurrently using rayon.
///
/// TODO(v0.1.7): lift GPU/CUDA/DirectML dispatch into this parallel path.
/// Currently those dispatchers only run in run_sequential_inner (non-parallel path).
///
/// Note: inplace and slot-write optimisations are active for single-node levels.
/// For multi-node levels they are intentionally disabled — those paths require
/// exclusive mutable access to state during the operator call, which serialises
/// all workers and defeats the purpose of rayon parallelism.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn run_parallel_inner(
&self,
state: &mut SessionRunState,
ref_counts: &mut HashMap<String, usize>,
output_set: &std::collections::HashSet<&str>,
) -> Result<(), OnnxError> {
let depths = Self::compute_node_depths(&self.sorted_nodes, &self.weights);
let mut groups = Self::group_by_depth(&depths);
// Sort nodes within each level by critical-path cost (descending).
// This ensures the heaviest work starts first, reducing tail latency.
let critical_costs = crate::optimizer::cost_model::compute_critical_path_costs(
&self.sorted_nodes,
self.shape_cache.as_ref(),
);
for group in &mut groups {
group.sort_by(|&a, &b| critical_costs[b].cmp(&critical_costs[a]));
}
for group in &groups {
if group.is_empty() {
continue;
}
if group.len() == 1 {
// Single node — execute sequentially via dispatch_node (inplace + slot-write).
let node = &self.sorted_nodes[group[0]];
if let OpKind::Unknown(_) = &node.op {
continue;
}
let op_name = node.op.as_str();
let operator = self.registry.get(op_name).ok_or_else(|| {
OnnxError::UnknownOp(format!("No operator registered for '{}'", op_name))
})?;
let resolved = self
.resolved_shapes
.lock()
.map(|s| s.clone())
.unwrap_or_default();
let elapsed =
self.dispatch_node(node, operator, state, ref_counts, output_set, &resolved)?;
if let Some(ref profiling) = self.profiling_data {
if let Ok(mut data) = profiling.lock() {
// Collect output shapes from state after dispatch_node wrote them.
let output_shapes = node
.outputs
.iter()
.filter(|n| !n.is_empty())
.filter_map(|n| state.get(n))
.map(|t| t.shape.clone())
.collect();
data.push(NodeProfile {
node_name: node.name.clone(),
op_type: node.op.as_str().to_string(),
duration: elapsed,
output_shapes,
});
}
}
self.decrement_refs_state(node, state, ref_counts, output_set);
} else {
// Multiple nodes at this depth — execute in parallel via rayon.
//
// Read phase: snapshot inputs from state (immutable borrow ends before write phase).
// Compute phase: par_iter — zero state access, full rayon parallelism.
// Write phase: sequential insert via state.insert (pool-backed buffer release).
let nodes_at_depth: Vec<&crate::graph::Node> =
group.iter().map(|&i| &self.sorted_nodes[i]).collect();
// Collect operators and pre-resolve inputs (read-only snapshot).
let work_items: Vec<(&crate::graph::Node, &dyn Operator, Vec<Option<&Tensor>>)> =
nodes_at_depth
.iter()
.filter(|n| !matches!(n.op, OpKind::Unknown(_)))
.map(|n| {
let op = self.registry.get(n.op.as_str()).ok_or_else(|| {
OnnxError::UnknownOp(format!(
"No operator registered for '{}'",
n.op.as_str()
))
});
let inputs: Vec<Option<&Tensor>> = n
.inputs
.iter()
.map(|name| {
if name.is_empty() {
None
} else {
state.get(name).or_else(|| self.weights.get(name))
}
})
.collect();
op.map(|o| (*n, o, inputs))
})
.collect::<Result<Vec<_>, _>>()?;
// Execute in parallel — each produces (node_name, results, duration).
type ParResult<'a> = Result<(&'a str, Vec<Tensor>, std::time::Duration), OnnxError>;
let par_execute = || -> Vec<ParResult<'_>> {
work_items
.par_iter()
.map(|(node, operator, inputs)| {
let ctx = OpContext {
node,
inputs: inputs.clone(),
outer_scope: None,
registry: None,
};
let start = std::time::Instant::now();
let res = operator.execute(&ctx)?;
let elapsed = start.elapsed();
Ok((node.name.as_str(), res, elapsed))
})
.collect()
};
let par_results: Vec<ParResult<'_>> = if let Some(ref pool) = self.thread_pool {
pool.install(par_execute)
} else {
par_execute()
};
// Write phase: insert all outputs sequentially via state (pool-backed release).
let pool = self.pool.as_ref().map(|m| m as &Mutex<SizeClassPool>);
for result in par_results {
let (node_name, tensors, elapsed) = result?;
if let Some(node) = nodes_at_depth.iter().find(|n| n.name == node_name) {
if let Some(ref profiling) = self.profiling_data {
if let Ok(mut data) = profiling.lock() {
data.push(NodeProfile {
node_name: node.name.clone(),
op_type: node.op.as_str().to_string(),
duration: elapsed,
output_shapes: tensors
.iter()
.map(|t| t.shape.clone())
.collect(),
});
}
}
for (name, tensor) in node.outputs.iter().zip(tensors) {
if !name.is_empty() {
state.insert(name.clone(), tensor, pool);
}
}
}
}
// Decrement ref counts for all nodes in this group via state.
for node in &nodes_at_depth {
self.decrement_refs_state(node, state, ref_counts, output_set);
}
}
}
Ok(())
}
/// Fallback on wasm32: parallel is not supported, delegate to sequential.
#[cfg(target_arch = "wasm32")]
pub(crate) fn run_parallel_inner(
&self,
state: &mut SessionRunState,
ref_counts: &mut HashMap<String, usize>,
output_set: &std::collections::HashSet<&str>,
) -> Result<(), OnnxError> {
self.run_sequential_inner(state, ref_counts, output_set)
}
}