rustorch 0.6.29

Production-ready PyTorch-compatible deep learning library in Rust with special mathematical functions (gamma, Bessel, error functions), statistical distributions, Fourier transforms (FFT/RFFT), matrix decomposition (SVD/QR/LU/eigenvalue), automatic differentiation, neural networks, computer vision transforms, complete GPU acceleration (CUDA/Metal/OpenCL), SIMD optimizations, parallel processing, WebAssembly browser support, comprehensive distributed learning support, and performance validation
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
/// GPU kernel demonstration and validation example
/// GPUカーネルデモンストレーションと検証例
#[cfg(not(target_arch = "wasm32"))]
use rustorch::gpu::{
    kernels::{AddKernel, KernelExecutor, MatMulKernel},
    validation::print_gpu_validation_report,
    DeviceType,
};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    println!("=== RusTorch GPU Kernel Demo ===\n");

    #[cfg(not(target_arch = "wasm32"))]
    {
        // Print available devices
        println!("Available GPU devices:");
        let devices = vec![
            DeviceType::Cpu,
            #[cfg(feature = "cuda")]
            DeviceType::Cuda(0),
            #[cfg(feature = "metal")]
            DeviceType::Metal(0),
            #[cfg(feature = "opencl")]
            DeviceType::OpenCL(0),
        ];

        for device in &devices {
            if device.is_available() {
                println!("{}", device);
            } else {
                println!("{} (not available)", device);
            }
        }
        println!();
    }

    #[cfg(target_arch = "wasm32")]
    {
        println!("GPU operations are not available in WASM target.");
        println!("This demo shows CPU-based operations only.\n");
    }

    // Demonstrate element-wise addition
    demo_elementwise_addition()?;

    // Demonstrate matrix multiplication
    demo_matrix_multiplication()?;

    #[cfg(not(target_arch = "wasm32"))]
    {
        // Run comprehensive validation
        println!("=== Running GPU Validation ===");
        print_gpu_validation_report();

        // Performance comparison
        performance_comparison()?;

        // Optional: Metal specific demo
        #[cfg(feature = "metal")]
        demo_metal_specific()?;
    }

    #[cfg(target_arch = "wasm32")]
    {
        println!("=== WASM CPU Performance Demo ===");
        wasm_cpu_performance_demo()?;
    }

    Ok(())
}

fn demo_elementwise_addition() -> Result<(), Box<dyn std::error::Error>> {
    println!("=== Element-wise Addition Demo ===");

    let size = 1024;
    let a = vec![1.0f32; size];
    let b = vec![2.0f32; size];
    let mut c = vec![0.0f32; size];

    #[cfg(not(target_arch = "wasm32"))]
    {
        let kernel = AddKernel;

        for device in &[DeviceType::Cpu] {
            if !device.is_available() {
                continue;
            }

            let executor = KernelExecutor::new(*device);
            let start_time = std::time::Instant::now();

            let inputs = [a.as_slice(), b.as_slice()];
            let mut outputs = [c.as_mut_slice()];

            executor.execute_kernel(&kernel, &inputs, &mut outputs)?;

            let elapsed = start_time.elapsed();

            // Verify results
            let correct = c.iter().all(|&x| (x - 3.0).abs() < 1e-6);

            println!(
                "  {}: {} ({:.2}ms) - {}",
                device,
                if correct { "" } else { "" },
                elapsed.as_secs_f64() * 1000.0,
                if correct { "PASS" } else { "FAIL" }
            );

            // Reset output for next device
            c.fill(0.0);
        }
    }

    #[cfg(target_arch = "wasm32")]
    {
        let start_time = std::time::Instant::now();

        // CPU implementation for WASM
        for i in 0..size {
            c[i] = a[i] + b[i];
        }

        let elapsed = start_time.elapsed();
        let correct = c.iter().all(|&x| (x - 3.0).abs() < 1e-6);

        println!(
            "  CPU (WASM): {} ({:.2}ms) - {}",
            if correct { "" } else { "" },
            elapsed.as_secs_f64() * 1000.0,
            if correct { "PASS" } else { "FAIL" }
        );
    }

    println!();
    Ok(())
}

