Skip to main content

fuel_tensor/
cpu_accel.rs

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