tenflowers-core 0.1.1

Core tensor operations and execution engine for TenfloweRS
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
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
use crate::{DType, Device};
use thiserror::Error;

/// Enhanced error handling with contextual information and recovery strategies
#[derive(Error, Debug, Clone)]
pub enum TensorError {
    #[error("Shape mismatch in operation '{operation}': expected {expected}, got {got}")]
    ShapeMismatch {
        operation: String,
        expected: String,
        got: String,
        context: Option<ErrorContext>,
    },

    #[error("Incompatible devices in operation '{operation}': {device1} and {device2}")]
    DeviceMismatch {
        operation: String,
        device1: String,
        device2: String,
        context: Option<ErrorContext>,
    },

    #[error("Operation '{operation}' not supported on device: {device}")]
    UnsupportedDevice {
        operation: String,
        device: String,
        fallback_available: bool,
        context: Option<ErrorContext>,
    },

    #[error("Invalid shape in operation '{operation}': {reason}")]
    InvalidShape {
        operation: String,
        reason: String,
        shape: Option<Vec<usize>>,
        context: Option<ErrorContext>,
    },

    #[error("Invalid axis {axis} in operation '{operation}' for tensor with {ndim} dimensions")]
    InvalidAxis {
        operation: String,
        axis: i32,
        ndim: usize,
        context: Option<ErrorContext>,
    },

    #[error("Gradient computation not enabled for tensor in operation '{operation}'")]
    GradientNotEnabled {
        operation: String,
        suggestion: String,
        context: Option<ErrorContext>,
    },

    #[error("Invalid argument in operation '{operation}': {reason}")]
    InvalidArgument {
        operation: String,
        reason: String,
        context: Option<ErrorContext>,
    },

    #[error("Memory allocation failed in operation '{operation}': {details}")]
    AllocationError {
        operation: String,
        details: String,
        requested_bytes: Option<usize>,
        available_bytes: Option<usize>,
        context: Option<ErrorContext>,
    },

    #[error("Operation '{operation}' not supported: {reason}")]
    UnsupportedOperation {
        operation: String,
        reason: String,
        alternatives: Vec<String>,
        context: Option<ErrorContext>,
    },

    #[error("GPU error in operation '{operation}': {details}")]
    #[cfg(feature = "gpu")]
    GpuError {
        operation: String,
        details: String,
        gpu_id: Option<usize>,
        fallback_attempted: bool,
        context: Option<ErrorContext>,
    },

    #[error("Device error in operation '{operation}': {details}")]
    DeviceError {
        operation: String,
        details: String,
        device: String,
        context: Option<ErrorContext>,
    },

    #[error("Compute error in operation '{operation}': {details}")]
    ComputeError {
        operation: String,
        details: String,
        retry_possible: bool,
        context: Option<ErrorContext>,
    },

    #[error("BLAS error in operation '{operation}': {details}")]
    #[cfg(feature = "blas")]
    BlasError {
        operation: String,
        details: String,
        context: Option<ErrorContext>,
    },

    #[error("Serialization error in operation '{operation}': {details}")]
    SerializationError {
        operation: String,
        details: String,
        context: Option<ErrorContext>,
    },

    #[error("Operation '{operation}' not implemented: {details}")]
    NotImplemented {
        operation: String,
        details: String,
        planned_version: Option<String>,
        context: Option<ErrorContext>,
    },

    #[error("Invalid operation '{operation}': {reason}")]
    InvalidOperation {
        operation: String,
        reason: String,
        context: Option<ErrorContext>,
    },

    #[error("Benchmark error in '{operation}': {details}")]
    BenchmarkError {
        operation: String,
        details: String,
        context: Option<ErrorContext>,
    },

    #[error("IO error in operation '{operation}': {details}")]
    IoError {
        operation: String,
        details: String,
        path: Option<String>,
        context: Option<ErrorContext>,
    },