fn demo_matrix_multiplication() -> Result<(), Box<dyn std::error::Error>> {
    println!("=== Matrix Multiplication Demo ===");

    let n = 4;
    let size = n * n;

    // Create test matrices
    let mut a = vec![0.0f32; size];
    let mut b = vec![0.0f32; size];

    // A = sequential values, B = identity matrix
    for i in 0..n {
        for j in 0..n {
            a[i * n + j] = (i * n + j + 1) as f32;
            b[i * n + j] = if i == j { 1.0 } else { 0.0 };
        }
    }

    let mut c = vec![0.0f32; size];

    #[cfg(not(target_arch = "wasm32"))]
    {
        let kernel = MatMulKernel;

        for device in &[DeviceType::Cpu] {
            if !device.is_available() {
                continue;
            }

            let executor = KernelExecutor::new(*device);
            let start_time = std::time::Instant::now();

            let inputs = [a.as_slice(), b.as_slice()];
            let mut outputs = [c.as_mut_slice()];

            executor.execute_kernel(&kernel, &inputs, &mut outputs)?;

            let elapsed = start_time.elapsed();

            // Verify results (A * I = A)
            let correct = a
                .iter()
                .zip(c.iter())
                .all(|(expected, actual)| (expected - actual).abs() < 1e-5);

            println!(
                "  {} ({}x{}): {} ({:.2}ms) - {}",
                device,
                n,
                n,
                if correct { "" } else { "" },
                elapsed.as_secs_f64() * 1000.0,
                if correct { "PASS" } else { "FAIL" }
            );

            // Reset output for next device
            c.fill(0.0);
        }
    }

    #[cfg(target_arch = "wasm32")]
    {
        let start_time = std::time::Instant::now();

        // CPU matrix multiplication for WASM (A * B = C)
        for i in 0..n {
            for j in 0..n {
                for k in 0..n {
                    c[i * n + j] += a[i * n + k] * b[k * n + j];
                }
            }
        }

        let elapsed = start_time.elapsed();

        // Verify results (A * I = A)
        let correct = a
            .iter()
            .zip(c.iter())
            .all(|(expected, actual)| (expected - actual).abs() < 1e-5);

        println!(
            "  CPU (WASM) ({}x{}): {} ({:.2}ms) - {}",
            n,
            n,
            if correct { "" } else { "" },
            elapsed.as_secs_f64() * 1000.0,
            if correct { "PASS" } else { "FAIL" }
        );
    }

    println!();
    Ok(())
}

#[cfg(not(target_arch = "wasm32"))]
fn performance_comparison() -> Result<(), Box<dyn std::error::Error>> {
    println!("=== Performance Comparison ===");

    let sizes = vec![1024, 4096, 16384];

    #[cfg(not(target_arch = "wasm32"))]
    let kernel = AddKernel;

    for size in sizes {
        println!("Size: {} elements", size);

        let a = vec![1.0f32; size];
        let b = vec![2.0f32; size];
        let mut c = vec![0.0f32; size];

        #[cfg(not(target_arch = "wasm32"))]
        {
            for device in &[DeviceType::Cpu] {
                if !device.is_available() {
                    continue;
                }

                let executor = KernelExecutor::new(*device);

                // Warmup
                let inputs = [a.as_slice(), b.as_slice()];
                let mut outputs = [c.as_mut_slice()];
                executor.execute_kernel(&kernel, &inputs, &mut outputs)?;

                // Benchmark
                let iterations = 10;
                let start_time = std::time::Instant::now();

                for _ in 0..iterations {
                    let inputs = [a.as_slice(), b.as_slice()];
                    let mut outputs = [c.as_mut_slice()];
                    executor.execute_kernel(&kernel, &inputs, &mut outputs)?;
                }

                let elapsed = start_time.elapsed();
                let avg_time = elapsed.as_secs_f64() / iterations as f64;
                let throughput = size as f64 / avg_time / 1e6; // Million elements per second

                println!(
                    "  {}: {:.2}ms avg, {:.1} Melem/s",
                    device,
                    avg_time * 1000.0,
                    throughput
                );
            }
        }

        #[cfg(target_arch = "wasm32")]
        {
            // Warmup
            for i in 0..size {
                c[i] = a[i] + b[i];
            }

            // Benchmark
            let iterations = 10;
            let start_time = std::time::Instant::now();

            for _ in 0..iterations {
                for i in 0..size {
                    c[i] = a[i] + b[i];
                }
            }

            let elapsed = start_time.elapsed();
            let avg_time = elapsed.as_secs_f64() / iterations as f64;
            let throughput = size as f64 / avg_time / 1e6; // Million elements per second

            println!(
                "  CPU (WASM): {:.2}ms avg, {:.1} Melem/s",
                avg_time * 1000.0,
                throughput
            );
        }
        println!();
    }

    Ok(())
}

