Skip to main content

fuel_tensor/
cpu_accel.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! One-time install of the kernels that live ABOVE `fuel-dispatch` into the global binding table: the vendor CPU
3//! BLAS kernels (oneMKL behind the `onemkl` feature, AOCL behind `aocl`; ROADMAP row 66) and the Vulkan kernels
4//! (`fuel-vulkan-dispatch`, behind `vulkan`; ROADMAP row 137 step 6.1).
5//!
6//! **Order matters (the snapshot hazard).** [`ensure_installed`] runs BEFORE the bridge takes its
7//! `SystemTopology` snapshot and its snapshot of the global table (the topology is built from the table, so a
8//! backend installed after it is absent from `backends_for(..)`: GAP-359). An extension publishes a new table for later readers; a snapshot already taken
9//! keeps the old one, so a kernel installed after it is invisible to that realize with no error. The Vulkan
10//! install is therefore NOT optional in this function, and `tests/vulkan_install_before_snapshot.rs` fails if it is
11//! removed or moved after the snapshot.
12//!
13//! `fuel_mkl_cpu_backend::register_mkl_cpu_kernels` had no production caller: building with
14//! `--features onemkl` linked the backend and then never offered its matmul to the judge. The
15//! first lazy realize now probes the library and, if it loads, extends the global bindings once.
16//!
17//! A library that is NOT loadable is not an error: nothing is registered, the scalar CPU kernels
18//! stay in force, and [`cpu_accel_report`] says why, so a user can ask "why not MKL".
19//!
20//! Status: wired, NOT run on hardware by CI (no hosted runner has oneMKL or AOCL). The once-only logic in
21//! `install_once` is feature-independent and unit-tested in every build.
22
23#[cfg(any(feature = "onemkl", feature = "aocl", test))]
24use std::sync::OnceLock;
25
26/// What happened when a backend's kernels were considered for installation.
27#[derive(Debug, Clone, PartialEq, Eq)]
28pub enum AccelStatus {
29    /// The probe passed and the kernels were added to the global binding table.
30    Registered,
31    /// The probe failed; nothing was registered. Carries the probe's error text.
32    NotLoadable(String),
33}
34
35/// Run `probe` then, if it passed, `register`, at most once per `cell`; later calls return the
36/// recorded status without calling either closure again.
37#[cfg(any(feature = "onemkl", feature = "aocl", test))]
38pub(crate) fn install_once(
39    cell: &OnceLock<AccelStatus>,
40    probe: impl FnOnce() -> Result<(), String>,
41    register: impl FnOnce(),
42) -> AccelStatus {
43    cell.get_or_init(|| match probe() {
44        Ok(()) => {
45            register();
46            AccelStatus::Registered
47        }
48        Err(why) => AccelStatus::NotLoadable(why),
49    })
50    .clone()
51}
52
53#[cfg(feature = "onemkl")]
54static MKL: OnceLock<AccelStatus> = OnceLock::new();
55#[cfg(feature = "aocl")]
56static AOCL: OnceLock<AccelStatus> = OnceLock::new();
57
58/// Install every enabled vendor CPU backend, once. Cheap after the first call.
59pub(crate) fn ensure_installed() {
60    // Vulkan kernels (idempotent: `install_global` is once-only). With the `vulkan` feature off there is nothing here.
61    #[cfg(feature = "vulkan")]
62    fuel_vulkan_dispatch::install_global();
63    // CUDA kernels (row 137 step 6.2), same once-only install and same snapshot rule as Vulkan above.
64    #[cfg(feature = "cuda")]
65    fuel_cuda_dispatch::install_global();
66    #[cfg(feature = "onemkl")]
67    {
68        install_once(
69            &MKL,
70            || fuel_mkl_cpu_backend::probe_mkl_loadable().map_err(|e| format!("{e:?}")),
71            || {
72                fuel_dispatch::dispatch::extend_global_bindings(
73                    fuel_mkl_cpu_backend::register_mkl_cpu_kernels,
74                )
75            },
76        );
77    }
78    #[cfg(feature = "aocl")]
79    {
80        install_once(
81            &AOCL,
82            || fuel_aocl_cpu_backend::probe_aocl_loadable().map_err(|e| format!("{e:?}")),
83            || {
84                fuel_dispatch::dispatch::extend_global_bindings(
85                    fuel_aocl_cpu_backend::register_aocl_cpu_kernels,
86                )
87            },
88        );
89    }
90}
91
92/// The install result per vendor backend that this build enables, as `(name, status)`. A backend
93/// whose feature is off is absent, and so is one before the first lazy realize has run.
94pub fn cpu_accel_report() -> Vec<(&'static str, AccelStatus)> {
95    #[allow(unused_mut)]
96    let mut out: Vec<(&'static str, AccelStatus)> = Vec::new();
97    #[cfg(feature = "onemkl")]
98    if let Some(s) = MKL.get() {
99        out.push(("mkl", s.clone()));
100    }
101    #[cfg(feature = "aocl")]
102    if let Some(s) = AOCL.get() {
103        out.push(("aocl", s.clone()));
104    }
105    out
106}
107
108#[cfg(test)]
109mod tests {
110    use super::*;
111    use std::sync::atomic::{AtomicUsize, Ordering};
112
113    #[test]
114    fn a_loadable_library_registers_exactly_once_across_calls() {
115        let cell = OnceLock::new();
116        let registered = AtomicUsize::new(0);
117        for _ in 0..3 {
118            let s = install_once(
119                &cell,
120                || Ok(()),
121                || {
122                    registered.fetch_add(1, Ordering::SeqCst);
123                },
124            );
125            assert_eq!(s, AccelStatus::Registered);
126        }
127        assert_eq!(registered.load(Ordering::SeqCst), 1);
128    }
129
130    #[test]
131    fn an_unloadable_library_registers_nothing_and_says_why() {
132        let cell = OnceLock::new();
133        let registered = AtomicUsize::new(0);
134        let s = install_once(
135            &cell,
136            || Err("mkl_rt.dll not found".to_string()),
137            || {
138                registered.fetch_add(1, Ordering::SeqCst);
139            },
140        );
141        assert_eq!(s, AccelStatus::NotLoadable("mkl_rt.dll not found".into()));
142        assert_eq!(registered.load(Ordering::SeqCst), 0);
143        // A second call does not re-probe: the recorded failure stands.
144        let again = install_once(&cell, || Ok(()), || registered.store(99, Ordering::SeqCst));
145        assert_eq!(again, s);
146        assert_eq!(registered.load(Ordering::SeqCst), 0);
147    }
148
149    #[cfg(any(feature = "onemkl", feature = "aocl"))]
150    #[test]
151    fn ensure_installed_records_a_status_once_with_the_features_on() {
152        ensure_installed();
153        let first = cpu_accel_report();
154        ensure_installed();
155        let expected = usize::from(cfg!(feature = "onemkl")) + usize::from(cfg!(feature = "aocl"));
156        assert_eq!(first.len(), expected);
157        assert_eq!(cpu_accel_report(), first);
158    }
159}