tenferro-tensor 0.3.0

Dense runtime tensors, views, backend traits, and backend-independent contracts for tenferro.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
//! Backend operation capability descriptors.
//!
//! # Examples
//!
//! ```rust
//! use tenferro_core_ops::PrimitiveOpKind;
//! use tenferro_tensor::{capability_output_dtype, DType};
//!
//! assert_eq!(
//!     capability_output_dtype(PrimitiveOpKind::Compare, DType::F64),
//!     Some(DType::Bool)
//! );
//! ```

use std::fmt;

use tenferro_core_ops::{descriptor, DTypePolicy, PrimitiveOpKind};

use crate::DType;

/// Stable backend identifier used by capability descriptors.
///
/// # Examples
///
/// ```rust
/// use tenferro_tensor::BackendId;
///
/// assert_eq!(BackendId::Cuda.as_str(), "cuda");
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum BackendId {
    Cpu,
    Cuda,
    WebGpu,
    Other(&'static str),
}

impl BackendId {
    /// Return the stable backend name used in diagnostics and generated docs.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_tensor::BackendId;
    ///
    /// assert_eq!(BackendId::Cpu.as_str(), "cpu");
    /// ```
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Cpu => "cpu",
            Self::Cuda => "cuda",
            Self::WebGpu => "webgpu",
            Self::Other(name) => name,
        }
    }
}

impl fmt::Display for BackendId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Three-valued support level for a backend capability axis.
///
/// `FallbackCopy` is intentionally distinct from `Native`: the operation is
/// accepted, but only by materializing through a default/copy path.
///
/// # Examples
///
/// ```rust
/// use tenferro_tensor::SupportLevel;
///
/// assert!(SupportLevel::Native > SupportLevel::FallbackCopy);
/// assert!(SupportLevel::FallbackCopy.is_supported());
/// assert!(!SupportLevel::Unsupported.is_supported());
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum SupportLevel {
    Unsupported,
    FallbackCopy,
    Native,
}

impl SupportLevel {
    /// Return whether this level represents any usable implementation.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_tensor::SupportLevel;
    ///
    /// assert!(SupportLevel::Native.is_supported());
    /// assert!(!SupportLevel::Unsupported.is_supported());
    /// ```
    #[must_use]
    pub const fn is_supported(self) -> bool {
        !matches!(self, Self::Unsupported)
    }
}

/// Axis within an operation capability entry.
///
/// # Examples
///
/// ```rust
/// use tenferro_tensor::CapabilityAxis;
///
/// let axis = CapabilityAxis::ReadInputs;
/// assert_eq!(format!("{axis:?}"), "ReadInputs");
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum CapabilityAxis {
    OwnedResult,
    ReadInputs,
    WriteOutput,
    StridedOutput,
    Accumulation,
}

/// Query key for a backend capability lookup.
///
/// # Examples
///
/// ```rust
/// use tenferro_core_ops::PrimitiveOpKind;
/// use tenferro_tensor::{CapabilityQuery, DType};
///
/// let query = CapabilityQuery::new(PrimitiveOpKind::Add, DType::F32);
/// assert_eq!(query.dtype, DType::F32);
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct CapabilityQuery {
    pub op: PrimitiveOpKind,
    pub dtype: DType,
}

impl CapabilityQuery {
    /// Build a capability lookup key.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_core_ops::PrimitiveOpKind;
    /// use tenferro_tensor::{CapabilityQuery, DType};
    ///
    /// assert_eq!(
    ///     CapabilityQuery::new(PrimitiveOpKind::Mul, DType::I64).op,
    ///     PrimitiveOpKind::Mul
    /// );
    /// ```
    #[must_use]
    pub const fn new(op: PrimitiveOpKind, dtype: DType) -> Self {
        Self { op, dtype }
    }
}

/// One backend capability entry for a primitive op and input dtype.
///
/// # Examples
///
/// ```rust
/// use tenferro_core_ops::PrimitiveOpKind;
/// use tenferro_tensor::{
///     BackendId, CapabilityAxis, DType, OperationCapability, SupportLevel,
/// };
///
/// let entry = OperationCapability {
///     backend: BackendId::Cpu,
///     op: PrimitiveOpKind::Add,
///     dtype: DType::F64,
///     output_dtype: DType::F64,
///     result: SupportLevel::Native,
///     read_inputs: SupportLevel::Native,
///     write_output: SupportLevel::Native,
///     strided_output: SupportLevel::Native,
///     accumulation: SupportLevel::Unsupported,
/// };
/// assert_eq!(entry.axis(CapabilityAxis::OwnedResult), SupportLevel::Native);
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct OperationCapability {
    pub backend: BackendId,
    pub op: PrimitiveOpKind,
    pub dtype: DType,
    pub output_dtype: DType,
    pub result: SupportLevel,
    pub read_inputs: SupportLevel,
    pub write_output: SupportLevel,
    pub strided_output: SupportLevel,
    pub accumulation: SupportLevel,
}