#[cfg(target_arch = "wasm32")]
fn wasm_cpu_performance_demo() -> Result<(), Box<dyn std::error::Error>> {
    println!("=== WASM CPU Performance Demo ===");

    let sizes = vec![128, 512, 1024];

    for size in sizes {
        println!("Matrix size: {}x{}", size, size);

        // Create test matrices
        let a: Vec<f32> = (0..size * size)
            .map(|i| (i as f32) / (size * size) as f32)
            .collect();
        let b: Vec<f32> = (0..size * size)
            .map(|i| ((i * 2) as f32) / (size * size) as f32)
            .collect();
        let mut c = vec![0.0f32; size * size];

        let start_time = std::time::Instant::now();

        // Matrix multiplication: C = A * B
        for i in 0..size {
            for j in 0..size {
                for k in 0..size {
                    c[i * size + j] += a[i * size + k] * b[k * size + j];
                }
            }
        }

        let elapsed = start_time.elapsed();

        // Calculate GFLOPS
        let flops = 2.0 * (size * size * size) as f64;
        let gflops = flops / (elapsed.as_secs_f64() * 1e9);

        println!(
            "  CPU: {:.3}ms ({:.2} GFLOPS)",
            elapsed.as_secs_f64() * 1000.0,
            gflops
        );

        // Verify some results are non-zero
        let non_zero_count = c.iter().filter(|&&x| x.abs() > 1e-6).count();
        println!("  Non-zero results: {}/{}", non_zero_count, size * size);
    }

    println!();
    Ok(())
}

#[cfg(feature = "cuda")]
#[allow(dead_code)]
fn demo_cuda_specific() -> Result<(), Box<dyn std::error::Error>> {
    use rustorch::gpu::cuda_kernels::{cuda_elementwise_add_f32, CudaKernelExecutor};

    println!("=== CUDA Specific Demo ===");

    if let Ok(_executor) = CudaKernelExecutor::new(0) {
        let size = 1024;
        let a = vec![1.0f32; size];
        let b = vec![2.0f32; size];
        let mut c = vec![0.0f32; size];

        let start_time = std::time::Instant::now();
        cuda_elementwise_add_f32(&a, &b, &mut c)?;
        let elapsed = start_time.elapsed();

        let correct = c.iter().all(|&x| (x - 3.0).abs() < 1e-6);

        println!(
            "  CUDA Direct Call: {} ({:.2}ms)",
            if correct { "" } else { "" },
            elapsed.as_secs_f64() * 1000.0
        );
    } else {
        println!("  CUDA not available");
    }

    println!();
    Ok(())
}

#[cfg(feature = "metal")]
fn demo_metal_specific() -> Result<(), Box<dyn std::error::Error>> {
    use rustorch::gpu::metal_kernels::{metal_elementwise_add_f32, MetalKernelExecutor};

    println!("=== Metal Specific Demo ===");

    if let Ok(_executor) = MetalKernelExecutor::new() {
        let size = 1024;
        let a = vec![1.0f32; size];
        let b = vec![2.0f32; size];
        let mut c = vec![0.0f32; size];

        let start_time = std::time::Instant::now();
        metal_elementwise_add_f32(&a, &b, &mut c)?;
        let elapsed = start_time.elapsed();

        let correct = c.iter().all(|&x| (x - 3.0).abs() < 1e-6);

        println!(
            "  Metal Direct Call: {} ({:.2}ms)",
            if correct { "" } else { "" },
            elapsed.as_secs_f64() * 1000.0
        );
    } else {
        println!("  Metal not available");
    }

    println!();
    Ok(())
}