    #[error("Numerical error in operation '{operation}': {details}")]
    NumericalError {
        operation: String,
        details: String,
        suggestions: Vec<String>,
        context: Option<ErrorContext>,
    },

    #[error("Resource exhaustion in operation '{operation}': {resource}")]
    ResourceExhausted {
        operation: String,
        resource: String,
        current_usage: Option<usize>,
        limit: Option<usize>,
        context: Option<ErrorContext>,
    },

    #[error("Timeout in operation '{operation}' after {duration_ms}ms")]
    Timeout {
        operation: String,
        duration_ms: u64,
        context: Option<ErrorContext>,
    },

    #[error("Cache operation failed in '{operation}': {details}")]
    CacheError {
        operation: String,
        details: String,
        recoverable: bool,
        context: Option<ErrorContext>,
    },

    #[error("Other error in operation '{operation}': {details}")]
    Other {
        operation: String,
        details: String,
        context: Option<ErrorContext>,
    },
}

/// Additional context information for errors
#[derive(Debug, Clone)]
pub struct ErrorContext {
    /// Input tensor shapes
    pub input_shapes: Vec<Vec<usize>>,
    /// Input tensor devices
    pub input_devices: Vec<Device>,
    /// Input tensor data types
    pub input_dtypes: Vec<DType>,
    /// Output shape (if applicable)
    pub output_shape: Option<Vec<usize>>,
    /// Thread ID where error occurred
    pub thread_id: String,
    /// Stack trace (if available)
    pub stack_trace: Option<String>,
    /// Additional metadata
    pub metadata: std::collections::HashMap<String, String>,
}

/// Recovery strategy for handling errors
#[derive(Debug, Clone)]
pub enum RecoveryStrategy {
    /// No recovery possible
    None,
    /// Fallback to CPU execution
    FallbackToCpu,
    /// Retry with different parameters
    RetryWithParams(std::collections::HashMap<String, String>),
    /// Use alternative algorithm
    UseAlternative(String),
    /// Reduce precision
    ReducePrecision,
    /// Free memory and retry
    FreeMemoryAndRetry,
}

impl ErrorContext {
    /// Create a new error context
    pub fn new() -> Self {
        Self {
            input_shapes: Vec::new(),
            input_devices: Vec::new(),
            input_dtypes: Vec::new(),
            output_shape: None,
            thread_id: format!("{:?}", std::thread::current().id()),
            stack_trace: None,
            metadata: std::collections::HashMap::new(),
        }
    }

    /// Add input tensor information
    pub fn with_input_tensor(mut self, shape: &[usize], device: Device, dtype: DType) -> Self {
        self.input_shapes.push(shape.to_vec());
        self.input_devices.push(device);
        self.input_dtypes.push(dtype);
        self
    }

    /// Add output shape information
    pub fn with_output_shape(mut self, shape: &[usize]) -> Self {
        self.output_shape = Some(shape.to_vec());
        self
    }

    /// Add metadata
    pub fn with_metadata(mut self, key: String, value: String) -> Self {
        self.metadata.insert(key, value);
        self
    }
}

impl Default for ErrorContext {
    fn default() -> Self {
        Self::new()
    }
}

impl TensorError {
    /// Create a shape mismatch error with context
    pub fn shape_mismatch(operation: &str, expected: &str, got: &str) -> Self {
        Self::ShapeMismatch {
            operation: operation.to_string(),
            expected: expected.to_string(),
            got: got.to_string(),
            context: None,
        }
    }

    /// Create a device mismatch error with context
    pub fn device_mismatch(operation: &str, device1: &str, device2: &str) -> Self {
        Self::DeviceMismatch {
            operation: operation.to_string(),
            device1: device1.to_string(),
            device2: device2.to_string(),
            context: None,
        }
    }

    /// Create an unsupported device error with fallback information
    pub fn unsupported_device(operation: &str, device: &str, fallback_available: bool) -> Self {
        Self::UnsupportedDevice {
            operation: operation.to_string(),
            device: device.to_string(),
            fallback_available,
            context: None,
        }
    }

