trustformers-core 0.1.1

Core traits and utilities for TrustformeRS
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
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
use scirs2_core::ndarray::ShapeError;
use std::time::{Duration, Instant};
use thiserror::Error;

/// Error code for categorizing errors
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ErrorCode {
    /// Shape-related errors (E1000 series)
    E1001, // Shape mismatch
    E1002, // Dimension mismatch
    E1003, // Invalid shape

    /// Tensor operation errors (E2000 series)
    E2001, // Incompatible tensor types
    E2002, // Invalid tensor operation
    E2003, // Tensor data corruption

    /// Memory errors (E3000 series)
    E3001, // Out of memory
    E3002, // Memory allocation failed
    E3003, // Memory access violation

    /// Configuration errors (E4000 series)
    E4001, // Invalid configuration
    E4002, // Missing required parameter
    E4003, // Conflicting parameters

    /// Hardware errors (E5000 series)
    E5001, // GPU unavailable
    E5002, // Unsupported operation on hardware
    E5003, // Hardware capability insufficient

    /// Performance errors (E6000 series)
    E6001, // Operation timeout
    E6002, // Performance regression detected
    E6003, // Resource limit exceeded,

    /// General errors (E9000 series)
    E9001, // Unknown error
    E9002, // Not implemented
    E9003, // Internal error
}

impl ErrorCode {
    /// Get the numeric code as a string
    pub fn code(&self) -> &'static str {
        match self {
            ErrorCode::E1001 => "E1001",
            ErrorCode::E1002 => "E1002",
            ErrorCode::E1003 => "E1003",
            ErrorCode::E2001 => "E2001",
            ErrorCode::E2002 => "E2002",
            ErrorCode::E2003 => "E2003",
            ErrorCode::E3001 => "E3001",
            ErrorCode::E3002 => "E3002",
            ErrorCode::E3003 => "E3003",
            ErrorCode::E4001 => "E4001",
            ErrorCode::E4002 => "E4002",
            ErrorCode::E4003 => "E4003",
            ErrorCode::E5001 => "E5001",
            ErrorCode::E5002 => "E5002",
            ErrorCode::E5003 => "E5003",
            ErrorCode::E6001 => "E6001",
            ErrorCode::E6002 => "E6002",
            ErrorCode::E6003 => "E6003",
            ErrorCode::E9001 => "E9001",
            ErrorCode::E9002 => "E9002",
            ErrorCode::E9003 => "E9003",
        }
    }

    /// Get helpful suggestions for resolving the error
    pub fn suggestions(&self) -> Vec<&'static str> {
        match self {
            ErrorCode::E1001 => vec![
                "Check that tensor dimensions are compatible for the operation",
                "Use reshape() to adjust tensor dimensions",
                "Verify input data shapes match expected model dimensions",
            ],
            ErrorCode::E1002 => vec![
                "Ensure tensors have the same number of dimensions",
                "Use expand_dims() or squeeze() to adjust dimensionality",
                "Check documentation for required input dimensions",
            ],
            ErrorCode::E2001 => vec![
                "Convert tensors to compatible types using to_dtype()",
                "Check if operation supports mixed precision",
                "Use explicit casting before the operation",
            ],
            ErrorCode::E3001 => vec![
                "Reduce batch size or model size",
                "Enable gradient checkpointing",
                "Use model parallelism for large models",
                "Clear unused tensors from memory",
            ],
            ErrorCode::E4001 => vec![
                "Check configuration file syntax",
                "Verify all required parameters are present",
                "Consult documentation for valid parameter values",
            ],
            ErrorCode::E5001 => vec![
                "Install appropriate GPU drivers",
                "Check CUDA/ROCm installation",
                "Fall back to CPU execution",
                "Verify GPU is not being used by another process",
            ],
            ErrorCode::E6001 => vec![
                "Increase timeout duration",
                "Use smaller batch sizes",
                "Enable operation optimization",
                "Check for infinite loops in custom operations",
            ],
            _ => vec!["Check documentation for troubleshooting guide"],
        }
    }
}

