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