impl OperationCapability {
    /// Return the support level for one capability axis.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_core_ops::PrimitiveOpKind;
    /// use tenferro_tensor::{
    ///     BackendId, CapabilityAxis, DType, OperationCapability, SupportLevel,
    /// };
    ///
    /// let entry = OperationCapability {
    ///     backend: BackendId::Cuda,
    ///     op: PrimitiveOpKind::ReduceSum,
    ///     dtype: DType::I32,
    ///     output_dtype: DType::I32,
    ///     result: SupportLevel::Native,
    ///     read_inputs: SupportLevel::FallbackCopy,
    ///     write_output: SupportLevel::Unsupported,
    ///     strided_output: SupportLevel::Unsupported,
    ///     accumulation: SupportLevel::Unsupported,
    /// };
    /// assert_eq!(entry.axis(CapabilityAxis::ReadInputs), SupportLevel::FallbackCopy);
    /// ```
    #[must_use]
    pub const fn axis(&self, axis: CapabilityAxis) -> SupportLevel {
        match axis {
            CapabilityAxis::OwnedResult => self.result,
            CapabilityAxis::ReadInputs => self.read_inputs,
            CapabilityAxis::WriteOutput => self.write_output,
            CapabilityAxis::StridedOutput => self.strided_output,
            CapabilityAxis::Accumulation => self.accumulation,
        }
    }
}

/// Backend capability query surface.
///
/// # Examples
///
/// ```rust
/// use tenferro_core_ops::PrimitiveOpKind;
/// use tenferro_tensor::{
///     BackendId, CapabilityQuery, DType, OperationCapability, SupportLevel,
///     TensorBackendCapability,
/// };
///
/// struct Backend;
///
/// const ENTRIES: &[OperationCapability] = &[OperationCapability {
///     backend: BackendId::Cpu,
///     op: PrimitiveOpKind::Add,
///     dtype: DType::F32,
///     output_dtype: DType::F32,
///     result: SupportLevel::Native,
///     read_inputs: SupportLevel::Native,
///     write_output: SupportLevel::Native,
///     strided_output: SupportLevel::Native,
///     accumulation: SupportLevel::Unsupported,
/// }];
///
/// impl TensorBackendCapability for Backend {
///     fn backend_id(&self) -> BackendId { BackendId::Cpu }
///     fn capabilities(&self) -> &'static [OperationCapability] { ENTRIES }
/// }
///
/// assert!(Backend
///     .capability(CapabilityQuery::new(PrimitiveOpKind::Add, DType::F32))
///     .is_some());
/// ```
pub trait TensorBackendCapability {
    fn backend_id(&self) -> BackendId;
    fn capabilities(&self) -> &'static [OperationCapability];

    /// Look up one operation/dtype capability for this backend.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_core_ops::PrimitiveOpKind;
    /// use tenferro_tensor::{
    ///     BackendId, CapabilityQuery, DType, OperationCapability, SupportLevel,
    ///     TensorBackendCapability,
    /// };
    ///
    /// struct Backend;
    /// const ENTRIES: &[OperationCapability] = &[OperationCapability {
    ///     backend: BackendId::Cpu,
    ///     op: PrimitiveOpKind::Mul,
    ///     dtype: DType::I64,
    ///     output_dtype: DType::I64,
    ///     result: SupportLevel::Native,
    ///     read_inputs: SupportLevel::Native,
    ///     write_output: SupportLevel::Unsupported,
    ///     strided_output: SupportLevel::Unsupported,
    ///     accumulation: SupportLevel::Unsupported,
    /// }];
    /// impl TensorBackendCapability for Backend {
    ///     fn backend_id(&self) -> BackendId { BackendId::Cpu }
    ///     fn capabilities(&self) -> &'static [OperationCapability] { ENTRIES }
    /// }
    ///
    /// let entry = Backend
    ///     .capability(CapabilityQuery::new(PrimitiveOpKind::Mul, DType::I64))
    ///     .unwrap();
    /// assert_eq!(entry.result, SupportLevel::Native);
    /// ```
    #[must_use]
    fn capability(&self, query: CapabilityQuery) -> Option<OperationCapability> {
        self.capabilities().iter().copied().find(|entry| {
            entry.backend == self.backend_id() && entry.op == query.op && entry.dtype == query.dtype
        })
    }

