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
//! Automatic fallback mechanisms for operation recovery
//!
//! This module provides utilities for automatic fallback when operations fail,
//! particularly for GPU-to-CPU fallback scenarios.
#[cfg(feature = "gpu")]
use crate::Device;
use crate::{Result, Tensor, TensorError};
use scirs2_core::num_traits;
use std::sync::atomic::{AtomicBool, Ordering};
/// Global flag to enable/disable automatic fallback
static AUTO_FALLBACK_ENABLED: AtomicBool = AtomicBool::new(true);
/// Configuration for fallback behavior
#[derive(Debug, Clone)]
pub struct FallbackConfig {
/// Enable automatic GPU-to-CPU fallback
pub gpu_to_cpu: bool,
/// Enable automatic precision reduction
pub reduce_precision: bool,
/// Enable memory cleanup and retry
pub memory_cleanup: bool,
/// Maximum number of retry attempts
pub max_retries: usize,
/// Log fallback attempts
pub log_fallbacks: bool,
}
impl Default for FallbackConfig {
fn default() -> Self {
Self {
gpu_to_cpu: true,
reduce_precision: false,
memory_cleanup: true,
max_retries: 3,
log_fallbacks: true,
}
}
}
/// Global fallback configuration
#[allow(static_mut_refs)]
static mut GLOBAL_FALLBACK_CONFIG: Option<FallbackConfig> = None;
static FALLBACK_CONFIG_INIT: std::sync::Once = std::sync::Once::new();
/// Get the global fallback configuration
#[allow(static_mut_refs)]
pub fn get_fallback_config() -> FallbackConfig {
unsafe {
FALLBACK_CONFIG_INIT.call_once(|| {
GLOBAL_FALLBACK_CONFIG = Some(FallbackConfig::default());
});
GLOBAL_FALLBACK_CONFIG
.as_ref()
.expect("Fallback config should be initialized")
.clone()
}
}
/// Set the global fallback configuration
#[allow(static_mut_refs)]
pub fn set_fallback_config(config: FallbackConfig) {
unsafe {
GLOBAL_FALLBACK_CONFIG = Some(config);
}
}
/// Enable or disable automatic fallback globally
pub fn set_auto_fallback_enabled(enabled: bool) {
AUTO_FALLBACK_ENABLED.store(enabled, Ordering::SeqCst);
}
/// Check if automatic fallback is enabled
pub fn is_auto_fallback_enabled() -> bool {
AUTO_FALLBACK_ENABLED.load(Ordering::SeqCst)
}
/// Trait for operations that support fallback
pub trait FallbackOperation<T> {
/// Execute the operation with automatic fallback
fn with_fallback(self) -> Result<T>;
/// Execute the operation on CPU as fallback
fn fallback_to_cpu(self) -> Result<T>;
}
/// Execute a binary operation with automatic fallback
pub fn execute_binary_op_with_fallback<T, F>(
operation_name: &str,
tensor_a: &Tensor<T>,
tensor_b: &Tensor<T>,
gpu_op: F,
#[allow(unused_variables)] cpu_op: F,
) -> Result<Tensor<T>>
where
T: Clone
+ Default
+ scirs2_core::num_traits::Zero
+ scirs2_core::num_traits::One
+ Send
+ Sync
+ 'static
+ bytemuck::Pod,
F: Fn(&Tensor<T>, &Tensor<T>) -> Result<Tensor<T>>,
{
let config = get_fallback_config();
if !is_auto_fallback_enabled() {
return gpu_op(tensor_a, tensor_b);
}
// Try the primary operation first
match gpu_op(tensor_a, tensor_b) {
Ok(result) => Ok(result),
Err(error) => {
if config.log_fallbacks {
eprintln!("Operation '{operation_name}' failed: {error}. Attempting fallback...");
}
// Check if this error supports fallback
if error.supports_fallback() && config.gpu_to_cpu {
// Try to move tensors to CPU and retry
match (tensor_a.device(), tensor_b.device()) {
#[cfg(feature = "gpu")]
(Device::Gpu(_), _) | (_, Device::Gpu(_)) => {
if config.log_fallbacks {
eprintln!(
"Falling back to CPU execution for operation '{}'",
operation_name
);
}
// Move tensors to CPU
let cpu_a = tensor_a.to_device(Device::Cpu)?;
let cpu_b = tensor_b.to_device(Device::Cpu)?;
// Execute on CPU
match cpu_op(&cpu_a, &cpu_b) {
Ok(result) => {
if config.log_fallbacks {
eprintln!(
"CPU fallback successful for operation '{}'",
operation_name
);
}
Ok(result)
}
Err(cpu_error) => {
if config.log_fallbacks {
eprintln!(
"CPU fallback also failed for operation '{}': {}",
operation_name, cpu_error
);
}
Err(cpu_error)
}
}
}
_ => {
// Already on CPU or other device, can't fallback further
Err(error)
}
}
} else {
Err(error)
}
}
}
}
/// Execute a unary operation with automatic fallback
pub fn execute_unary_op_with_fallback<T, F>(
operation_name: &str,
tensor: &Tensor<T>,
gpu_op: F,
#[allow(unused_variables)] cpu_op: F,
) -> Result<Tensor<T>>
where
T: Clone
+ Default
+ scirs2_core::num_traits::Zero
+ scirs2_core::num_traits::One
+ Send
+ Sync
+ 'static
+ bytemuck::Pod,
F: Fn(&Tensor<T>) -> Result<Tensor<T>>,
{
let config = get_fallback_config();
if !is_auto_fallback_enabled() {
return gpu_op(tensor);
}
// Try the primary operation first
match gpu_op(tensor) {
Ok(result) => Ok(result),
Err(error) => {
if config.log_fallbacks {
eprintln!("Operation '{operation_name}' failed: {error}. Attempting fallback...");
}
// Check if this error supports fallback
if error.supports_fallback() && config.gpu_to_cpu {
// Try to move tensor to CPU and retry
#[cfg(feature = "gpu")]
return if let Device::Gpu(_) = tensor.device() {
if config.log_fallbacks {
eprintln!(
"Falling back to CPU execution for operation '{}'",
operation_name
);
}
// Move tensor to CPU
let cpu_tensor = tensor.to_device(Device::Cpu)?;
// Execute on CPU
match cpu_op(&cpu_tensor) {
Ok(result) => {
if config.log_fallbacks {
eprintln!(
"CPU fallback successful for operation '{}'",
operation_name
);
}
Ok(result)
}
Err(cpu_error) => {
if config.log_fallbacks {
eprintln!(
"CPU fallback also failed for operation '{}': {}",
operation_name, cpu_error
);
}
Err(cpu_error)
}
}
} else {
// Already on CPU or other device, can't fallback further
Err(error)
};
#[cfg(not(feature = "gpu"))]
return Err(error);
} else {
Err(error)
}
}
}
}
/// Memory cleanup utility for fallback scenarios
pub fn cleanup_memory_and_retry<T, F>(operation: F, max_retries: usize) -> Result<T>
where
F: Fn() -> Result<T>,
{
let mut attempt = 0;
loop {
match operation() {
Ok(result) => return Ok(result),
Err(error) => {
attempt += 1;
if attempt >= max_retries {
return Err(error);
}
// Check if this is a memory-related error
match &error {
TensorError::AllocationError { .. } | TensorError::ResourceExhausted { .. } => {
eprintln!("Memory error detected, attempting cleanup (attempt {attempt}/{max_retries})");
// Trigger garbage collection if available
#[cfg(feature = "gpu")]
{
// Clear GPU memory pools
crate::memory::global_monitor().clear();
}
// Force garbage collection
std::hint::black_box(Vec::<u8>::new());
// Short delay before retry
std::thread::sleep(std::time::Duration::from_millis(100));
}
_ => {
// Not a memory error, don't retry
return Err(error);
}
}
}
}
}
}
/// Wrapper for automatic fallback of results
pub struct FallbackWrapper<T> {
result: Result<T>,
operation_name: String,
}
impl<T> FallbackWrapper<T> {
pub fn new(result: Result<T>, operation_name: &str) -> Self {
Self {
result,
operation_name: operation_name.to_string(),
}
}
pub fn with_cpu_fallback<F>(self, cpu_fallback: F) -> Result<T>
where
F: FnOnce() -> Result<T>,
{
match self.result {
Ok(result) => Ok(result),
Err(error) => {
if error.supports_fallback() && is_auto_fallback_enabled() {
let config = get_fallback_config();
if config.log_fallbacks {
eprintln!(
"Attempting CPU fallback for operation '{}'",
self.operation_name
);
}
cpu_fallback()
} else {
Err(error)
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{DType, Device, Tensor};
#[test]
fn test_fallback_config() {
let config = FallbackConfig::default();
assert!(config.gpu_to_cpu);
assert!(config.memory_cleanup);
assert_eq!(config.max_retries, 3);
}
#[test]
fn test_auto_fallback_flag() {
assert!(is_auto_fallback_enabled()); // Default is true
set_auto_fallback_enabled(false);
assert!(!is_auto_fallback_enabled());
set_auto_fallback_enabled(true);
assert!(is_auto_fallback_enabled());
}
#[test]
fn test_fallback_wrapper() {
let success_result: Result<i32> = Ok(42);
let wrapper = FallbackWrapper::new(success_result, "test_op");
let result = wrapper.with_cpu_fallback(|| Ok(100));
assert_eq!(result.expect("test: operation should succeed"), 42);
}
#[test]
fn test_error_supports_fallback() {
let gpu_error = TensorError::unsupported_device("test", "gpu:0", true);
assert!(gpu_error.supports_fallback());
let shape_error = TensorError::shape_mismatch("test", "[2, 2]", "[3, 3]");
assert!(!shape_error.supports_fallback());
}
}