/// Enhanced error context with profiling and recovery information
#[derive(Debug, Clone)]
pub struct ErrorContext {
    /// Error code for categorization
    pub code: ErrorCode,
    /// Timestamp when error occurred
    pub timestamp: Instant,
    /// Operation that caused the error
    pub operation: String,
    /// Stack trace or call context
    pub context: Vec<String>,
    /// Performance metrics when error occurred
    pub performance_info: Option<PerformanceInfo>,
    /// Suggested recovery actions
    pub recovery_suggestions: Vec<String>,
}

/// Performance information captured during error
#[derive(Debug, Clone, PartialEq)]
pub struct PerformanceInfo {
    /// Memory usage at time of error
    pub memory_usage_mb: Option<u64>,
    /// Operation duration before error
    pub operation_duration: Option<Duration>,
    /// GPU utilization if available
    pub gpu_utilization: Option<f32>,
    /// CPU usage percentage
    pub cpu_usage: Option<f32>,
}

impl ErrorContext {
    pub fn new(code: ErrorCode, operation: String) -> Self {
        Self {
            code,
            timestamp: Instant::now(),
            operation,
            context: Vec::new(),
            performance_info: None,
            recovery_suggestions: code.suggestions().iter().map(|s| s.to_string()).collect(),
        }
    }

    pub fn with_context(mut self, context: String) -> Self {
        self.context.push(context);
        self
    }

    pub fn with_performance(mut self, perf: PerformanceInfo) -> Self {
        self.performance_info = Some(perf);
        self
    }

    pub fn add_recovery_suggestion(mut self, suggestion: String) -> Self {
        self.recovery_suggestions.push(suggestion);
        self
    }
}

impl PartialEq for ErrorContext {
    fn eq(&self, other: &Self) -> bool {
        self.code == other.code
            && self.operation == other.operation
            && self.context == other.context
            && self.performance_info == other.performance_info
            && self.recovery_suggestions == other.recovery_suggestions
        // Note: We deliberately ignore timestamp for equality comparison
    }
}

#[deprecated(
    since = "0.4.0",
    note = "CoreError is deprecated. Use TrustformersError from crate::errors for better error handling with rich context and suggestions."
)]
#[derive(Error, Debug)]
pub enum CoreError {
    /// Enhanced shape mismatch error with detailed context
    #[error("Shape mismatch: expected {expected:?}, got {got:?}")]
    ShapeMismatch {
        expected: Vec<usize>,
        got: Vec<usize>,
        context: ErrorContext,
    },

    /// Enhanced dimension mismatch error
    #[error("Dimension mismatch")]
    DimensionMismatch { context: ErrorContext },

    /// Enhanced tensor operation error
    #[error("Tensor operation failed: {message}")]
    TensorOpError {
        message: String,
        context: ErrorContext,
    },

    /// Enhanced memory error
    #[error("Memory error: {message}")]
    MemoryError {
        message: String,
        context: ErrorContext,
    },

    /// Enhanced hardware error
    #[error("Hardware error: {message}")]
    HardwareError {
        message: String,
        context: ErrorContext,
    },

    /// Device not found error
    #[error("Device not found: {0}")]
    DeviceNotFound(String),

    /// Enhanced configuration error
    #[error("Configuration error: {message}")]
    ConfigError {
        message: String,
        context: ErrorContext,
    },

    /// Enhanced performance error
    #[error("Performance error: {message}")]
    PerformanceError {
        message: String,
        context: ErrorContext,
    },

