fuel-dispatch 0.81.0

Dispatch infrastructure for fuel: KernelBindingTable, per-backend registration wrappers, CompiledNode + compile_node, ExecutionPlan + compile_plan + resolve_kernel, FusedKernelRegistry, PipelinedExecutor. The layer that takes a graph and runs it against registered backends. Extracted from fuel-memory 2026-05-31.
Documentation
// SPDX-License-Identifier: MIT OR Apache-2.0
//! Offers the conv + epilogue node (ROADMAP row 172 item 3) as an `Op::Branch` arm: arm 0
//! is the graph's own conv followed by its elementwise ops, arm 1 is one
//! `FusedOps::CONV2D_EPILOGUE` node carrying the extracted recipe. A region no kernel can
//! run stays as it is.

use std::collections::{HashMap, HashSet};

use fuel_graph::registry::conv2d_epilogue::{Extracted, build_node, extract_epilogue};
use fuel_graph::registry::{FusedOpParams, FusedOps};
use fuel_graph::{Graph, NodeId, Op};
use fuel_ir::Result;
use fuel_ir::probe::BackendId;

use crate::driver::{OptimizationContext, Pathfinder};

/// The registered [`Pathfinder`]; see the module docs. v1 offers the arm only for a conv
/// the plan placed on the CPU, and only when the region has at most one operand beyond
/// `x` and `weight` (the registered dtype tuples: the conv's bias OR one extra).
pub struct ConvEpiloguePathfinder;

impl Pathfinder for ConvEpiloguePathfinder {
    fn name(&self) -> &'static str {
        "ConvEpilogueArm"
    }

    fn propose(&self, graph: &mut Graph, ctx: &OptimizationContext<'_>) -> Result<()> {
        let on_cpu = |conv: NodeId| {
            ctx.plan
                .alternatives(conv)
                .and_then(|alts| alts.alternatives().first().map(|c| c.backend))
                == Some(BackendId::Cpu)
        };
        let mut consumers: HashMap<NodeId, Vec<NodeId>> = HashMap::new();
        for i in 0..graph.len() {
            for &input in &graph.node(NodeId(i)).inputs {
                consumers.entry(input).or_default().push(NodeId(i));
            }
        }
        // Latest first, so the outermost region over a conv wins over its inner ones.
        let mut claimed: HashSet<NodeId> = HashSet::new();
        let mut found: Vec<(NodeId, NodeId, Extracted, HashSet<NodeId>)> = Vec::new();
        for &root in ctx.order.iter().rev() {
            // Exactly one consumer: it is where the two arms reconverge.
            let Some(&[reconverge]) = consumers.get(&root).map(Vec::as_slice) else {
                continue;
            };
            let Some(region) = extract_epilogue(graph, root) else {
                continue;
            };
            if claimed.contains(&region.conv) || !on_cpu(region.conv) || !fits(graph, &region) {
                continue;
            }
            let Some(interior) = closed_arm(graph, &consumers, root, reconverge, &region) else {
                continue;
            };
            claimed.insert(region.conv);
            found.push((root, reconverge, region, interior));
        }
        // A fused node reads its region's conv inputs and extras. If one of those is a node
        // inside ANOTHER offered region's unfused arm, the graph would refuse that branch
        // (an arm interior read from outside), so the region owning that node is not offered.
        let reads: Vec<HashSet<NodeId>> = found
            .iter()
            .map(|(_, _, region, _)| {
                graph
                    .node(region.conv)
                    .inputs
                    .iter()
                    .chain(&region.extras)
                    .copied()
                    .collect()
            })
            .collect();
        let keep: Vec<bool> = (0..found.len())
            .map(|i| {
                !(0..found.len()).any(|j| j != i && reads[j].iter().any(|n| found[i].3.contains(n)))
            })
            .collect();
        let mut keep = keep.into_iter();
        found.retain(|_| keep.next().unwrap_or(false));

        for (root, reconverge, region, _) in found {
            let Some(fused) = build_node(graph, root, &region) else {
                continue;
            };
            graph.set_target_backend(fused, BackendId::Cpu);
            let diverge = graph.node(fused).inputs[0];
            let mut branch = graph.open_branch(diverge);
            branch.add_arm(root); // arm 0 — the unfused ops
            branch.add_arm(fused); // arm 1 — one node
            branch.finalize_branches(graph, reconverge)?;
        }
        Ok(())
    }
}

/// The unfused arm's interior (arm 0), when it is closed: every node on a path from the diverge
/// point (the conv's first input) to `root` is read only by nodes of that arm or by the
/// reconverge node. A region operand computed from the same input and also read
/// elsewhere breaks this, and the graph refuses such a branch, so no arm is offered.
fn closed_arm(
    graph: &Graph,
    consumers: &HashMap<NodeId, Vec<NodeId>>,
    root: NodeId,
    reconverge: NodeId,
    region: &Extracted,
) -> Option<HashSet<NodeId>> {
    let diverge = *graph.node(region.conv).inputs.first()?;
    let mut back: HashSet<NodeId> = HashSet::new();
    let mut stack = vec![root];
    while let Some(n) = stack.pop() {
        if back.insert(n) {
            stack.extend(graph.node(n).inputs.iter().copied());
        }
    }
    let mut fwd: HashSet<NodeId> = HashSet::new();
    let mut stack = vec![diverge];
    while let Some(n) = stack.pop() {
        if fwd.insert(n) {
            stack.extend(consumers.get(&n).into_iter().flatten().copied());
        }
    }
    let interior: HashSet<NodeId> = back
        .intersection(&fwd)
        .copied()
        .filter(|&n| n != diverge)
        .collect();
    let closed = interior.iter().all(|n| {
        consumers
            .get(n)
            .into_iter()
            .flatten()
            .all(|c| *c == reconverge || interior.contains(c))
    });
    closed.then_some(interior)
}

/// Whether the CPU kernel can run this region: a registered dtype tuple, every extra
/// output-shaped, and a recipe its compiler accepts.
fn fits(graph: &Graph, region: &Extracted) -> bool {
    let conv = graph.node(region.conv);
    if !matches!(conv.op, Op::Fused(_, FusedOpParams::Conv2D { .. })) {
        return false;
    }
    let operands = conv.inputs.len() + region.extras.len();
    if operands > 3 {
        return false;
    }
    if region.extras.iter().any(|&e| {
        let n = graph.node(e);
        n.shape != conv.shape || n.dtype != conv.dtype
    }) {
        return false;
    }
    let dtypes: Vec<_> = conv
        .inputs
        .iter()
        .chain(&region.extras)
        .map(|&i| graph.node(i).dtype)
        .chain([conv.dtype])
        .collect();
    crate::fused::default_kernel_registry()
        .lookup_by_dtypes(FusedOps::CONV2D_EPILOGUE, BackendId::Cpu, &dtypes)
        .is_some()
        && crate::conv_epilogue::compile_epilogue(
            &region.recipe,
            &region.scalars,
            region.extras.len(),
        )
        .is_ok()
}