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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
//! Runtime error types for tensor execution.
//!
//! # Examples
//!
//! ```rust
//! let error = tenferro_tensor::Error::shape_mismatch("add", [2], [3]);
//! assert!(matches!(
//!     error,
//!     tenferro_tensor::Error::Validation { op: "add", .. }
//! ));
//! ```

use std::error::Error as StdError;

use tenferro_tensor_core::{ErrorKind, ValidationError};

/// Boxed source used for backend and extension failures whose concrete type is
/// owned by another crate or a vendor API.
pub type BoxError = Box<dyn StdError + Send + Sync + 'static>;

/// Runtime failures produced by tensor execution backends and helpers.
///
/// Validation failures retain the shared tensor-core payload as a typed source.
/// Backend and extension failures retain opaque typed sources when one exists;
/// text-only vendor failures use [`Error::BackendFailure`].
///
/// # Examples
///
/// ```rust
/// let error = tenferro_tensor::Error::rank_mismatch("reshape", 2, 1);
/// assert!(matches!(
///     error,
///     tenferro_tensor::Error::Validation { op: "reshape", .. }
/// ));
/// ```
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
    #[error("{op}: {source}")]
    Validation {
        op: &'static str,
        #[source]
        source: ValidationError,
    },
    #[error("{op}: unsupported dtype conversion from {from:?} to {to:?}: {message}")]
    UnsupportedDTypeConversion {
        op: &'static str,
        from: crate::DType,
        to: crate::DType,
        message: String,
    },
    #[error("{op}: unsupported dtype {dtype:?}: {message}")]
    UnsupportedDType {
        op: &'static str,
        dtype: crate::DType,
        message: String,
    },
    #[error("{op}: unsupported operation: {message}")]
    Unsupported { op: &'static str, message: String },
    #[error("{op}: backend failure: {message}")]
    BackendFailure { op: &'static str, message: String },
    #[error("{op}: backend failure: {source}")]
    BackendSource {
        op: &'static str,
        #[source]
        source: BoxError,
    },
    #[error("{op}: I/O failure: {source}")]
    IoSource {
        op: &'static str,
        #[source]
        source: BoxError,
    },
    #[error("{op}: runtime state failure: {message}")]
    RuntimeState { op: &'static str, message: String },
    #[error("{op}: runtime state failure: {source}")]
    RuntimeStateSource {
        op: &'static str,
        #[source]
        source: BoxError,
    },
    #[error("{op}: host access failed: {source}")]
    HostAccess {
        op: &'static str,
        #[source]
        source: crate::HostAccessError,
    },
    #[error("{op}: extension {family} failed: {source}")]
    Extension {
        op: &'static str,
        family: &'static str,
        kind: ErrorKind,
        #[source]
        source: BoxError,
    },
    #[error("missing runtime value for slot {slot}")]
    MissingValue { slot: usize },
    #[error("internal tensor error: {0}")]
    Internal(String),
}

/// Owns the original tensor when a consuming representation reinterpretation
/// cannot publish its checked descriptor.
///
/// Reinterpretation never falls back to an allocation or a copy.  Call
/// [`Self::into_owner`] to recover the unchanged input and [`Self::error`] to
/// inspect the typed failure.
///
/// # Examples
///
/// ```
/// use tenferro_tensor::TypedTensor;
///
/// let tensor = TypedTensor::<f32>::from_vec_col_major(vec![1], vec![1.0])?;
/// let Err(failure) = tensor.into_complex() else { return Ok(()); };
/// assert!(!failure.error().to_string().is_empty());
/// # Ok::<(), tenferro_tensor::Error>(())
/// ```
#[derive(Debug)]
pub struct ReinterpretError<T> {
    owner: Box<T>,
    error: Error,
}

impl<T> ReinterpretError<T> {
    pub(crate) fn new(owner: T, error: Error) -> Self {
        Self {
            owner: Box::new(owner),
            error,
        }
    }

    /// Recover the unchanged original owner.
    ///
    /// # Examples
    ///
    /// ```
    /// use tenferro_tensor::TypedTensor;
    ///
    /// let tensor = TypedTensor::<f32>::from_vec_col_major(vec![1], vec![1.0])?;
    /// let Err(failure) = tensor.into_complex() else { return Ok(()); };
    /// let _owner = failure.into_owner();
    /// # Ok::<(), tenferro_tensor::Error>(())
    /// ```
    pub fn into_owner(self) -> T {
        *self.owner
    }

    /// Borrow the typed failure without consuming the owner.
    ///
    /// # Examples
    ///
    /// ```
    /// use tenferro_tensor::TypedTensor;
    ///
    /// let tensor = TypedTensor::<f32>::from_vec_col_major(vec![1], vec![1.0])?;
    /// let Err(failure) = tensor.into_complex() else { return Ok(()); };
    /// assert!(!failure.error().to_string().is_empty());
    /// # Ok::<(), tenferro_tensor::Error>(())
    /// ```
    pub fn error(&self) -> &Error {
        &self.error
    }

    pub(crate) fn into_parts(self) -> (T, Error) {
        (*self.owner, self.error)
    }
}

impl<T: std::fmt::Debug> std::fmt::Display for ReinterpretError<T> {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(formatter, "tensor reinterpretation failed: {}", self.error)
    }
}

impl<T: std::fmt::Debug + 'static> std::error::Error for ReinterpretError<T> {}

impl Error {
    /// Construct an incompatible-shapes validation error.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_tensor::Error;
    ///
    /// let error = Error::shape_mismatch("add", [2, 3], [2, 4]);
    /// assert!(matches!(error, Error::Validation { .. }));
    /// ```
    pub fn shape_mismatch(
        op: &'static str,
        lhs: impl Into<Vec<usize>>,
        rhs: impl Into<Vec<usize>>,
    ) -> Self {
        Self::validation(
            op,
            tenferro_tensor_core::ShapeMismatch::IncompatibleShapes {
                lhs: tenferro_tensor_core::ShapeVec::from_vec(lhs.into()),
                rhs: tenferro_tensor_core::ShapeVec::from_vec(rhs.into()),
            }
            .into(),
        )
    }

    /// Construct a rank-mismatch validation error.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_tensor::Error;
    ///
    /// let error = Error::rank_mismatch("transpose", 2, 3);
    /// assert!(matches!(error, Error::Validation { .. }));
    /// ```
    pub fn rank_mismatch(op: &'static str, expected: usize, actual: usize) -> Self {
        Self::validation(op, ValidationError::RankMismatch { expected, actual })
    }

    /// Construct an axis-out-of-bounds validation error.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_tensor::Error;
    ///
    /// let error = Error::axis_out_of_bounds("sum", 2, 2);
    /// assert!(matches!(error, Error::Validation { .. }));
    /// ```
    pub fn axis_out_of_bounds(op: &'static str, axis: usize, rank: usize) -> Self {
        Self::validation(op, ValidationError::AxisOutOfBounds { axis, rank })
    }

    /// Construct a duplicate-axis validation error.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_tensor::Error;
    ///
    /// let error = Error::duplicate_axis("transpose", 1, "permutation");
    /// assert!(matches!(error, Error::Validation { .. }));
    /// ```
    pub fn duplicate_axis(op: &'static str, axis: usize, role: &'static str) -> Self {
        Self::validation(op, ValidationError::DuplicateAxis { axis, role })
    }

    /// Construct a dtype-mismatch validation error.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_tensor::{DType, Error};
    ///
    /// let error = Error::dtype_mismatch("add", DType::F32, DType::F64);
    /// assert!(matches!(error, Error::Validation { .. }));
    /// ```
    pub fn dtype_mismatch(op: &'static str, expected: crate::DType, actual: crate::DType) -> Self {
        Self::validation(
            op,
            ValidationError::DTypeMismatch {
                expected: crate::core_dtype(expected),
                actual: crate::core_dtype(actual),
            },
        )
    }

    /// Wrap shared tensor validation with the operation that requested it.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_tensor::{Error, ValidationError};
    ///
    /// let error = Error::validation(
    ///     "transpose",
    ///     ValidationError::AxisOutOfBounds { axis: 2, rank: 2 },
    /// );
    /// assert!(matches!(error, Error::Validation { op: "transpose", .. }));
    /// ```
    pub fn validation(op: &'static str, source: ValidationError) -> Self {
        Self::Validation { op, source }
    }

    /// Construct a structured invalid-argument validation error.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_tensor::{Error, ErrorKind, ValidationKind};
    ///
    /// let error = Error::invalid_argument("slice", "step", "must be non-zero");
    /// assert_eq!(error.kind(), ErrorKind::Validation(ValidationKind::InvalidArgument));
    /// ```
    pub fn invalid_argument(
        op: &'static str,
        argument: &'static str,
        message: impl Into<String>,
    ) -> Self {
        Self::validation(
            op,
            ValidationError::InvalidArgument {
                argument,
                message: message.into(),
            },
        )
    }

    /// Construct an unsupported dtype conversion error.
    ///
    /// # Examples
    ///
    /// ```rust
    /// let error = tenferro_tensor::Error::unsupported_dtype_conversion(
    ///     "convert",
    ///     tenferro_tensor::DType::F64,
    ///     tenferro_tensor::DType::I32,
    ///     "lossy conversion is disabled",
    /// );
    /// assert!(matches!(
    ///     error,
    ///     tenferro_tensor::Error::UnsupportedDTypeConversion { .. }
    /// ));
    /// ```
    pub fn unsupported_dtype_conversion(
        op: &'static str,
        from: crate::DType,
        to: crate::DType,
        message: impl Into<String>,
    ) -> Self {
        Self::UnsupportedDTypeConversion {
            op,
            from,
            to,
            message: message.into(),
        }
    }

    /// Construct an operation-level unsupported-dtype error.
    ///
    /// This is for an operation that cannot run for the supplied dtype. It is
    /// deliberately distinct from [`Error::unsupported_dtype_conversion`],
    /// which is reserved for an actual from-dtype to to-dtype conversion.
    ///
    /// # Examples
    ///
    /// ```rust
    /// let error = tenferro_tensor::Error::unsupported_dtype(
    ///     "exp",
    ///     tenferro_tensor::DType::I64,
    ///     "integer exponentials are not implemented",
    /// );
    /// assert!(matches!(
    ///     error,
    ///     tenferro_tensor::Error::UnsupportedDType {
    ///         op: "exp",
    ///         dtype: tenferro_tensor::DType::I64,
    ///         ..
    ///     }
    /// ));
    /// ```
    pub fn unsupported_dtype(
        op: &'static str,
        dtype: crate::DType,
        message: impl Into<String>,
    ) -> Self {
        Self::UnsupportedDType {
            op,
            dtype,
            message: message.into(),
        }
    }

    /// Construct a structured unsupported-operation error.
    ///
    /// Use this for an operation or execution surface that is not implemented
    /// by the selected backend. Dtype conversion failures use
    /// [`Error::unsupported_dtype_conversion`] instead, and operation-specific
    /// typed reasons should use [`Error::extension`] with `ErrorKind::Unsupported`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// let error = tenferro_tensor::Error::unsupported(
    ///     "full_piv_lu",
    ///     "backend has no implementation",
    /// );
    /// assert!(matches!(
    ///     error,
    ///     tenferro_tensor::Error::Unsupported { op: "full_piv_lu", .. }
    /// ));
    /// ```
    pub fn unsupported(op: &'static str, message: impl Into<String>) -> Self {
        Self::Unsupported {
            op,
            message: message.into(),
        }
    }

    /// Construct a text-only backend failure.
    ///
    /// Use [`Error::backend_source`] when a typed source is available.
    ///
    /// # Examples
    ///
    /// ```rust
    /// let error = tenferro_tensor::Error::backend_failure(
    ///     "matmul",
    ///     "backend rejected launch",
    /// );
    /// assert!(matches!(
    ///     error,
    ///     tenferro_tensor::Error::BackendFailure { op: "matmul", .. }
    /// ));
    /// ```
    pub fn backend_failure(op: &'static str, message: impl Into<String>) -> Self {
        Self::BackendFailure {
            op,
            message: message.into(),
        }
    }

    /// Construct a backend failure while preserving its typed source.
    ///
    /// # Examples
    ///
    /// ```rust
    /// let error = tenferro_tensor::Error::backend_source(
    ///     "load",
    ///     std::io::Error::other("read failed"),
    /// );
    /// assert!(std::error::Error::source(&error).is_some());
    /// ```
    pub fn backend_source<E>(op: &'static str, source: E) -> Self
    where
        E: StdError + Send + Sync + 'static,
    {
        Self::BackendSource {
            op,
            source: Box::new(source),
        }
    }

    /// Construct an I/O failure while preserving its typed source.
    ///
    /// I/O errors are intentionally separate from backend failures: callers
    /// can classify them as [`ErrorKind::Io`] without parsing a message.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_tensor::{Error, ErrorKind};
    ///
    /// let error = Error::io_source("load", std::io::Error::other("read failed"));
    /// assert_eq!(error.kind(), ErrorKind::Io);
    /// assert!(std::error::Error::source(&error).is_some());
    /// ```
    pub fn io_source<E>(op: &'static str, source: E) -> Self
    where
        E: StdError + Send + Sync + 'static,
    {
        Self::IoSource {
            op,
            source: Box::new(source),
        }
    }

    /// Construct a runtime-state failure when no typed source exists.
    ///
    /// Use this for missing, uninitialized, or invalid execution state. It is
    /// distinct from [`Error::backend_failure`], which is reserved for
    /// vendor/backend status text.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_tensor::{Error, ErrorKind};
    ///
    /// let error = Error::runtime_state("execute", "backend session is not initialized");
    /// assert_eq!(error.kind(), ErrorKind::RuntimeState);
    /// ```
    pub fn runtime_state(op: &'static str, message: impl Into<String>) -> Self {
        Self::RuntimeState {
            op,
            message: message.into(),
        }
    }

    /// Construct a runtime-state failure while preserving a typed source.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_tensor::{Error, ErrorKind};
    ///
    /// let error = Error::runtime_state_source(
    ///     "execute",
    ///     std::io::Error::other("executor lock poisoned"),
    /// );
    /// assert_eq!(error.kind(), ErrorKind::RuntimeState);
    /// assert!(std::error::Error::source(&error).is_some());
    /// ```
    pub fn runtime_state_source<E>(op: &'static str, source: E) -> Self
    where
        E: StdError + Send + Sync + 'static,
    {
        Self::RuntimeStateSource {
            op,
            source: Box::new(source),
        }
    }

    /// Construct an extension failure while preserving its typed source and
    /// coarse classification.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::error::Error as _;
    /// use tenferro_tensor::{Error, ErrorKind};
    ///
    /// let error = Error::extension(
    ///     "einsum",
    ///     "einsum",
    ///     ErrorKind::Internal,
    ///     std::io::Error::other("planner failed"),
    /// );
    /// assert!(error.source().is_some());
    /// ```
    pub fn extension<E>(op: &'static str, family: &'static str, kind: ErrorKind, source: E) -> Self
    where
        E: StdError + Send + Sync + 'static,
    {
        Self::Extension {
            op,
            family,
            kind,
            source: Box::new(source),
        }
    }

    /// Preserve a typed guarded-host-access failure.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_tensor::{Error, HostAccessError};
    ///
    /// let error = Error::host_access(
    ///     "map",
    ///     HostAccessError::Unsupported { backend: "opaque" },
    /// );
    /// assert!(matches!(error, Error::HostAccess { .. }));
    /// ```
    pub fn host_access(op: &'static str, source: crate::HostAccessError) -> Self {
        Self::HostAccess { op, source }
    }

    /// Return the stable coarse classification for this tensor failure.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_tensor::{Error, ErrorKind, ValidationError, ValidationKind};
    /// use tenferro_tensor::core::DType;
    ///
    /// let error = Error::validation(
    ///     "add",
    ///     ValidationError::DTypeMismatch {
    ///         expected: DType::F32,
    ///         actual: DType::F64,
    ///     },
    /// );
    /// assert_eq!(error.kind(), ErrorKind::Validation(ValidationKind::DTypeMismatch));
    /// ```
    pub fn kind(&self) -> ErrorKind {
        match self {
            Self::Validation { source, .. } => ErrorKind::Validation(source.kind()),
            Self::UnsupportedDTypeConversion { .. }
            | Self::UnsupportedDType { .. }
            | Self::Unsupported { .. } => ErrorKind::Unsupported,
            Self::BackendFailure { .. } | Self::BackendSource { .. } => ErrorKind::BackendFailure,
            Self::IoSource { .. } => ErrorKind::Io,
            Self::RuntimeState { .. }
            | Self::RuntimeStateSource { .. }
            | Self::HostAccess { .. } => ErrorKind::RuntimeState,
            Self::Extension { kind, .. } => *kind,
            Self::MissingValue { .. } => ErrorKind::RuntimeState,
            Self::Internal(_) => ErrorKind::Internal,
        }
    }
}

/// Result type alias for runtime tensor operations.
pub type Result<T> = std::result::Result<T, Error>;