    // Legacy errors for backward compatibility
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),

    #[error("Serialization error: {0}")]
    Serialization(#[from] serde_json::Error),

    #[error("Invalid configuration: {0}")]
    InvalidConfig(String),

    #[error("Weight loading error: {0}")]
    WeightLoadError(String),

    #[error("Model error: {0}")]
    ModelError(String),

    #[error("Shape error: {0}")]
    ShapeError(String),

    #[error("SafeTensors error: {0}")]
    SafeTensorsError(String),

    #[error("Invalid input: {0}")]
    InvalidInput(String),

    #[error("Tokenizer error: {0}")]
    TokenizerError(String),

    #[error("Image processing error: {0}")]
    ImageProcessingError(String),

    #[error("Runtime error: {0}")]
    RuntimeError(String),

    #[error("IO error: {0}")]
    IoError(String),

    // ConfigError is defined above as a structured error
    #[error("Computation error: {0}")]
    ComputationError(String),

    #[error("Serialization error: {0}")]
    SerializationError(String),

    #[error("Quantization error: {0}")]
    QuantizationError(String),

    #[error("Resource exhausted: {0}")]
    ResourceExhausted(String),

    #[error("Invalid argument: {0}")]
    InvalidArgument(String),

    #[error("Formatting error: {0}")]
    FormattingError(String),

    #[error("Not implemented: {0}")]
    NotImplemented(String),

    #[error("Lock error: {0}")]
    LockError(String),

    #[error("Plugin error: {0}")]
    PluginError(String),

    #[error("Timeout error: {0}")]
    Timeout(String),

    #[error("Network error: {0}")]
    NetworkError(String),

    #[error("File not found: {0}")]
    FileNotFound(String),

    #[error("Tensor not found: {0}")]
    TensorNotFound(String),

    #[error("Invalid format: {0}")]
    InvalidFormat(String),

    #[error("Invalid state: {0}")]
    InvalidState(String),

    #[error("Unsupported format: {0}")]
    UnsupportedFormat(String),

    #[error("Autodiff error: {0}")]
    AutodiffError(String),

    #[error("Invalid operation: {0}")]
    InvalidOperation(String),

    #[error("Internal error: {0}")]
    InternalError(String),

    #[error("Other error: {0}")]
    Other(#[from] anyhow::Error),
}

#[allow(deprecated)] // Backward compatibility implementation for CoreError
impl CoreError {
    /// Create a shape mismatch error with enhanced context
    pub fn shape_mismatch(expected: Vec<usize>, got: Vec<usize>, operation: &str) -> Self {
        let context = ErrorContext::new(ErrorCode::E1001, operation.to_string())
            .with_context(format!("Expected shape {:?}, got {:?}", expected, got));

        Self::ShapeMismatch {
            expected,
            got,
            context,
        }
    }

    /// Create a dimension mismatch error with enhanced context
    pub fn dimension_mismatch(operation: &str) -> Self {
        let context = ErrorContext::new(ErrorCode::E1002, operation.to_string());
        Self::DimensionMismatch { context }
    }

    /// Create a tensor operation error with enhanced context
    pub fn tensor_op_error(message: &str, operation: &str) -> Self {
        let context = ErrorContext::new(ErrorCode::E2002, operation.to_string());
        Self::TensorOpError {
            message: message.to_string(),
            context,
        }
    }

    /// Create a memory error with enhanced context
    pub fn memory_error(message: &str, operation: &str) -> Self {
        let context = ErrorContext::new(ErrorCode::E3001, operation.to_string());
        Self::MemoryError {
            message: message.to_string(),
            context,
        }
    }

    /// Create a hardware error with enhanced context
    pub fn hardware_error(message: &str, operation: &str) -> Self {
        let context = ErrorContext::new(ErrorCode::E5001, operation.to_string());
        Self::HardwareError {
            message: message.to_string(),
            context,
        }
    }

    /// Create a configuration error with enhanced context
    pub fn config_error(message: &str, operation: &str) -> Self {
        let context = ErrorContext::new(ErrorCode::E4001, operation.to_string());
        Self::ConfigError {
            message: message.to_string(),
            context,
        }
    }

    /// Create a performance error with enhanced context
    pub fn performance_error(message: &str, operation: &str) -> Self {
        let context = ErrorContext::new(ErrorCode::E6001, operation.to_string());
        Self::PerformanceError {
            message: message.to_string(),
            context,
        }
    }

    /// Get the error code if available
    pub fn error_code(&self) -> Option<ErrorCode> {
        match self {
            Self::ShapeMismatch { context, .. } => Some(context.code),
            Self::DimensionMismatch { context, .. } => Some(context.code),
            Self::TensorOpError { context, .. } => Some(context.code),
            Self::MemoryError { context, .. } => Some(context.code),
            Self::HardwareError { context, .. } => Some(context.code),
            Self::ConfigError { context, .. } => Some(context.code),
            Self::PerformanceError { context, .. } => Some(context.code),
            _ => None,
        }
    }

    /// Get recovery suggestions if available
    pub fn recovery_suggestions(&self) -> Option<&Vec<String>> {
        match self {
            Self::ShapeMismatch { context, .. } => Some(&context.recovery_suggestions),
            Self::DimensionMismatch { context, .. } => Some(&context.recovery_suggestions),
            Self::TensorOpError { context, .. } => Some(&context.recovery_suggestions),
            Self::MemoryError { context, .. } => Some(&context.recovery_suggestions),
            Self::HardwareError { context, .. } => Some(&context.recovery_suggestions),
            Self::ConfigError { context, .. } => Some(&context.recovery_suggestions),
            Self::PerformanceError { context, .. } => Some(&context.recovery_suggestions),
            _ => None,
        }
    }

    /// Get performance information if available
    pub fn performance_info(&self) -> Option<&PerformanceInfo> {
        match self {
            Self::ShapeMismatch { context, .. } => context.performance_info.as_ref(),
            Self::DimensionMismatch { context, .. } => context.performance_info.as_ref(),
            Self::TensorOpError { context, .. } => context.performance_info.as_ref(),
            Self::MemoryError { context, .. } => context.performance_info.as_ref(),
            Self::HardwareError { context, .. } => context.performance_info.as_ref(),
            Self::ConfigError { context, .. } => context.performance_info.as_ref(),
            Self::PerformanceError { context, .. } => context.performance_info.as_ref(),
            _ => None,
        }
    }

    /// Check if this error is recoverable
    pub fn is_recoverable(&self) -> bool {
        match self {
            Self::ShapeMismatch { .. } => true, // Can be fixed by reshaping
            Self::DimensionMismatch { .. } => true, // Can be fixed by dimension adjustment
            Self::TensorOpError { .. } => false, // Usually indicates fundamental issue
            Self::MemoryError { .. } => true,   // Can be fixed by freeing memory
            Self::HardwareError { .. } => true, // Can fallback to CPU
            Self::ConfigError { .. } => true,   // Can be fixed by config adjustment
            Self::PerformanceError { .. } => true, // Can be fixed by optimization
            _ => false,
        }
    }

    /// Attempt to recover from the error automatically
    pub fn try_recover(&self) -> std::result::Result<RecoveryAction, Self> {
        match self {
            Self::MemoryError { .. } => Ok(RecoveryAction::ClearMemory),
            Self::HardwareError { .. } => Ok(RecoveryAction::FallbackToCpu),
            Self::ShapeMismatch {
                expected,
                got,
                context,
            } => {
                if can_reshape(got, expected) {
                    Ok(RecoveryAction::Reshape(expected.clone()))
                } else {
                    Err(Self::ShapeMismatch {
                        expected: expected.clone(),
                        got: got.clone(),
                        context: context.clone(),
                    })
                }
            },
            _ => Err(Self::tensor_op_error(
                "Recovery not supported for this error type",
                "try_recover",
            )),
        }
    }
}

/// Recovery actions that can be taken automatically
#[derive(Debug, Clone)]
pub enum RecoveryAction {
    /// Clear memory and retry
    ClearMemory,
    /// Fallback to CPU execution
    FallbackToCpu,
    /// Reshape tensor to expected dimensions
    Reshape(Vec<usize>),
    /// Reduce batch size
    ReduceBatchSize(usize),
    /// Enable gradient checkpointing
    EnableCheckpointing,
}

/// Check if a tensor can be reshaped from one shape to another
fn can_reshape(from: &[usize], to: &[usize]) -> bool {
    let from_size: usize = from.iter().product();
    let to_size: usize = to.iter().product();
    from_size == to_size
}

// Removed manual Display implementation - using derive(Error) instead
// impl std::fmt::Display for CoreError {
//     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
/*        match self {
            Self::ShapeMismatch { expected, got, context } => {
                write!(f, "[{}] Shape mismatch in '{}': expected {:?}, got {:?}",
                       context.code.code(), context.operation, expected, got)?;
                if !context.recovery_suggestions.is_empty() {
                    write!(f, "\n\nSuggestions:")?;
                    for suggestion in &context.recovery_suggestions {
                        write!(f, "\n  • {}", suggestion)?;
                    }
                }
                if let Some(perf) = &context.performance_info {
                    write!(f, "\n\nPerformance Info:")?;
                    if let Some(mem) = perf.memory_usage_mb {
                        write!(f, "\n  Memory usage: {} MB", mem)?;
                    }
                    if let Some(dur) = perf.operation_duration {
                        write!(f, "\n  Operation duration: {:?}", dur)?;
                    }
                }
                Ok(())
            }
            Self::DimensionMismatch { context } => {
                write!(f, "[{}] Dimension mismatch in '{}'",
                       context.code.code(), context.operation)?;
                if !context.recovery_suggestions.is_empty() {
                    write!(f, "\n\nSuggestions:")?;
                    for suggestion in &context.recovery_suggestions {
                        write!(f, "\n  • {}", suggestion)?;
                    }
                }
                Ok(())
            }
            Self::TensorOpError { message, context } => {
                write!(f, "[{}] Tensor operation failed in '{}': {}",
                       context.code.code(), context.operation, message)?;
                if !context.recovery_suggestions.is_empty() {
                    write!(f, "\n\nSuggestions:")?;
                    for suggestion in &context.recovery_suggestions {
                        write!(f, "\n  • {}", suggestion)?;
                    }
                }
                Ok(())
            }
            Self::MemoryError { message, context } => {
                write!(f, "[{}] Memory error in '{}': {}",
                       context.code.code(), context.operation, message)?;
                if !context.recovery_suggestions.is_empty() {
                    write!(f, "\n\nSuggestions:")?;
                    for suggestion in &context.recovery_suggestions {
                        write!(f, "\n  • {}", suggestion)?;
                    }
                }
                if let Some(perf) = &context.performance_info {
                    if let Some(mem) = perf.memory_usage_mb {
                        write!(f, "\n\nMemory usage at error: {} MB", mem)?;
                    }
                }
                Ok(())
            }
            Self::HardwareError { message, context } => {
                write!(f, "[{}] Hardware error in '{}': {}",
                       context.code.code(), context.operation, message)?;
                if !context.recovery_suggestions.is_empty() {
                    write!(f, "\n\nSuggestions:")?;
                    for suggestion in &context.recovery_suggestions {
                        write!(f, "\n  • {}", suggestion)?;
                    }
                }
                Ok(())
            }
            Self::ConfigError { message, context } => {
                write!(f, "[{}] Configuration error in '{}': {}",
                       context.code.code(), context.operation, message)?;
                if !context.recovery_suggestions.is_empty() {
                    write!(f, "\n\nSuggestions:")?;
                    for suggestion in &context.recovery_suggestions {
                        write!(f, "\n  • {}", suggestion)?;
                    }
                }
                Ok(())
            }
            Self::PerformanceError { message, context } => {
                write!(f, "[{}] Performance error in '{}': {}",
                       context.code.code(), context.operation, message)?;
                if !context.recovery_suggestions.is_empty() {
                    write!(f, "\n\nSuggestions:")?;
                    for suggestion in &context.recovery_suggestions {
                        write!(f, "\n  • {}", suggestion)?;
                    }
                }
                if let Some(perf) = &context.performance_info {
                    write!(f, "\n\nPerformance Info:")?;
                    if let Some(dur) = perf.operation_duration {
                        write!(f, "\n  Operation duration: {:?}", dur)?;
                    }
                    if let Some(cpu) = perf.cpu_usage {
                        write!(f, "\n  CPU usage: {:.1}%", cpu)?;
                    }
                    if let Some(gpu) = perf.gpu_utilization {
                        write!(f, "\n  GPU utilization: {:.1}%", gpu)?;
                    }
                }
                Ok(())
            }
            // Fall back to default Error display for legacy errors
            _ => write!(f, "{}", self),
        }
    }
} */

#[allow(deprecated)] // Backward compatibility implementation for CoreError
impl From<std::fmt::Error> for CoreError {
    fn from(err: std::fmt::Error) -> Self {
        CoreError::FormattingError(err.to_string())
    }
}

#[allow(deprecated)] // Backward compatibility implementation for CoreError
impl From<ShapeError> for CoreError {
    fn from(err: ShapeError) -> Self {
        CoreError::ShapeError(err.to_string())
    }
}

#[allow(deprecated)] // Backward compatibility implementation for CoreError
impl Clone for CoreError {
    fn clone(&self) -> Self {
        match self {
            CoreError::ShapeMismatch {
                expected,
                got,
                context,
            } => CoreError::ShapeMismatch {
                expected: expected.clone(),
                got: got.clone(),
                context: context.clone(),
            },
            CoreError::DimensionMismatch { context } => CoreError::DimensionMismatch {
                context: context.clone(),
            },
            CoreError::InvalidArgument(msg) => CoreError::InvalidArgument(msg.clone()),
            CoreError::InvalidConfig(msg) => CoreError::InvalidConfig(msg.clone()),
            CoreError::NotImplemented(msg) => CoreError::NotImplemented(msg.clone()),
            CoreError::TensorOpError { message, context } => CoreError::TensorOpError {
                message: message.clone(),
                context: context.clone(),
            },
            CoreError::MemoryError { message, context } => CoreError::MemoryError {
                message: message.clone(),
                context: context.clone(),
            },
            CoreError::HardwareError { message, context } => CoreError::HardwareError {
                message: message.clone(),
                context: context.clone(),
            },
            CoreError::ConfigError { message, context } => CoreError::ConfigError {
                message: message.clone(),
                context: context.clone(),
            },
            CoreError::PerformanceError { message, context } => CoreError::PerformanceError {
                message: message.clone(),
                context: context.clone(),
            },
            CoreError::WeightLoadError(msg) => CoreError::WeightLoadError(msg.clone()),
            CoreError::ShapeError(msg) => CoreError::ShapeError(msg.clone()),
            // For non-cloneable types, create new instances with the string representation
            CoreError::Io(io_err) => CoreError::InvalidConfig(format!("IO Error: {}", io_err)),
            CoreError::Serialization(serde_err) => {
                CoreError::InvalidConfig(format!("Serialization Error: {}", serde_err))
            },
            CoreError::Other(anyhow_err) => {
                CoreError::InvalidConfig(format!("Other Error: {}", anyhow_err))
            },
            // Handle all other string-based variants
            _ => {
                // For any other variant, convert to string and wrap as InvalidConfig
                CoreError::InvalidConfig(format!("{}", self))
            },
        }
    }
}

#[deprecated(
    since = "0.4.0",
    note = "Use Result from crate::errors instead for standardized error handling"
)]
#[allow(deprecated)]
pub type Result<T> = std::result::Result<T, CoreError>;