dfir_lang/graph/
flat_to_partitioned.rs

1//! Subgraph partioning algorithm
2
3use std::collections::{BTreeMap, BTreeSet};
4
5use proc_macro2::Span;
6use slotmap::{SecondaryMap, SparseSecondaryMap};
7use syn::parse_quote;
8
9use super::meta_graph::DfirGraph;
10use super::ops::{DelayType, FloType, find_node_op_constraints};
11use super::{Color, GraphEdgeId, GraphNode, GraphNodeId, GraphSubgraphId, graph_algorithms};
12use crate::diagnostic::{Diagnostic, Level};
13use crate::union_find::UnionFind;
14
15/// Helper struct for tracking barrier crossers, see [`find_barrier_crossers`].
16struct BarrierCrossers {
17    /// Edge barrier crossers, including what type.
18    pub edge_barrier_crossers: SecondaryMap<GraphEdgeId, DelayType>,
19    /// Singleton reference barrier crossers, considered to be [`DelayType::Stratum`].
20    pub singleton_barrier_crossers: Vec<(GraphNodeId, GraphNodeId)>,
21}
22impl BarrierCrossers {
23    /// Iterate pairs of nodes that are across a barrier. Excludes `DelayType::NextIteration` pairs.
24    fn iter_node_pairs<'a>(
25        &'a self,
26        partitioned_graph: &'a DfirGraph,
27    ) -> impl 'a + Iterator<Item = ((GraphNodeId, GraphNodeId), DelayType)> {
28        let edge_pairs_iter = self
29            .edge_barrier_crossers
30            .iter()
31            .map(|(edge_id, &delay_type)| {
32                let src_dst = partitioned_graph.edge(edge_id);
33                (src_dst, delay_type)
34            });
35        let singleton_pairs_iter = self
36            .singleton_barrier_crossers
37            .iter()
38            .map(|&src_dst| (src_dst, DelayType::Stratum));
39        edge_pairs_iter.chain(singleton_pairs_iter)
40    }
41
42    /// Insert/replace edge.
43    fn replace_edge(&mut self, old_edge_id: GraphEdgeId, new_edge_id: GraphEdgeId) {
44        if let Some(delay_type) = self.edge_barrier_crossers.remove(old_edge_id) {
45            self.edge_barrier_crossers.insert(new_edge_id, delay_type);
46        }
47    }
48}
49
50/// Find all the barrier crossers.
51fn find_barrier_crossers(partitioned_graph: &DfirGraph) -> BarrierCrossers {
52    let edge_barrier_crossers = partitioned_graph
53        .edges()
54        .filter(|&(_, (_src, dst))| {
55            // Ignore barriers within `loop {` blocks.
56            partitioned_graph.node_loop(dst).is_none()
57        })
58        .filter_map(|(edge_id, (_src, dst))| {
59            let (_src_port, dst_port) = partitioned_graph.edge_ports(edge_id);
60            let op_constraints = partitioned_graph.node_op_inst(dst)?.op_constraints;
61            let input_barrier = (op_constraints.input_delaytype_fn)(dst_port)?;
62            Some((edge_id, input_barrier))
63        })
64        .collect();
65    let singleton_barrier_crossers = partitioned_graph
66        .node_ids()
67        .flat_map(|dst| {
68            partitioned_graph
69                .node_singleton_references(dst)
70                .iter()
71                .flatten()
72                .map(move |&src_ref| (src_ref, dst))
73        })
74        .collect();
75    BarrierCrossers {
76        edge_barrier_crossers,
77        singleton_barrier_crossers,
78    }
79}
80
81fn find_subgraph_unionfind(
82    partitioned_graph: &DfirGraph,
83    barrier_crossers: &BarrierCrossers,
84) -> (UnionFind<GraphNodeId>, BTreeSet<GraphEdgeId>) {
85    // Modality (color) of nodes, push or pull.
86    // TODO(mingwei)? This does NOT consider `DelayType` barriers (which generally imply `Pull`),
87    // which makes it inconsistant with the final output in `as_code()`. But this doesn't create
88    // any bugs since we exclude `DelayType` edges from joining subgraphs anyway.
89    let mut node_color = partitioned_graph
90        .node_ids()
91        .filter_map(|node_id| {
92            let op_color = partitioned_graph.node_color(node_id)?;
93            Some((node_id, op_color))
94        })
95        .collect::<SparseSecondaryMap<_, _>>();
96
97    let mut subgraph_unionfind: UnionFind<GraphNodeId> =
98        UnionFind::with_capacity(partitioned_graph.nodes().len());
99
100    // Will contain all edges which are handoffs. Starts out with all edges and
101    // we remove from this set as we combine nodes into subgraphs.
102    let mut handoff_edges: BTreeSet<GraphEdgeId> = partitioned_graph.edge_ids().collect();
103    // Would sort edges here for priority (for now, no sort/priority).
104
105    // Each edge gets looked at in order. However we may not know if a linear
106    // chain of operators is PUSH vs PULL until we look at the ends. A fancier
107    // algorithm would know to handle linear chains from the outside inward.
108    // But instead we just run through the edges in a loop until no more
109    // progress is made. Could have some sort of O(N^2) pathological worst
110    // case.
111    let mut progress = true;
112    while progress {
113        progress = false;
114        // TODO(mingwei): Could this iterate `handoff_edges` instead? (Modulo ownership). Then no case (1) below.
115        for (edge_id, (src, dst)) in partitioned_graph.edges().collect::<Vec<_>>() {
116            // Ignore (1) already added edges as well as (2) new self-cycles. (Unless reference edge).
117            if subgraph_unionfind.same_set(src, dst) {
118                // Note that the _edge_ `edge_id` might not be in the subgraph even when both `src` and `dst` are. This prevents case 2.
119                // Handoffs will be inserted later for this self-loop.
120                continue;
121            }
122
123            // Do not connect stratum crossers (next edges).
124            if barrier_crossers
125                .iter_node_pairs(partitioned_graph)
126                .any(|((x_src, x_dst), _)| {
127                    (subgraph_unionfind.same_set(x_src, src)
128                        && subgraph_unionfind.same_set(x_dst, dst))
129                        || (subgraph_unionfind.same_set(x_src, dst)
130                            && subgraph_unionfind.same_set(x_dst, src))
131                })
132            {
133                continue;
134            }
135
136            // Do not connect across loop contexts.
137            if partitioned_graph.node_loop(src) != partitioned_graph.node_loop(dst) {
138                continue;
139            }
140            // Do not connect `next_iteration()`.
141            if partitioned_graph.node_op_inst(dst).is_some_and(|op_inst| {
142                Some(FloType::NextIteration) == op_inst.op_constraints.flo_type
143            }) {
144                continue;
145            }
146
147            if can_connect_colorize(&mut node_color, src, dst) {
148                // At this point we have selected this edge and its src & dst to be
149                // within a single subgraph.
150                subgraph_unionfind.union(src, dst);
151                assert!(handoff_edges.remove(&edge_id));
152                progress = true;
153            }
154        }
155    }
156
157    (subgraph_unionfind, handoff_edges)
158}
159
160/// Builds the datastructures for checking which subgraph each node belongs to
161/// after handoffs have already been inserted to partition subgraphs.
162/// This list of nodes in each subgraph are returned in topological sort order.
163fn make_subgraph_collect(
164    partitioned_graph: &DfirGraph,
165    mut subgraph_unionfind: UnionFind<GraphNodeId>,
166) -> SecondaryMap<GraphNodeId, Vec<GraphNodeId>> {
167    // We want the nodes of each subgraph to be listed in topo-sort order.
168    // We could do this on each subgraph, or we could do it all at once on the
169    // whole node graph by ignoring handoffs, which is what we do here:
170    let topo_sort = graph_algorithms::topo_sort(
171        partitioned_graph
172            .nodes()
173            .filter(|&(_, node)| !matches!(node, GraphNode::Handoff { .. }))
174            .map(|(node_id, _)| node_id),
175        |v| {
176            partitioned_graph
177                .node_predecessor_nodes(v)
178                .filter(|&pred_id| {
179                    let pred = partitioned_graph.node(pred_id);
180                    !matches!(pred, GraphNode::Handoff { .. })
181                })
182        },
183    )
184    .expect("Subgraphs are in-out trees.");
185
186    let mut grouped_nodes: SecondaryMap<GraphNodeId, Vec<GraphNodeId>> = Default::default();
187    for node_id in topo_sort {
188        let repr_node = subgraph_unionfind.find(node_id);
189        if !grouped_nodes.contains_key(repr_node) {
190            grouped_nodes.insert(repr_node, Default::default());
191        }
192        grouped_nodes[repr_node].push(node_id);
193    }
194    grouped_nodes
195}
196
197/// Find subgraph and insert handoffs.
198/// Modifies barrier_crossers so that the edge OUT of an inserted handoff has
199/// the DelayType data.
200fn make_subgraphs(partitioned_graph: &mut DfirGraph, barrier_crossers: &mut BarrierCrossers) {
201    // Algorithm:
202    // 1. Each node begins as its own subgraph.
203    // 2. Collect edges. (Future optimization: sort so edges which should not be split across a handoff come first).
204    // 3. For each edge, try to join `(to, from)` into the same subgraph.
205
206    // TODO(mingwei):
207    // self.partitioned_graph.assert_valid();
208
209    let (subgraph_unionfind, handoff_edges) =
210        find_subgraph_unionfind(partitioned_graph, barrier_crossers);
211
212    // Insert handoffs between subgraphs (or on subgraph self-loop edges)
213    for edge_id in handoff_edges {
214        let (src_id, dst_id) = partitioned_graph.edge(edge_id);
215
216        // Already has a handoff, no need to insert one.
217        let src_node = partitioned_graph.node(src_id);
218        let dst_node = partitioned_graph.node(dst_id);
219        if matches!(src_node, GraphNode::Handoff { .. })
220            || matches!(dst_node, GraphNode::Handoff { .. })
221        {
222            continue;
223        }
224
225        let hoff = GraphNode::Handoff {
226            src_span: src_node.span(),
227            dst_span: dst_node.span(),
228        };
229        let (_node_id, out_edge_id) = partitioned_graph.insert_intermediate_node(edge_id, hoff);
230
231        // Update barrier_crossers for inserted node.
232        barrier_crossers.replace_edge(edge_id, out_edge_id);
233    }
234
235    // Determine node's subgraph and subgraph's nodes.
236    // This list of nodes in each subgraph are to be in topological sort order.
237    // Eventually returned directly in the [`DfirGraph`].
238    let grouped_nodes = make_subgraph_collect(partitioned_graph, subgraph_unionfind);
239    for (_repr_node, member_nodes) in grouped_nodes {
240        partitioned_graph.insert_subgraph(member_nodes).unwrap();
241    }
242}
243
244/// Set `src` or `dst` color if `None` based on the other (if possible):
245/// `None` indicates an op could be pull or push i.e. unary-in & unary-out.
246/// So in that case we color `src` or `dst` based on its newfound neighbor (the other one).
247///
248/// Returns if `src` and `dst` can be in the same subgraph.
249fn can_connect_colorize(
250    node_color: &mut SparseSecondaryMap<GraphNodeId, Color>,
251    src: GraphNodeId,
252    dst: GraphNodeId,
253) -> bool {
254    // Pull -> Pull
255    // Push -> Push
256    // Pull -> [Computation] -> Push
257    // Push -> [Handoff] -> Pull
258    let can_connect = match (node_color.get(src), node_color.get(dst)) {
259        // Linear chain, can't connect because it may cause future conflicts.
260        // But if it doesn't in the _future_ we can connect it (once either/both ends are determined).
261        (None, None) => false,
262
263        // Infer left side.
264        (None, Some(Color::Pull | Color::Comp)) => {
265            node_color.insert(src, Color::Pull);
266            true
267        }
268        (None, Some(Color::Push | Color::Hoff)) => {
269            node_color.insert(src, Color::Push);
270            true
271        }
272
273        // Infer right side.
274        (Some(Color::Pull | Color::Hoff), None) => {
275            node_color.insert(dst, Color::Pull);
276            true
277        }
278        (Some(Color::Comp | Color::Push), None) => {
279            node_color.insert(dst, Color::Push);
280            true
281        }
282
283        // Both sides already specified.
284        (Some(Color::Pull), Some(Color::Pull)) => true,
285        (Some(Color::Pull), Some(Color::Comp)) => true,
286        (Some(Color::Pull), Some(Color::Push)) => true,
287
288        (Some(Color::Comp), Some(Color::Pull)) => false,
289        (Some(Color::Comp), Some(Color::Comp)) => false,
290        (Some(Color::Comp), Some(Color::Push)) => true,
291
292        (Some(Color::Push), Some(Color::Pull)) => false,
293        (Some(Color::Push), Some(Color::Comp)) => false,
294        (Some(Color::Push), Some(Color::Push)) => true,
295
296        // Handoffs are not part of subgraphs.
297        (Some(Color::Hoff), Some(_)) => false,
298        (Some(_), Some(Color::Hoff)) => false,
299    };
300    can_connect
301}
302
303/// Stratification is surprisingly tricky. Basically it is topological sort, but with some nuance.
304///
305/// Returns an error if there is a cycle thru negation.
306fn find_subgraph_strata(
307    partitioned_graph: &mut DfirGraph,
308    barrier_crossers: &BarrierCrossers,
309) -> Result<(), Diagnostic> {
310    // Determine subgraphs's stratum number.
311    // Find SCCs ignoring `defer_tick()` (`DelayType::Tick`) edges, then do TopoSort on the
312    // resulting DAG.
313    // Cycles thru cross-stratum negative edges (both `DelayType::Tick` and `DelayType::Stratum`)
314    // are an error.
315
316    // Generate a subgraph graph. I.e. each node is a subgraph.
317    // Edges are connections between subgraphs, ignoring tick-crossers.
318    // TODO: use DiMulGraph here?
319    #[derive(Default)]
320    struct SubgraphGraph {
321        preds: BTreeMap<GraphSubgraphId, Vec<GraphSubgraphId>>,
322        succs: BTreeMap<GraphSubgraphId, Vec<GraphSubgraphId>>,
323    }
324    impl SubgraphGraph {
325        fn insert_edge(&mut self, src: GraphSubgraphId, dst: GraphSubgraphId) {
326            self.preds.entry(dst).or_default().push(src);
327            self.succs.entry(src).or_default().push(dst);
328        }
329    }
330    let mut subgraph_graph = SubgraphGraph::default();
331
332    // Negative (next stratum) connections between subgraphs. (Ignore `defer_tick()` connections).
333    let mut subgraph_stratum_barriers: BTreeSet<(GraphSubgraphId, GraphSubgraphId)> =
334        Default::default();
335
336    // Iterate handoffs between subgraphs, to build a subgraph meta-graph.
337    for (node_id, node) in partitioned_graph.nodes() {
338        if matches!(node, GraphNode::Handoff { .. }) {
339            assert_eq!(1, partitioned_graph.node_successors(node_id).count());
340            let (succ_edge, succ) = partitioned_graph.node_successors(node_id).next().unwrap();
341
342            // TODO(mingwei): Should we look at the singleton references too?
343            let succ_edge_delaytype = barrier_crossers
344                .edge_barrier_crossers
345                .get(succ_edge)
346                .copied();
347            // Ignore tick edges.
348            if let Some(DelayType::Tick | DelayType::TickLazy) = succ_edge_delaytype {
349                continue;
350            }
351
352            assert_eq!(1, partitioned_graph.node_predecessors(node_id).count());
353            let (_edge_id, pred) = partitioned_graph.node_predecessors(node_id).next().unwrap();
354
355            let pred_sg = partitioned_graph.node_subgraph(pred).unwrap();
356            let succ_sg = partitioned_graph.node_subgraph(succ).unwrap();
357
358            subgraph_graph.insert_edge(pred_sg, succ_sg);
359
360            if Some(DelayType::Stratum) == succ_edge_delaytype {
361                subgraph_stratum_barriers.insert((pred_sg, succ_sg));
362            }
363        }
364    }
365    // Include reference edges as well.
366    // TODO(mingwei): deduplicate graph building code.
367    for &(pred, succ) in barrier_crossers.singleton_barrier_crossers.iter() {
368        assert_ne!(pred, succ, "TODO(mingwei)");
369        let pred_sg = partitioned_graph.node_subgraph(pred).unwrap();
370        let succ_sg = partitioned_graph.node_subgraph(succ).unwrap();
371        assert_ne!(pred_sg, succ_sg);
372        subgraph_graph.insert_edge(pred_sg, succ_sg);
373        subgraph_stratum_barriers.insert((pred_sg, succ_sg));
374    }
375
376    // Topological sort (of strongly connected components) is how we find the (nondecreasing)
377    // order of strata.
378    let topo_sort_order = graph_algorithms::topo_sort_scc(
379        || partitioned_graph.subgraph_ids(),
380        |v| subgraph_graph.preds.get(&v).into_iter().flatten().cloned(),
381        |u| subgraph_graph.succs.get(&u).into_iter().flatten().cloned(),
382    );
383
384    // Each subgraph's stratum number is the same as it's predecessors.
385    //
386    // Unless:
387    // - At the top level: there is a negative edge (e.g. `fold()`), then we increment.
388    // - Entering or exiting a loop.
389    for sg_id in topo_sort_order {
390        let curr_loop = partitioned_graph.subgraph_loop(sg_id);
391
392        let stratum = subgraph_graph
393            .preds
394            .get(&sg_id)
395            .into_iter()
396            .flatten()
397            .filter_map(|&pred_sg_id| {
398                partitioned_graph
399                    .subgraph_stratum(pred_sg_id)
400                    .map(|stratum| {
401                        let pred_loop = partitioned_graph.subgraph_loop(pred_sg_id);
402                        if curr_loop != pred_loop {
403                            // Entering or exiting a loop.
404                            stratum + 1
405                        } else if curr_loop.is_none()
406                            && subgraph_stratum_barriers.contains(&(pred_sg_id, sg_id))
407                        {
408                            // Top level && negative edge.
409                            stratum + 1
410                        } else {
411                            stratum
412                        }
413                    })
414            })
415            .max()
416            .unwrap_or(0);
417        partitioned_graph.set_subgraph_stratum(sg_id, stratum);
418    }
419
420    // Re-introduce the `defer_tick()` edges, ensuring they actually go to the next tick.
421    let extra_stratum = partitioned_graph.max_stratum().unwrap_or(0) + 1; // Used for `defer_tick()` delayer subgraphs.
422    for (edge_id, &delay_type) in barrier_crossers.edge_barrier_crossers.iter() {
423        let (hoff, dst) = partitioned_graph.edge(edge_id);
424        // Ignore barriers within `loop {` blocks.
425        if partitioned_graph.node_loop(dst).is_some() {
426            continue;
427        }
428        let (_hoff_port, dst_port) = partitioned_graph.edge_ports(edge_id);
429
430        assert_eq!(1, partitioned_graph.node_predecessors(hoff).count());
431        let src = partitioned_graph
432            .node_predecessor_nodes(hoff)
433            .next()
434            .unwrap();
435
436        let src_sg = partitioned_graph.node_subgraph(src).unwrap();
437        let dst_sg = partitioned_graph.node_subgraph(dst).unwrap();
438        let src_stratum = partitioned_graph.subgraph_stratum(src_sg);
439        let dst_stratum = partitioned_graph.subgraph_stratum(dst_sg);
440        match delay_type {
441            DelayType::Tick | DelayType::TickLazy => {
442                let is_lazy = matches!(delay_type, DelayType::TickLazy);
443                // If tick edge goes foreward in stratum, need to buffer.
444                // (TODO(mingwei): could use a different kind of handoff.)
445                // Or if lazy, need to create extra subgraph to mark as lazy.
446                if src_stratum <= dst_stratum || is_lazy {
447                    // We inject a new subgraph between the src/dst which runs as the last stratum
448                    // of the tick and therefore delays the data until the next tick.
449
450                    // Before: A (src) -> H -> B (dst)
451                    // Then add intermediate identity:
452                    let (new_node_id, new_edge_id) = partitioned_graph.insert_intermediate_node(
453                        edge_id,
454                        // TODO(mingwei): Proper span w/ `parse_quote_spanned!`?
455                        GraphNode::Operator(parse_quote! { identity() }),
456                    );
457                    // Intermediate: A (src) -> H -> ID -> B (dst)
458                    let hoff = GraphNode::Handoff {
459                        src_span: Span::call_site(), // TODO(mingwei): Proper spanning?
460                        dst_span: Span::call_site(),
461                    };
462                    let (_hoff_node_id, _hoff_edge_id) =
463                        partitioned_graph.insert_intermediate_node(new_edge_id, hoff);
464                    // After: A (src) -> H -> ID -> H' -> B (dst)
465
466                    // Set stratum number for new intermediate:
467                    // Create subgraph.
468                    let new_subgraph_id = partitioned_graph
469                        .insert_subgraph(vec![new_node_id])
470                        .unwrap();
471
472                    // Assign stratum.
473                    partitioned_graph.set_subgraph_stratum(new_subgraph_id, extra_stratum);
474
475                    // Assign laziness.
476                    partitioned_graph.set_subgraph_laziness(new_subgraph_id, is_lazy);
477                }
478            }
479            DelayType::Stratum => {
480                // Any negative edges which go onto the same or previous stratum are bad.
481                // Indicates an unbroken negative cycle.
482                // TODO(mingwei): This check is insufficient: https://github.com/hydro-project/hydro/issues/1115#issuecomment-2018385033
483                if dst_stratum <= src_stratum {
484                    return Err(Diagnostic::spanned(
485                        dst_port.span(),
486                        Level::Error,
487                        "Negative edge creates a negative cycle which must be broken with a `defer_tick()` operator.",
488                    ));
489                }
490            }
491            DelayType::MonotoneAccum => {
492                // cycles are actually fine
493                continue;
494            }
495        }
496    }
497    Ok(())
498}
499
500/// Put `is_external_input: true` operators in separate stratum 0 subgraphs if they are not in stratum 0.
501/// By ripping them out of their subgraph/stratum if they're not already in statum 0.
502fn separate_external_inputs(partitioned_graph: &mut DfirGraph) {
503    let external_input_nodes: Vec<_> = partitioned_graph
504        .nodes()
505        // Ensure node is an operator (not a handoff), get constraints spec.
506        .filter_map(|(node_id, node)| {
507            find_node_op_constraints(node).map(|op_constraints| (node_id, op_constraints))
508        })
509        // Ensure current `node_id` is an external input.
510        .filter(|(_node_id, op_constraints)| op_constraints.is_external_input)
511        // Collect just `node_id`s.
512        .map(|(node_id, _op_constraints)| node_id)
513        // Ignore if operator node is already stratum 0.
514        .filter(|&node_id| {
515            0 != partitioned_graph
516                .subgraph_stratum(partitioned_graph.node_subgraph(node_id).unwrap())
517                .unwrap()
518        })
519        .collect();
520
521    for node_id in external_input_nodes {
522        // Remove node from old subgraph.
523        assert!(
524            partitioned_graph.remove_from_subgraph(node_id),
525            "Cannot move input node that is not in a subgraph, this is a bug."
526        );
527        // Create new subgraph in stratum 0 for this source.
528        let new_sg_id = partitioned_graph.insert_subgraph(vec![node_id]).unwrap();
529        partitioned_graph.set_subgraph_stratum(new_sg_id, 0);
530
531        // Insert handoff.
532        for edge_id in partitioned_graph
533            .node_successor_edges(node_id)
534            .collect::<Vec<_>>()
535        {
536            let span = partitioned_graph.node(node_id).span();
537            let hoff = GraphNode::Handoff {
538                src_span: span,
539                dst_span: span,
540            };
541            partitioned_graph.insert_intermediate_node(edge_id, hoff);
542        }
543    }
544}
545
546/// Main method for this module. Partions a flat [`DfirGraph`] into one with subgraphs.
547///
548/// Returns an error if a negative cycle exists in the graph. Negative cycles prevent partioning.
549pub fn partition_graph(flat_graph: DfirGraph) -> Result<DfirGraph, Diagnostic> {
550    // Pre-find barrier crossers (input edges with a `DelayType`).
551    let mut barrier_crossers = find_barrier_crossers(&flat_graph);
552    let mut partitioned_graph = flat_graph;
553
554    // Partition into subgraphs.
555    make_subgraphs(&mut partitioned_graph, &mut barrier_crossers);
556
557    // Find strata for subgraphs (early returns with error if negative cycle found).
558    find_subgraph_strata(&mut partitioned_graph, &barrier_crossers)?;
559
560    // Ensure all external inputs are in stratum 0.
561    separate_external_inputs(&mut partitioned_graph);
562
563    Ok(partitioned_graph)
564}