Skip to main content

tenferro_fft/
backend.rs

1use std::fmt;
2
3use tenferro_runtime::ExtensionCacheStore;
4use tenferro_tensor::{Engine, Tensor, TensorRead};
5
6use crate::{FftPlanCache, FftPlanSpec};
7
8#[derive(Clone, Copy, Debug)]
9pub(crate) enum FftCacheOwner {
10    CallerOwned,
11    EngineOwned,
12}
13
14/// Execution-cache state supplied to an [`FftBackend`].
15///
16/// Direct repeated calls use a caller-owned [`FftPlanCache`], while traced
17/// and eager execution use the executing engine's own [`ExtensionCacheStore`]
18/// (lent by the runtime for the run). The two differ in what they may hold:
19///
20/// * a caller-owned cache may outlive the engine and be used with several
21///   engines, so it holds only engine-independent plans (the CPU's rustfft
22///   plans);
23/// * an engine-owned store dies with its engine, so a device backend keeps
24///   device-bound plans and workspaces (cuFFT plans) only there. Given a
25///   caller-owned cache, a device backend keeps its device-bound plans in its
26///   own engine instead.
27///
28/// Constructors keep the owner representation closed.
29///
30/// # Examples
31///
32/// ```
33/// use tenferro_fft::{FftExecutionCache, FftPlanCache};
34///
35/// let mut plans = FftPlanCache::default();
36/// let cache = FftExecutionCache::caller_owned(&mut plans);
37/// assert!(format!("{cache:?}").contains("CallerOwned"));
38/// ```
39pub struct FftExecutionCache<'a> {
40    owner: FftCacheOwner,
41    store: &'a mut ExtensionCacheStore,
42}
43
44impl fmt::Debug for FftExecutionCache<'_> {
45    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
46        f.debug_struct("FftExecutionCache")
47            .field("owner", &self.owner)
48            .field(
49                "stats",
50                &self
51                    .store
52                    .stats(tenferro_runtime::ExtensionCacheSelector::All),
53            )
54            .finish_non_exhaustive()
55    }
56}
57
58impl<'a> FftExecutionCache<'a> {
59    /// Build a context backed by a caller-owned typed FFT execution cache.
60    pub fn caller_owned(cache: &'a mut FftPlanCache) -> Self {
61        Self {
62            owner: FftCacheOwner::CallerOwned,
63            store: cache.store_mut(),
64        }
65    }
66
67    /// Build a context backed by the executing engine's own extension cache
68    /// store, which may hold device-bound plans.
69    ///
70    /// # Examples
71    ///
72    /// ```
73    /// use tenferro_fft::FftExecutionCache;
74    /// use tenferro_runtime::ExtensionCacheStore;
75    ///
76    /// let mut store = ExtensionCacheStore::default();
77    /// let cache = FftExecutionCache::engine_owned(&mut store);
78    /// assert!(cache.is_engine_owned());
79    /// ```
80    pub fn engine_owned(cache: &'a mut ExtensionCacheStore) -> Self {
81        Self {
82            owner: FftCacheOwner::EngineOwned,
83            store: cache,
84        }
85    }
86
87    /// Whether this store belongs to the executing engine, so device-bound
88    /// entries may be retained in it.
89    ///
90    /// # Examples
91    ///
92    /// ```
93    /// use tenferro_fft::{FftExecutionCache, FftPlanCache};
94    ///
95    /// let mut plans = FftPlanCache::default();
96    /// assert!(!FftExecutionCache::caller_owned(&mut plans).is_engine_owned());
97    /// ```
98    pub fn is_engine_owned(&self) -> bool {
99        matches!(self.owner, FftCacheOwner::EngineOwned)
100    }
101
102    /// Borrow the bounded typed store owned by the caller or extension runtime.
103    ///
104    /// Backend implementations should use a stable family/cache namespace and
105    /// include every plan-identity field in the key discriminator. The store
106    /// owns LRU bounds, typed retrieval, clear behavior, entry counts, and the
107    /// retained-byte estimates supplied at insertion.
108    pub fn store_mut(&mut self) -> &mut ExtensionCacheStore {
109        self.store
110    }
111
112    /// Borrow the store under the ownership tag of `self`.
113    ///
114    /// A request that executes one backend call per axis hands the backend a
115    /// fresh cache view per step; the tag must survive that split so a
116    /// caller-owned cache is never treated as engine-owned storage.
117    pub(crate) fn with_owner(owner: FftCacheOwner, store: &'a mut ExtensionCacheStore) -> Self {
118        Self { owner, store }
119    }
120
121    /// Return the ownership tag of this cache view.
122    pub(crate) fn owner(&self) -> FftCacheOwner {
123        self.owner
124    }
125}
126
127/// Explicit backend capability required by concrete and traced FFT execution.
128///
129/// Implementations must execute on the input's existing placement. Unsupported
130/// dtypes, layouts, placements, or operations return an error; they must never
131/// transfer the tensor or select a different backend.
132///
133/// # Examples
134/// Backend surface required by the FFT extension runtime and the built-in
135/// concrete FFT dispatch.
136///
137/// This is a backend SPI: third-party backend implementers implement this
138/// trait on their execution sessions to provide FFT capability. The concrete
139/// [`FftOps`](crate::FftOps)/[`FftOps`](crate::FftOps) methods and [`FftExecutor`](crate::FftExecutor) take an
140/// erased `&mut dyn Engine` and dispatch **internally** to the
141/// built-in CPU/CUDA/WebGPU execution sessions; a session without this
142/// capability returns a typed `Error::Unsupported` instead of being accepted
143/// as an arbitrary third-party backend (issue #1680 Phase 3).
144///
145/// # Examples
146///
147/// ```
148/// use tenferro_cpu::CpuEngine;
149/// use tenferro_fft::FftBackend;
150///
151/// fn accepts_fft_backend<B: FftBackend>() {}
152///
153/// accepts_fft_backend::<CpuEngine>();
154/// ```
155///
156/// A generic engine does not expose the FFT capability at the SPI level:
157///
158/// ```compile_fail
159/// use tenferro_tensor::Engine;
160/// use tenferro_fft::FftBackend;
161///
162/// fn requires_fft_backend<B: Engine>(engine: &mut B) {
163///     let _: &mut dyn FftBackend = engine;
164/// }
165/// ```
166pub trait FftBackend: Engine {
167    /// Validate a borrowed runtime input before the extension read path
168    /// materializes it into a compact tensor.
169    ///
170    /// Backends that can materialize their own placement may keep the default
171    /// no-op. CPU overrides this to report device inputs as unsupported FFT
172    /// placement errors instead of leaking a generic host-materialization error.
173    ///
174    /// # Errors
175    ///
176    /// Returns [`tenferro_tensor::Error::Unsupported`] when this backend cannot
177    /// consume the borrowed input placement without an explicit transfer.
178    fn validate_fft_read_input(
179        &self,
180        _op: &'static str,
181        _input: &TensorRead<'_>,
182    ) -> tenferro_tensor::Result<()> {
183        Ok(())
184    }
185
186    /// Execute a validated FFT from borrowed storage.
187    ///
188    /// The default explicitly canonicalizes view inputs. Backends supporting
189    /// compact borrowed storage override this method to avoid input copies.
190    ///
191    /// # Examples
192    /// The borrowed public surface dispatches through this backend hook:
193    /// ```
194    /// use num_complex::Complex64;
195    /// use tenferro_cpu::CpuEngine;
196    /// use tenferro_fft::{FftOps, FftOptions};
197    /// use tenferro_tensor::{Tensor, TensorRead};
198    /// let input = Tensor::from_vec_col_major([2], vec![Complex64::new(1., 0.); 2])?;
199    /// let mut engine = CpuEngine::serial();
200    /// let output =
201    ///     TensorRead::Tensor(&input).fft_with(&FftOptions::default().axis(0), &mut engine)?;
202    /// assert_eq!(output.as_slice::<Complex64>()?, &[Complex64::new(2., 0.), Complex64::new(0., 0.)]);
203    /// # Ok::<(), Box<dyn std::error::Error>>(())
204    /// ```
205    ///
206    /// # Errors
207    /// Returns [`tenferro_tensor::Error::Unsupported`] for unsupported dtype,
208    /// layout, or placement, and [`tenferro_tensor::Error::Validation`] when
209    /// input metadata disagrees with the validated spec. Same-placement
210    /// canonicalization, plan creation, and execution failures preserve the
211    /// selected backend's typed error source; no implicit transfer is performed.
212    fn execute_fft_read(
213        &mut self,
214        input: TensorRead<'_>,
215        spec: &FftPlanSpec,
216        cache: FftExecutionCache<'_>,
217    ) -> tenferro_tensor::Result<Tensor> {
218        match input {
219            TensorRead::Tensor(input) => self.execute_fft(input, spec, cache),
220            input => {
221                let owned = self.to_contiguous_read(input)?;
222                self.execute_fft(&owned, spec, cache)
223            }
224        }
225    }
226
227    /// Execute one validated FFT request on `input`'s existing placement.
228    ///
229    /// # Errors
230    ///
231    /// Returns [`tenferro_tensor::Error::Unsupported`] for an unsupported
232    /// operation, dtype, layout, or placement;
233    /// [`tenferro_tensor::Error::Validation`] for inconsistent input/spec
234    /// metadata or checked shape arithmetic; and a typed backend or runtime
235    /// source when plan creation, cache access, or execution fails.
236    fn execute_fft(
237        &mut self,
238        input: &Tensor,
239        spec: &FftPlanSpec,
240        cache: FftExecutionCache<'_>,
241    ) -> tenferro_tensor::Result<Tensor>;
242}
243
244#[cfg(test)]
245mod tests;