    /// Require support for one operation/dtype/axis, returning a structured
    /// unsupported error otherwise.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_core_ops::PrimitiveOpKind;
    /// use tenferro_tensor::{
    ///     BackendId, CapabilityAxis, CapabilityQuery, DType, Error, OperationCapability,
    ///     SupportLevel, TensorBackendCapability,
    /// };
    ///
    /// struct Backend;
    /// const ENTRIES: &[OperationCapability] = &[OperationCapability {
    ///     backend: BackendId::Cuda,
    ///     op: PrimitiveOpKind::Neg,
    ///     dtype: DType::I32,
    ///     output_dtype: DType::I32,
    ///     result: SupportLevel::Unsupported,
    ///     read_inputs: SupportLevel::Unsupported,
    ///     write_output: SupportLevel::Unsupported,
    ///     strided_output: SupportLevel::Unsupported,
    ///     accumulation: SupportLevel::Unsupported,
    /// }];
    /// impl TensorBackendCapability for Backend {
    ///     fn backend_id(&self) -> BackendId { BackendId::Cuda }
    ///     fn capabilities(&self) -> &'static [OperationCapability] { ENTRIES }
    /// }
    ///
    /// let err = Backend
    ///     .require_capability(
    ///         CapabilityQuery::new(PrimitiveOpKind::Neg, DType::I32),
    ///         CapabilityAxis::OwnedResult,
    ///     )
    ///     .unwrap_err();
    /// assert!(matches!(err, Error::UnsupportedDType { op: "neg", dtype: DType::I32, .. }));
    /// ```
    /// # Errors
    ///
    /// Returns [`crate::Error::UnsupportedDType`] when the backend capability
    /// table does not support the requested operation and dtype.
    fn require_capability(
        &self,
        query: CapabilityQuery,
        axis: CapabilityAxis,
    ) -> crate::Result<OperationCapability> {
        let entry = self.capability(query).ok_or_else(|| {
            crate::Error::unsupported_dtype(
                descriptor(query.op).name,
                query.dtype,
                format!(
                    "backend {} does not support this operation/dtype",
                    self.backend_id()
                ),
            )
        })?;
        if entry.axis(axis).is_supported() {
            Ok(entry)
        } else {
            Err(crate::Error::unsupported_dtype(
                descriptor(query.op).name,
                query.dtype,
                format!(
                    "backend {} does not support this operation/dtype",
                    self.backend_id()
                ),
            ))
        }
    }
}

/// Return the output dtype allowed by the core op catalog policy for a unary
/// dtype representative.
///
/// `None` means the catalog policy does not admit the queried dtype. Backend
/// descriptors add implementation support on top of this semantic policy.
///
/// # Examples
///
/// ```rust
/// use tenferro_core_ops::PrimitiveOpKind;
/// use tenferro_tensor::{capability_output_dtype, DType};
///
/// assert_eq!(
///     capability_output_dtype(PrimitiveOpKind::Abs, DType::C64),
///     Some(DType::F64)
/// );
/// assert_eq!(
///     capability_output_dtype(PrimitiveOpKind::Pow, DType::I32),
///     Some(DType::I32)
/// );
/// ```
#[must_use]
pub fn capability_output_dtype(op: PrimitiveOpKind, dtype: DType) -> Option<DType> {
    let policy = descriptor(op).dtype_policy;
    match policy {
        DTypePolicy::SameAny => Some(dtype),
        DTypePolicy::SameNumeric => numeric_dtype(dtype).then_some(dtype),
        DTypePolicy::SameFloat => float_dtype(dtype).then_some(dtype),
        DTypePolicy::AbsToReal => match dtype {
            DType::F32 => Some(DType::F32),
            DType::F64 => Some(DType::F64),
            DType::I32 => Some(DType::I32),
            DType::I64 => Some(DType::I64),
            DType::C32 => Some(DType::F32),
            DType::C64 => Some(DType::F64),
            DType::Bool => None,
        },
        DTypePolicy::SameFloatOrComplex => float_or_complex_dtype(dtype).then_some(dtype),
        DTypePolicy::CompareToBool => comparable_dtype(dtype).then_some(DType::Bool),
        DTypePolicy::BoolSelect => Some(dtype),
        DTypePolicy::Convert | DTypePolicy::Shape | DTypePolicy::Constant => Some(dtype),
    }
}

const fn numeric_dtype(dtype: DType) -> bool {
    matches!(
        dtype,
        DType::F32 | DType::F64 | DType::I32 | DType::I64 | DType::C32 | DType::C64
    )
}

const fn float_dtype(dtype: DType) -> bool {
    matches!(dtype, DType::F32 | DType::F64)
}

const fn float_or_complex_dtype(dtype: DType) -> bool {
    matches!(dtype, DType::F32 | DType::F64 | DType::C32 | DType::C64)
}

const fn comparable_dtype(dtype: DType) -> bool {
    matches!(
        dtype,
        DType::F32 | DType::F64 | DType::I32 | DType::I64 | DType::Bool
    )
}