Skip to main content

tenferro_tensor/
capability.rs

1//! Backend operation capability descriptors.
2//!
3//! # Examples
4//!
5//! ```rust
6//! use tenferro_core_ops::PrimitiveOpKind;
7//! use tenferro_tensor::{capability_output_dtype, DType};
8//!
9//! assert_eq!(
10//!     capability_output_dtype(PrimitiveOpKind::Compare, DType::F64),
11//!     Some(DType::Bool)
12//! );
13//! ```
14
15use std::fmt;
16
17use tenferro_core_ops::{descriptor, DTypePolicy, PrimitiveOpKind};
18
19use crate::DType;
20
21/// Stable backend identifier used by capability descriptors.
22///
23/// # Examples
24///
25/// ```rust
26/// use tenferro_tensor::BackendId;
27///
28/// assert_eq!(BackendId::Cuda.as_str(), "cuda");
29/// ```
30#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
31pub enum BackendId {
32    Cpu,
33    Cuda,
34    WebGpu,
35    Other(&'static str),
36}
37
38impl BackendId {
39    /// Return the stable backend name used in diagnostics and generated docs.
40    ///
41    /// # Examples
42    ///
43    /// ```rust
44    /// use tenferro_tensor::BackendId;
45    ///
46    /// assert_eq!(BackendId::Cpu.as_str(), "cpu");
47    /// ```
48    #[must_use]
49    pub const fn as_str(self) -> &'static str {
50        match self {
51            Self::Cpu => "cpu",
52            Self::Cuda => "cuda",
53            Self::WebGpu => "webgpu",
54            Self::Other(name) => name,
55        }
56    }
57}
58
59impl fmt::Display for BackendId {
60    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61        f.write_str(self.as_str())
62    }
63}
64
65/// Three-valued support level for a backend capability axis.
66///
67/// `FallbackCopy` is intentionally distinct from `Native`: the operation is
68/// accepted, but only by materializing through a default/copy path.
69///
70/// # Examples
71///
72/// ```rust
73/// use tenferro_tensor::SupportLevel;
74///
75/// assert!(SupportLevel::Native > SupportLevel::FallbackCopy);
76/// assert!(SupportLevel::FallbackCopy.is_supported());
77/// assert!(!SupportLevel::Unsupported.is_supported());
78/// ```
79#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
80pub enum SupportLevel {
81    Unsupported,
82    FallbackCopy,
83    Native,
84}
85
86impl SupportLevel {
87    /// Return whether this level represents any usable implementation.
88    ///
89    /// # Examples
90    ///
91    /// ```rust
92    /// use tenferro_tensor::SupportLevel;
93    ///
94    /// assert!(SupportLevel::Native.is_supported());
95    /// assert!(!SupportLevel::Unsupported.is_supported());
96    /// ```
97    #[must_use]
98    pub const fn is_supported(self) -> bool {
99        !matches!(self, Self::Unsupported)
100    }
101}
102
103/// Axis within an operation capability entry.
104///
105/// # Examples
106///
107/// ```rust
108/// use tenferro_tensor::CapabilityAxis;
109///
110/// let axis = CapabilityAxis::ReadInputs;
111/// assert_eq!(format!("{axis:?}"), "ReadInputs");
112/// ```
113#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
114pub enum CapabilityAxis {
115    OwnedResult,
116    ReadInputs,
117    WriteOutput,
118    StridedOutput,
119    Accumulation,
120}
121
122/// Query key for a backend capability lookup.
123///
124/// # Examples
125///
126/// ```rust
127/// use tenferro_core_ops::PrimitiveOpKind;
128/// use tenferro_tensor::{CapabilityQuery, DType};
129///
130/// let query = CapabilityQuery::new(PrimitiveOpKind::Add, DType::F32);
131/// assert_eq!(query.dtype, DType::F32);
132/// ```
133#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
134pub struct CapabilityQuery {
135    pub op: PrimitiveOpKind,
136    pub dtype: DType,
137}
138
139impl CapabilityQuery {
140    /// Build a capability lookup key.
141    ///
142    /// # Examples
143    ///
144    /// ```rust
145    /// use tenferro_core_ops::PrimitiveOpKind;
146    /// use tenferro_tensor::{CapabilityQuery, DType};
147    ///
148    /// assert_eq!(
149    ///     CapabilityQuery::new(PrimitiveOpKind::Mul, DType::I64).op,
150    ///     PrimitiveOpKind::Mul
151    /// );
152    /// ```
153    #[must_use]
154    pub const fn new(op: PrimitiveOpKind, dtype: DType) -> Self {
155        Self { op, dtype }
156    }
157}
158
159/// One backend capability entry for a primitive op and input dtype.
160///
161/// # Examples
162///
163/// ```rust
164/// use tenferro_core_ops::PrimitiveOpKind;
165/// use tenferro_tensor::{
166///     BackendId, CapabilityAxis, DType, OperationCapability, SupportLevel,
167/// };
168///
169/// let entry = OperationCapability {
170///     backend: BackendId::Cpu,
171///     op: PrimitiveOpKind::Add,
172///     dtype: DType::F64,
173///     output_dtype: DType::F64,
174///     result: SupportLevel::Native,
175///     read_inputs: SupportLevel::Native,
176///     write_output: SupportLevel::Native,
177///     strided_output: SupportLevel::Native,
178///     accumulation: SupportLevel::Unsupported,
179/// };
180/// assert_eq!(entry.axis(CapabilityAxis::OwnedResult), SupportLevel::Native);
181/// ```
182#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
183pub struct OperationCapability {
184    pub backend: BackendId,
185    pub op: PrimitiveOpKind,
186    pub dtype: DType,
187    pub output_dtype: DType,
188    pub result: SupportLevel,
189    pub read_inputs: SupportLevel,
190    pub write_output: SupportLevel,
191    pub strided_output: SupportLevel,
192    pub accumulation: SupportLevel,
193}
194
195impl OperationCapability {
196    /// Return the support level for one capability axis.
197    ///
198    /// # Examples
199    ///
200    /// ```rust
201    /// use tenferro_core_ops::PrimitiveOpKind;
202    /// use tenferro_tensor::{
203    ///     BackendId, CapabilityAxis, DType, OperationCapability, SupportLevel,
204    /// };
205    ///
206    /// let entry = OperationCapability {
207    ///     backend: BackendId::Cuda,
208    ///     op: PrimitiveOpKind::ReduceSum,
209    ///     dtype: DType::I32,
210    ///     output_dtype: DType::I32,
211    ///     result: SupportLevel::Native,
212    ///     read_inputs: SupportLevel::FallbackCopy,
213    ///     write_output: SupportLevel::Unsupported,
214    ///     strided_output: SupportLevel::Unsupported,
215    ///     accumulation: SupportLevel::Unsupported,
216    /// };
217    /// assert_eq!(entry.axis(CapabilityAxis::ReadInputs), SupportLevel::FallbackCopy);
218    /// ```
219    #[must_use]
220    pub const fn axis(&self, axis: CapabilityAxis) -> SupportLevel {
221        match axis {
222            CapabilityAxis::OwnedResult => self.result,
223            CapabilityAxis::ReadInputs => self.read_inputs,
224            CapabilityAxis::WriteOutput => self.write_output,
225            CapabilityAxis::StridedOutput => self.strided_output,
226            CapabilityAxis::Accumulation => self.accumulation,
227        }
228    }
229}
230
231/// Resolve one operation/dtype entry against a backend capability table.
232///
233/// This is the single lookup rule behind [`TensorBackendCapability::capability`].
234/// Backends and their operation kernels call it directly so a support decision
235/// is spelled once instead of re-implemented next to each table.
236///
237/// `axis` selects the capability axis the caller needs: `None` returns the
238/// declared entry without judging it, `Some(_)` returns it only when that axis
239/// reports support.
240///
241/// # Examples
242///
243/// ```rust
244/// use tenferro_core_ops::PrimitiveOpKind;
245/// use tenferro_tensor::{
246///     capability_entry, BackendId, CapabilityAxis, CapabilityQuery, DType,
247///     OperationCapability, SupportLevel,
248/// };
249///
250/// const ENTRIES: &[OperationCapability] = &[OperationCapability {
251///     backend: BackendId::Cpu,
252///     op: PrimitiveOpKind::Exp,
253///     dtype: DType::F64,
254///     output_dtype: DType::F64,
255///     result: SupportLevel::Native,
256///     read_inputs: SupportLevel::Native,
257///     write_output: SupportLevel::Unsupported,
258///     strided_output: SupportLevel::Unsupported,
259///     accumulation: SupportLevel::Unsupported,
260/// }];
261/// let query = CapabilityQuery::new(PrimitiveOpKind::Exp, DType::F64);
262///
263/// assert!(capability_entry(ENTRIES, BackendId::Cpu, query, Some(CapabilityAxis::ReadInputs)).is_some());
264/// assert!(capability_entry(ENTRIES, BackendId::Cpu, query, Some(CapabilityAxis::WriteOutput)).is_none());
265/// assert!(capability_entry(ENTRIES, BackendId::Cuda, query, None).is_none());
266/// ```
267#[must_use]
268pub fn capability_entry(
269    entries: &[OperationCapability],
270    backend: BackendId,
271    query: CapabilityQuery,
272    axis: Option<CapabilityAxis>,
273) -> Option<OperationCapability> {
274    entries
275        .iter()
276        .copied()
277        .find(|entry| {
278            entry.backend == backend && entry.op == query.op && entry.dtype == query.dtype
279        })
280        .filter(|entry| axis.is_none_or(|axis| entry.axis(axis).is_supported()))
281}
282
283/// Backend capability query surface.
284///
285/// # Examples
286///
287/// ```rust
288/// use tenferro_core_ops::PrimitiveOpKind;
289/// use tenferro_tensor::{
290///     BackendId, CapabilityQuery, DType, OperationCapability, SupportLevel,
291///     TensorBackendCapability,
292/// };
293///
294/// struct Backend;
295///
296/// const ENTRIES: &[OperationCapability] = &[OperationCapability {
297///     backend: BackendId::Cpu,
298///     op: PrimitiveOpKind::Add,
299///     dtype: DType::F32,
300///     output_dtype: DType::F32,
301///     result: SupportLevel::Native,
302///     read_inputs: SupportLevel::Native,
303///     write_output: SupportLevel::Native,
304///     strided_output: SupportLevel::Native,
305///     accumulation: SupportLevel::Unsupported,
306/// }];
307///
308/// impl TensorBackendCapability for Backend {
309///     fn backend_id(&self) -> BackendId { BackendId::Cpu }
310///     fn capabilities(&self) -> &'static [OperationCapability] { ENTRIES }
311/// }
312///
313/// assert!(Backend
314///     .capability(CapabilityQuery::new(PrimitiveOpKind::Add, DType::F32))
315///     .is_some());
316/// ```
317pub trait TensorBackendCapability {
318    fn backend_id(&self) -> BackendId;
319    fn capabilities(&self) -> &'static [OperationCapability];
320
321    /// Look up one operation/dtype capability for this backend.
322    ///
323    /// # Examples
324    ///
325    /// ```rust
326    /// use tenferro_core_ops::PrimitiveOpKind;
327    /// use tenferro_tensor::{
328    ///     BackendId, CapabilityQuery, DType, OperationCapability, SupportLevel,
329    ///     TensorBackendCapability,
330    /// };
331    ///
332    /// struct Backend;
333    /// const ENTRIES: &[OperationCapability] = &[OperationCapability {
334    ///     backend: BackendId::Cpu,
335    ///     op: PrimitiveOpKind::Mul,
336    ///     dtype: DType::I64,
337    ///     output_dtype: DType::I64,
338    ///     result: SupportLevel::Native,
339    ///     read_inputs: SupportLevel::Native,
340    ///     write_output: SupportLevel::Unsupported,
341    ///     strided_output: SupportLevel::Unsupported,
342    ///     accumulation: SupportLevel::Unsupported,
343    /// }];
344    /// impl TensorBackendCapability for Backend {
345    ///     fn backend_id(&self) -> BackendId { BackendId::Cpu }
346    ///     fn capabilities(&self) -> &'static [OperationCapability] { ENTRIES }
347    /// }
348    ///
349    /// let entry = Backend
350    ///     .capability(CapabilityQuery::new(PrimitiveOpKind::Mul, DType::I64))
351    ///     .unwrap();
352    /// assert_eq!(entry.result, SupportLevel::Native);
353    /// ```
354    #[must_use]
355    fn capability(&self, query: CapabilityQuery) -> Option<OperationCapability> {
356        capability_entry(self.capabilities(), self.backend_id(), query, None)
357    }
358}
359
360/// Return the output dtype allowed by the core op catalog policy for a unary
361/// dtype representative.
362///
363/// `None` means the catalog policy does not admit the queried dtype. Backend
364/// descriptors add implementation support on top of this semantic policy.
365///
366/// # Examples
367///
368/// ```rust
369/// use tenferro_core_ops::PrimitiveOpKind;
370/// use tenferro_tensor::{capability_output_dtype, DType};
371///
372/// assert_eq!(
373///     capability_output_dtype(PrimitiveOpKind::Abs, DType::C64),
374///     Some(DType::F64)
375/// );
376/// assert_eq!(
377///     capability_output_dtype(PrimitiveOpKind::Pow, DType::I32),
378///     Some(DType::I32)
379/// );
380/// ```
381#[must_use]
382pub fn capability_output_dtype(op: PrimitiveOpKind, dtype: DType) -> Option<DType> {
383    let policy = descriptor(op).dtype_policy;
384    match policy {
385        DTypePolicy::SameAny => Some(dtype),
386        DTypePolicy::SameNumeric => numeric_dtype(dtype).then_some(dtype),
387        DTypePolicy::SameFloat => float_dtype(dtype).then_some(dtype),
388        DTypePolicy::AbsToReal => match dtype {
389            DType::F32 => Some(DType::F32),
390            DType::F64 => Some(DType::F64),
391            DType::I32 => Some(DType::I32),
392            DType::I64 => Some(DType::I64),
393            DType::C32 => Some(DType::F32),
394            DType::C64 => Some(DType::F64),
395            // An externally defined scalar is not in tenferro's operation
396            // catalog, so no core operation claims an output dtype for it.
397            DType::Bool | DType::External(_) => None,
398        },
399        DTypePolicy::SameFloatOrComplex => float_or_complex_dtype(dtype).then_some(dtype),
400        DTypePolicy::CompareToBool => comparable_dtype(dtype).then_some(DType::Bool),
401        DTypePolicy::BoolSelect => Some(dtype),
402        DTypePolicy::Convert | DTypePolicy::Shape | DTypePolicy::Constant => Some(dtype),
403    }
404}
405
406const fn numeric_dtype(dtype: DType) -> bool {
407    matches!(
408        dtype,
409        DType::F32 | DType::F64 | DType::I32 | DType::I64 | DType::C32 | DType::C64
410    )
411}
412
413const fn float_dtype(dtype: DType) -> bool {
414    matches!(dtype, DType::F32 | DType::F64)
415}
416
417const fn float_or_complex_dtype(dtype: DType) -> bool {
418    matches!(dtype, DType::F32 | DType::F64 | DType::C32 | DType::C64)
419}
420
421const fn comparable_dtype(dtype: DType) -> bool {
422    matches!(
423        dtype,
424        DType::F32 | DType::F64 | DType::I32 | DType::I64 | DType::Bool
425    )
426}