    /// Create a GPU error with fallback information
    #[cfg(feature = "gpu")]
    pub fn gpu_error(
        operation: &str,
        details: &str,
        gpu_id: Option<usize>,
        fallback_attempted: bool,
    ) -> Self {
        Self::GpuError {
            operation: operation.to_string(),
            details: details.to_string(),
            gpu_id,
            fallback_attempted,
            context: None,
        }
    }

    /// Create an allocation error with memory information
    pub fn allocation_error(
        operation: &str,
        details: &str,
        requested: Option<usize>,
        available: Option<usize>,
    ) -> Self {
        Self::AllocationError {
            operation: operation.to_string(),
            details: details.to_string(),
            requested_bytes: requested,
            available_bytes: available,
            context: None,
        }
    }

    /// Create a numerical error with suggestions
    pub fn numerical_error(operation: &str, details: &str, suggestions: Vec<String>) -> Self {
        Self::NumericalError {
            operation: operation.to_string(),
            details: details.to_string(),
            suggestions,
            context: None,
        }
    }

    /// Create an invalid argument error (for backward compatibility)
    pub fn invalid_argument(reason: String) -> Self {
        Self::InvalidArgument {
            operation: "unknown".to_string(),
            reason,
            context: None,
        }
    }

    /// Create an invalid argument error with operation context
    pub fn invalid_argument_op(operation: &str, reason: &str) -> Self {
        Self::InvalidArgument {
            operation: operation.to_string(),
            reason: reason.to_string(),
            context: None,
        }
    }

    /// Create a generic "other" error (for backward compatibility)
    pub fn other(details: String) -> Self {
        Self::Other {
            operation: "unknown".to_string(),
            details,
            context: None,
        }
    }

    /// Create a generic "other" error with operation context
    pub fn other_op(operation: &str, details: &str) -> Self {
        Self::Other {
            operation: operation.to_string(),
            details: details.to_string(),
            context: None,
        }
    }

    /// Create an allocation error (for backward compatibility)
    pub fn allocation_error_simple(details: String) -> Self {
        Self::AllocationError {
            operation: "unknown".to_string(),
            details,
            requested_bytes: None,
            available_bytes: None,
            context: None,
        }
    }

    /// Create an unsupported operation error (for backward compatibility)
    pub fn unsupported_operation_simple(reason: String) -> Self {
        Self::UnsupportedOperation {
            operation: "unknown".to_string(),
            reason,
            alternatives: Vec::new(),
            context: None,
        }
    }

    /// Create an invalid shape error with operation context
    pub fn invalid_shape(operation: &str, expected: &str, got: &str) -> Self {
        Self::InvalidShape {
            operation: operation.to_string(),
            reason: format!("Expected {}, got {}", expected, got),
            shape: None,
            context: None,
        }
    }

    /// Create an invalid shape error (for backward compatibility)
    pub fn invalid_shape_simple(reason: String) -> Self {
        Self::InvalidShape {
            operation: "unknown".to_string(),
            reason,
            shape: None,
            context: None,
        }
    }

    /// Create a device error (for backward compatibility)
    pub fn device_error_simple(details: String) -> Self {
        Self::DeviceError {
            operation: "unknown".to_string(),
            details,
            device: "unknown".to_string(),
            context: None,
        }
    }

    /// Create a compute error (for backward compatibility)
    pub fn compute_error_simple(details: String) -> Self {
        Self::ComputeError {
            operation: "unknown".to_string(),
            details,
            retry_possible: false,
            context: None,
        }
    }

    /// Create a serialization error (for backward compatibility)
    pub fn serialization_error_simple(details: String) -> Self {
        Self::SerializationError {
            operation: "unknown".to_string(),
            details,
            context: None,
        }
    }

