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
//! Common GPU operations implementation
//!
//! This module provides the core logic for GPU-accelerated operations, with
//! implementations that can use CUDA when available or fall back to CPU processing.
use ndarray::{Array, Array1, Array2, Axis};
use rayon::prelude::*;
use std::sync::Arc;
use crate::error::{Error, Result};
use crate::gpu::{GpuConfig, GpuError, GpuManager, GpuOperationType};
use crate::optimized::dataframe::OptimizedDataFrame;
use crate::DataFrame;
use crate::Series;
/// Trait for GPU-accelerated operations
pub trait GpuAccelerated {
/// Apply GPU acceleration to supported operations
fn gpu_accelerate(&self) -> Result<Self>
where
Self: Sized;
/// Check if this object can be GPU-accelerated
fn is_gpu_acceleratable(&self) -> bool;
}
/// Trait for operations that can be executed on GPU
pub trait GpuExecutable {
/// Execute operation on GPU
fn execute_on_gpu(&self, manager: &GpuManager) -> Result<Self>
where
Self: Sized;
/// Get operation type
fn operation_type(&self) -> GpuOperationType;
/// Get operation size (for deciding whether to use GPU)
fn size(&self) -> usize;
}
/// GPU-accelerated matrix operations
pub struct GpuMatrix {
/// The data matrix
pub data: Array2<f64>,
/// Whether the matrix is already on GPU
pub on_gpu: bool,
}
impl GpuMatrix {
/// Create a new GPU matrix from an ndarray matrix
pub fn new(data: Array2<f64>) -> Self {
GpuMatrix {
data,
on_gpu: false,
}
}
/// Get the CPU data
pub fn to_cpu(&self) -> Result<Array2<f64>> {
Ok(self.data.clone())
}
/// Multiply this matrix by another matrix (CPU fallback)
pub fn dot_cpu(&self, other: &GpuMatrix) -> Result<GpuMatrix> {
// Check if dimensions are compatible
if self.data.shape()[1] != other.data.shape()[0] {
return Err(Error::DimensionMismatch(format!(
"Incompatible dimensions for matrix multiplication: {:?} and {:?}",
self.data.shape(),
other.data.shape()
)));
}
// Perform matrix multiplication using ndarray
let result = self.data.dot(&other.data);
Ok(GpuMatrix {
data: result,
on_gpu: false,
})
}
/// Matrix multiplication (with possible GPU acceleration)
pub fn dot(&self, other: &GpuMatrix) -> Result<GpuMatrix> {
// Try GPU acceleration if available
#[cfg(cuda_available)]
{
let manager = crate::gpu::get_gpu_manager()?;
// Check if GPU is available and the matrices are large enough
let total_elements = self.data.len() + other.data.len();
if manager.is_available() && manager.context().should_use_gpu(total_elements) {
match crate::gpu::cuda::matrix_multiply(self, other, &manager) {
Ok(result) => return Ok(result),
Err(e) => {
// If configured to fallback to CPU, do so
if manager.context().config().fallback_to_cpu {
println!("Warning: GPU matrix multiplication failed ({}). Falling back to CPU.", e);
} else {
return Err(e.into());
}
}
}
}
}
// Fallback to CPU implementation
self.dot_cpu(other)
}
/// Element-wise operation (CPU fallback)
fn elementwise_operation_cpu(
&self,
other: &GpuMatrix,
op: fn(f64, f64) -> f64,
) -> Result<GpuMatrix> {
// Check if dimensions match
if self.data.shape() != other.data.shape() {
return Err(Error::DimensionMismatch(format!(
"Incompatible dimensions for element-wise operation: {:?} and {:?}",
self.data.shape(),
other.data.shape()
)));
}
// Perform element-wise operation
let result = Array::from_shape_fn(self.data.dim(), |(i, j)| {
op(self.data[[i, j]], other.data[[i, j]])
});
Ok(GpuMatrix {
data: result,
on_gpu: false,
})
}
/// Element-wise addition (with possible GPU acceleration)
pub fn add(&self, other: &GpuMatrix) -> Result<GpuMatrix> {
// Try GPU acceleration if available
#[cfg(cuda_available)]
{
let manager = crate::gpu::get_gpu_manager()?;
// Check if GPU is available and the matrices are large enough
let total_elements = self.data.len() + other.data.len();
if manager.is_available() && manager.context().should_use_gpu(total_elements) {
match crate::gpu::cuda::elementwise_add(self, other, &manager) {
Ok(result) => return Ok(result),
Err(e) => {
// If configured to fallback to CPU, do so
if manager.context().config().fallback_to_cpu {
println!("Warning: GPU addition failed ({}). Falling back to CPU.", e);
} else {
return Err(e.into());
}
}
}
}
}
// Fallback to CPU implementation
self.elementwise_operation_cpu(other, |a, b| a + b)
}
/// Element-wise subtraction (with possible GPU acceleration)
pub fn subtract(&self, other: &GpuMatrix) -> Result<GpuMatrix> {
// Try GPU acceleration if available
#[cfg(cuda_available)]
{
let manager = crate::gpu::get_gpu_manager()?;
// Check if GPU is available and the matrices are large enough
let total_elements = self.data.len() + other.data.len();
if manager.is_available() && manager.context().should_use_gpu(total_elements) {
match crate::gpu::cuda::elementwise_subtract(self, other, &manager) {
Ok(result) => return Ok(result),
Err(e) => {
// If configured to fallback to CPU, do so
if manager.context().config().fallback_to_cpu {
println!(
"Warning: GPU subtraction failed ({}). Falling back to CPU.",
e
);
} else {
return Err(e.into());
}
}
}
}
}
// Fallback to CPU implementation
self.elementwise_operation_cpu(other, |a, b| a - b)
}
/// Element-wise multiplication (with possible GPU acceleration)
pub fn multiply(&self, other: &GpuMatrix) -> Result<GpuMatrix> {
// Try GPU acceleration if available
#[cfg(cuda_available)]
{
let manager = crate::gpu::get_gpu_manager()?;
// Check if GPU is available and the matrices are large enough
let total_elements = self.data.len() + other.data.len();
if manager.is_available() && manager.context().should_use_gpu(total_elements) {
match crate::gpu::cuda::elementwise_multiply(self, other, &manager) {
Ok(result) => return Ok(result),
Err(e) => {
// If configured to fallback to CPU, do so
if manager.context().config().fallback_to_cpu {
println!(
"Warning: GPU multiplication failed ({}). Falling back to CPU.",
e
);
} else {
return Err(e.into());
}
}
}
}
}
// Fallback to CPU implementation
self.elementwise_operation_cpu(other, |a, b| a * b)
}
/// Element-wise division (with possible GPU acceleration)
pub fn divide(&self, other: &GpuMatrix) -> Result<GpuMatrix> {
// Try GPU acceleration if available
#[cfg(cuda_available)]
{
let manager = crate::gpu::get_gpu_manager()?;
// Check if GPU is available and the matrices are large enough
let total_elements = self.data.len() + other.data.len();
if manager.is_available() && manager.context().should_use_gpu(total_elements) {
match crate::gpu::cuda::elementwise_divide(self, other, &manager) {
Ok(result) => return Ok(result),
Err(e) => {
// If configured to fallback to CPU, do so
if manager.context().config().fallback_to_cpu {
println!("Warning: GPU division failed ({}). Falling back to CPU.", e);
} else {
return Err(e.into());
}
}
}
}
}
// Fallback to CPU implementation
self.elementwise_operation_cpu(other, |a, b| if b != 0.0 { a / b } else { f64::NAN })
}
/// Sum of all elements (with possible GPU acceleration)
pub fn sum(&self) -> Result<f64> {
// Try GPU acceleration if available
#[cfg(cuda_available)]
{
let manager = crate::gpu::get_gpu_manager()?;
// Check if GPU is available and the matrix is large enough
if manager.is_available() && manager.context().should_use_gpu(self.data.len()) {
match crate::gpu::cuda::matrix_sum(self, &manager) {
Ok(result) => return Ok(result),
Err(e) => {
// If configured to fallback to CPU, do so
if manager.context().config().fallback_to_cpu {
println!("Warning: GPU sum failed ({}). Falling back to CPU.", e);
} else {
return Err(e.into());
}
}
}
}
}
// Fallback to CPU implementation
let sum = self.data.sum();
Ok(sum)
}
/// Mean of all elements (with possible GPU acceleration)
pub fn mean(&self) -> Result<f64> {
let sum = self.sum()?;
let len = self.data.len();
if len > 0 {
Ok(sum / (len as f64))
} else {
Ok(f64::NAN)
}
}
/// Sort matrix rows (with possible GPU acceleration)
pub fn sort_rows(&self) -> Result<GpuMatrix> {
// Try GPU acceleration if available
#[cfg(cuda_available)]
{
let manager = crate::gpu::get_gpu_manager()?;
// Check if GPU is available and the matrix is large enough
if manager.is_available() && manager.context().should_use_gpu(self.data.len()) {
match crate::gpu::cuda::sort_matrix_rows(self, &manager) {
Ok(result) => return Ok(result),
Err(e) => {
// If configured to fallback to CPU, do so
if manager.context().config().fallback_to_cpu {
println!("Warning: GPU sort failed ({}). Falling back to CPU.", e);
} else {
return Err(e.into());
}
}
}
}
}
// Fallback to CPU implementation using rayon for parallelism
let shape = self.data.dim();
let mut result = self.data.clone();
// Sort each row in parallel
result
.axis_iter_mut(Axis(0))
.par_bridge()
.for_each(|mut row| {
let mut row_vec: Vec<f64> = row.iter().cloned().collect();
row_vec.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
for (i, val) in row_vec.iter().enumerate() {
row[i] = *val;
}
});
Ok(GpuMatrix {
data: result,
on_gpu: false,
})
}
}
/// Add GPU acceleration to Series
impl<T> GpuAccelerated for Series<T>
where
T: Clone + Copy + Into<f64> + std::fmt::Debug,
{
fn gpu_accelerate(&self) -> Result<Self> {
// If the series is large enough, use GPU acceleration
if self.len() < 10_000 {
return Ok(self.clone());
}
// Actual acceleration happens when operations are performed
Ok(self.clone())
}
fn is_gpu_acceleratable(&self) -> bool {
// Simple numeric series are generally acceleratable
self.len() >= 10_000
}
}
/// Add GPU acceleration to DataFrame
impl GpuAccelerated for DataFrame {
fn gpu_accelerate(&self) -> Result<Self> {
// For now, just return a clone - actual acceleration happens when operations are performed
Ok(self.clone())
}
fn is_gpu_acceleratable(&self) -> bool {
// Check if DataFrame has numeric columns and is large enough
let mut has_numeric = false;
for col_name in self.column_names() {
if self.is_numeric_column(&col_name) {
has_numeric = true;
break;
}
}
has_numeric && self.row_count() >= 10_000
}
}
/// Add GPU acceleration to OptimizedDataFrame
impl GpuAccelerated for OptimizedDataFrame {
fn gpu_accelerate(&self) -> Result<Self> {
// For now, just return a clone - actual acceleration happens when operations are performed
Ok(self.clone())
}
fn is_gpu_acceleratable(&self) -> bool {
// OptimizedDataFrame is already optimized, but can benefit from GPU acceleration
self.row_count() >= 10_000
}
}
/// GPU vector operations
pub struct GpuVector {
/// The data vector
pub data: Array1<f64>,
/// Whether the vector is already on GPU
pub on_gpu: bool,
}
impl GpuVector {
/// Create a new GPU vector from an ndarray vector
pub fn new(data: Array1<f64>) -> Self {
GpuVector {
data,
on_gpu: false,
}
}
/// Dot product (with possible GPU acceleration)
pub fn dot(&self, other: &GpuVector) -> Result<f64> {
// Check if dimensions are compatible
if self.data.len() != other.data.len() {
return Err(Error::DimensionMismatch(format!(
"Incompatible dimensions for dot product: {} and {}",
self.data.len(),
other.data.len()
)));
}
// Try GPU acceleration if available
#[cfg(cuda_available)]
{
let manager = crate::gpu::get_gpu_manager()?;
// Check if GPU is available and the vectors are large enough
let total_elements = self.data.len() + other.data.len();
if manager.is_available() && manager.context().should_use_gpu(total_elements) {
match crate::gpu::cuda::vector_dot_product(self, other, &manager) {
Ok(result) => return Ok(result),
Err(e) => {
// If configured to fallback to CPU, do so
if manager.context().config().fallback_to_cpu {
println!(
"Warning: GPU dot product failed ({}). Falling back to CPU.",
e
);
} else {
return Err(e.into());
}
}
}
}
}
// Fallback to CPU implementation
let result = self.data.dot(&other.data);
Ok(result)
}
/// Element-wise operation (CPU fallback)
fn elementwise_operation_cpu(
&self,
other: &GpuVector,
op: fn(f64, f64) -> f64,
) -> Result<GpuVector> {
// Check if dimensions match
if self.data.len() != other.data.len() {
return Err(Error::DimensionMismatch(format!(
"Incompatible dimensions for element-wise operation: {} and {}",
self.data.len(),
other.data.len()
)));
}
// Perform element-wise operation
let result = Array::from_iter(
self.data
.iter()
.zip(other.data.iter())
.map(|(&a, &b)| op(a, b)),
);
Ok(GpuVector {
data: result,
on_gpu: false,
})
}
/// Element-wise addition (with possible GPU acceleration)
pub fn add(&self, other: &GpuVector) -> Result<GpuVector> {
// Try GPU acceleration if available
#[cfg(cuda_available)]
{
let manager = crate::gpu::get_gpu_manager()?;
// Check if GPU is available and the vectors are large enough
let total_elements = self.data.len() + other.data.len();
if manager.is_available() && manager.context().should_use_gpu(total_elements) {
match crate::gpu::cuda::vector_add(self, other, &manager) {
Ok(result) => return Ok(result),
Err(e) => {
// If configured to fallback to CPU, do so
if manager.context().config().fallback_to_cpu {
println!(
"Warning: GPU vector addition failed ({}). Falling back to CPU.",
e
);
} else {
return Err(e.into());
}
}
}
}
}
// Fallback to CPU implementation
self.elementwise_operation_cpu(other, |a, b| a + b)
}
}
/// A trait for operations that can be GPU-accelerated
pub trait GpuOperation {
/// Get the operation type
fn operation_type(&self) -> GpuOperationType;
/// Execute the operation
fn execute(&self) -> Result<Box<dyn GpuOperation>>;
/// Execute the operation on GPU
fn execute_on_gpu(&self, manager: &GpuManager) -> Result<Box<dyn GpuOperation>>;
/// Get the size of the operation (in elements)
fn size(&self) -> usize;
}