    /// Create a not implemented error (for backward compatibility)
    pub fn not_implemented_simple(details: String) -> Self {
        Self::NotImplemented {
            operation: "unknown".to_string(),
            details,
            planned_version: None,
            context: None,
        }
    }

    /// Create an invalid operation error (for backward compatibility)
    pub fn invalid_operation_simple(reason: String) -> Self {
        Self::InvalidOperation {
            operation: "unknown".to_string(),
            reason,
            context: None,
        }
    }

    /// Create a benchmark error (for backward compatibility)
    pub fn benchmark_error_simple(details: String) -> Self {
        Self::BenchmarkError {
            operation: "unknown".to_string(),
            details,
            context: None,
        }
    }

    /// Create an IO error (for backward compatibility)
    pub fn io_error_simple(details: String) -> Self {
        Self::IoError {
            operation: "unknown".to_string(),
            details,
            path: None,
            context: None,
        }
    }

    /// Create a resource exhausted error (for backward compatibility)
    pub fn resource_exhausted_simple(resource: String) -> Self {
        Self::ResourceExhausted {
            operation: "unknown".to_string(),
            resource,
            current_usage: None,
            limit: None,
            context: None,
        }
    }

    /// Create a timeout error (for backward compatibility)
    pub fn timeout_simple(duration_ms: u64) -> Self {
        Self::Timeout {
            operation: "unknown".to_string(),
            duration_ms,
            context: None,
        }
    }

    /// Add context to an existing error
    pub fn with_context(mut self, context: ErrorContext) -> Self {
        match &mut self {
            Self::ShapeMismatch { context: ctx, .. } => *ctx = Some(context),
            Self::DeviceMismatch { context: ctx, .. } => *ctx = Some(context),
            Self::UnsupportedDevice { context: ctx, .. } => *ctx = Some(context),
            Self::InvalidShape { context: ctx, .. } => *ctx = Some(context),
            Self::InvalidAxis { context: ctx, .. } => *ctx = Some(context),
            Self::GradientNotEnabled { context: ctx, .. } => *ctx = Some(context),
            Self::InvalidArgument { context: ctx, .. } => *ctx = Some(context),
            Self::AllocationError { context: ctx, .. } => *ctx = Some(context),
            Self::UnsupportedOperation { context: ctx, .. } => *ctx = Some(context),
            #[cfg(feature = "gpu")]
            Self::GpuError { context: ctx, .. } => *ctx = Some(context),
            Self::DeviceError { context: ctx, .. } => *ctx = Some(context),
            Self::ComputeError { context: ctx, .. } => *ctx = Some(context),
            #[cfg(feature = "blas")]
            Self::BlasError { context: ctx, .. } => *ctx = Some(context),
            Self::SerializationError { context: ctx, .. } => *ctx = Some(context),
            Self::NotImplemented { context: ctx, .. } => *ctx = Some(context),
            Self::InvalidOperation { context: ctx, .. } => *ctx = Some(context),
            Self::BenchmarkError { context: ctx, .. } => *ctx = Some(context),
            Self::IoError { context: ctx, .. } => *ctx = Some(context),
            Self::NumericalError { context: ctx, .. } => *ctx = Some(context),
            Self::ResourceExhausted { context: ctx, .. } => *ctx = Some(context),
            Self::Timeout { context: ctx, .. } => *ctx = Some(context),
            Self::CacheError { context: ctx, .. } => *ctx = Some(context),
            Self::Other { context: ctx, .. } => *ctx = Some(context),
        }
        self
    }

    /// Get the operation name for this error
    pub fn operation(&self) -> &str {
        match self {
            Self::ShapeMismatch { operation, .. } => operation,
            Self::DeviceMismatch { operation, .. } => operation,
            Self::UnsupportedDevice { operation, .. } => operation,
            Self::InvalidShape { operation, .. } => operation,
            Self::InvalidAxis { operation, .. } => operation,
            Self::GradientNotEnabled { operation, .. } => operation,
            Self::InvalidArgument { operation, .. } => operation,
            Self::AllocationError { operation, .. } => operation,
            Self::UnsupportedOperation { operation, .. } => operation,
            #[cfg(feature = "gpu")]
            Self::GpuError { operation, .. } => operation,
            Self::DeviceError { operation, .. } => operation,
            Self::ComputeError { operation, .. } => operation,
            #[cfg(feature = "blas")]
            Self::BlasError { operation, .. } => operation,
            Self::SerializationError { operation, .. } => operation,
            Self::NotImplemented { operation, .. } => operation,
            Self::InvalidOperation { operation, .. } => operation,
            Self::BenchmarkError { operation, .. } => operation,
            Self::IoError { operation, .. } => operation,
            Self::NumericalError { operation, .. } => operation,
            Self::ResourceExhausted { operation, .. } => operation,
            Self::Timeout { operation, .. } => operation,
            Self::CacheError { operation, .. } => operation,
            Self::Other { operation, .. } => operation,
        }
    }

    /// Check if this error supports fallback recovery
    pub fn supports_fallback(&self) -> bool {
        match self {
            Self::UnsupportedDevice {
                fallback_available, ..
            } => *fallback_available,
            #[cfg(feature = "gpu")]
            Self::GpuError { .. } => true,
            Self::AllocationError { .. } => true,
            Self::ComputeError { retry_possible, .. } => *retry_possible,
            _ => false,
        }
    }

    /// Get suggested recovery strategy
    pub fn recovery_strategy(&self) -> RecoveryStrategy {
        match self {
            Self::UnsupportedDevice {
                fallback_available: true,
                ..
            } => RecoveryStrategy::FallbackToCpu,
            #[cfg(feature = "gpu")]
            Self::GpuError {
                fallback_attempted: false,
                ..
            } => RecoveryStrategy::FallbackToCpu,
            Self::AllocationError { .. } => RecoveryStrategy::FreeMemoryAndRetry,
            Self::ComputeError {
                retry_possible: true,
                ..
            } => {
                let mut params = std::collections::HashMap::new();
                params.insert("reduce_precision".to_string(), "true".to_string());
                RecoveryStrategy::RetryWithParams(params)
            }
            Self::NumericalError { .. } => RecoveryStrategy::ReducePrecision,
            _ => RecoveryStrategy::None,
        }
    }
}

/// Trait for automatic error recovery
pub trait ErrorRecovery<T> {
    /// Attempt to recover from error using suggested strategy
    fn recover_with_strategy(self, strategy: RecoveryStrategy) -> Result<T>;

    /// Attempt automatic recovery if possible
    fn auto_recover(self) -> Result<T>;
}

impl<T> ErrorRecovery<T> for Result<T> {
    fn recover_with_strategy(self, _strategy: RecoveryStrategy) -> Result<T> {
        // For now, just return the original result
        // In a full implementation, this would attempt recovery based on the strategy
        self
    }

    fn auto_recover(self) -> Result<T> {
        match &self {
            Err(error) if error.supports_fallback() => {
                let strategy = error.recovery_strategy();
                self.recover_with_strategy(strategy)
            }
            _ => self,
        }
    }
}

pub type Result<T> = std::result::Result<T, TensorError>;

/// Convert from scirs2_core::ndarray::ShapeError to TensorError
impl From<scirs2_core::ndarray::ShapeError> for TensorError {
    fn from(err: scirs2_core::ndarray::ShapeError) -> Self {
        Self::InvalidShape {
            operation: "tensor_creation".to_string(),
            reason: format!("Shape error: {err}"),
            shape: None,
            context: None,
        }
    }
}

/// Convert from std::fmt::Error to TensorError
impl From<std::fmt::Error> for TensorError {
    fn from(err: std::fmt::Error) -> Self {
        Self::Other {
            operation: "formatting".to_string(),
            details: format!("Formatting error: {err}"),
            context: None,
        }
    }
}