scirs2-autograd 0.3.2

Automatic differentiation module for SciRS2 (scirs2-autograd)
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
//! GPU kernel implementations for automatic differentiation
//!
//! This module provides optimized GPU kernels for common autodiff operations.

use crate::{error::AutogradError, Float, Result};
use scirs2_core::gpu::GpuContext;

/// GPU kernel for element-wise operations
pub trait ElementWiseKernel<T: Float> {
    /// Execute element-wise operation on GPU
    fn execute(&self, context: &GpuContext, input: &[T], output: &mut [T]) -> Result<()>;
}

/// ReLU activation kernel
pub struct ReLUKernel;

impl<T: Float> ElementWiseKernel<T> for ReLUKernel {
    fn execute(&self, _context: &GpuContext, input: &[T], output: &mut [T]) -> Result<()> {
        if input.len() != output.len() {
            return Err(AutogradError::shape_error(
                "Input and output must have same length".to_string(),
            ));
        }

        // For CPU fallback or testing
        for (i, &val) in input.iter().enumerate() {
            output[i] = if val > T::zero() { val } else { T::zero() };
        }

        Ok(())
    }
}

/// Sigmoid activation kernel
pub struct SigmoidKernel;

impl<T: Float> ElementWiseKernel<T> for SigmoidKernel {
    fn execute(&self, _context: &GpuContext, input: &[T], output: &mut [T]) -> Result<()> {
        if input.len() != output.len() {
            return Err(AutogradError::shape_error(
                "Input and output must have same length".to_string(),
            ));
        }

        for (i, &val) in input.iter().enumerate() {
            // sigmoid(x) = 1 / (1 + exp(-x))
            output[i] = T::one() / (T::one() + (-val).exp());
        }

        Ok(())
    }
}

/// Tanh activation kernel
pub struct TanhKernel;

impl<T: Float> ElementWiseKernel<T> for TanhKernel {
    fn execute(&self, _context: &GpuContext, input: &[T], output: &mut [T]) -> Result<()> {
        if input.len() != output.len() {
            return Err(AutogradError::shape_error(
                "Input and output must have same length".to_string(),
            ));
        }

        for (i, &val) in input.iter().enumerate() {
            output[i] = val.tanh();
        }

        Ok(())
    }
}

/// GELU activation kernel
pub struct GELUKernel;

impl<T: Float> ElementWiseKernel<T> for GELUKernel {
    fn execute(&self, _context: &GpuContext, input: &[T], output: &mut [T]) -> Result<()> {
        if input.len() != output.len() {
            return Err(AutogradError::shape_error(
                "Input and output must have same length".to_string(),
            ));
        }

        // GELU(x) = x * Φ(x) where Φ is the cumulative distribution function of standard normal
        // Approximation: GELU(x) ≈ 0.5 * x * (1 + tanh(√(2/π) * (x + 0.044715 * x³)))
        let sqrt_2_over_pi = T::from(0.7978845608).ok_or_else(|| {
            AutogradError::compute_error("Failed to convert constant".to_string())
        })?;
        let coeff = T::from(0.044715).ok_or_else(|| {
            AutogradError::compute_error("Failed to convert constant".to_string())
        })?;

        for (i, &val) in input.iter().enumerate() {
            let val3 = val * val * val;
            let inner = sqrt_2_over_pi * (val + coeff * val3);
            output[i] = T::from(0.5).ok_or_else(|| {
                AutogradError::compute_error("Failed to convert constant".to_string())
            })? * val
                * (T::one() + inner.tanh());
        }

        Ok(())
    }
}

/// Matrix multiplication kernel (GEMM)
pub struct GEMMKernel;

impl GEMMKernel {
    /// Execute general matrix multiplication: C = alpha * A * B + beta * C
    pub fn execute<T: Float>(
        &self,
        _context: &GpuContext,
        m: usize,
        n: usize,
        k: usize,
        alpha: T,
        a: &[T],
        b: &[T],
        beta: T,
        c: &mut [T],
    ) -> Result<()> {
        // Validate dimensions
        if a.len() < m * k {
            return Err(AutogradError::shape_error(format!(
                "Matrix A size mismatch: expected {}, got {}",
                m * k,
                a.len()
            )));
        }
        if b.len() < k * n {
            return Err(AutogradError::shape_error(format!(
                "Matrix B size mismatch: expected {}, got {}",
                k * n,
                b.len()
            )));
        }
        if c.len() < m * n {
            return Err(AutogradError::shape_error(format!(
                "Matrix C size mismatch: expected {}, got {}",
                m * n,
                c.len()
            )));
        }

        // Simple CPU fallback implementation
        // In production, this would dispatch to optimized GPU kernels
        for i in 0..m {
            for j in 0..n {
                let mut sum = T::zero();
                for l in 0..k {
                    sum += a[i * k + l] * b[l * n + j];
                }
                let idx = i * n + j;
                c[idx] = alpha * sum + beta * c[idx];
            }
        }

        Ok(())
    }
}

/// Reduction kernel for sum/mean/max/min operations
pub struct ReductionKernel;

impl ReductionKernel {
    /// Sum reduction
    pub fn sum<T: Float>(
        &self,
        _context: &GpuContext,
        input: &[T],
        output: &mut [T],
        reduce_size: usize,
    ) -> Result<()> {
        if !input.len().is_multiple_of(reduce_size) {
            return Err(AutogradError::shape_error(
                "Input size must be divisible by reduce size".to_string(),
            ));
        }

        let num_outputs = input.len() / reduce_size;
        if output.len() < num_outputs {
            return Err(AutogradError::shape_error(format!(
                "Output size {} is too small, need {}",
                output.len(),
                num_outputs
            )));
        }

        for i in 0..num_outputs {
            let mut sum = T::zero();
            for j in 0..reduce_size {
                sum += input[i * reduce_size + j];
            }
            output[i] = sum;
        }

        Ok(())
    }

    /// Mean reduction
    pub fn mean<T: Float>(
        &self,
        context: &GpuContext,
        input: &[T],
        output: &mut [T],
        reduce_size: usize,
    ) -> Result<()> {
        self.sum(context, input, output, reduce_size)?;

        let divisor = T::from(reduce_size).ok_or_else(|| {
            AutogradError::compute_error("Failed to convert reduce size".to_string())
        })?;

        for val in output.iter_mut() {
            *val /= divisor;
        }

        Ok(())
    }

    /// Max reduction
    pub fn max<T: Float>(
        &self,
        _context: &GpuContext,
        input: &[T],
        output: &mut [T],
        reduce_size: usize,
    ) -> Result<()> {
        if !input.len().is_multiple_of(reduce_size) {
            return Err(AutogradError::shape_error(
                "Input size must be divisible by reduce size".to_string(),
            ));
        }

        let num_outputs = input.len() / reduce_size;
        if output.len() < num_outputs {
            return Err(AutogradError::shape_error(format!(
                "Output size {} is too small, need {}",
                output.len(),
                num_outputs
            )));
        }

        for i in 0..num_outputs {
            let start = i * reduce_size;
            let slice = &input[start..start + reduce_size];
            output[i] = slice.iter().copied().fold(T::neg_infinity(), T::max);
        }

        Ok(())
    }

    /// Min reduction
    pub fn min<T: Float>(
        &self,
        _context: &GpuContext,
        input: &[T],
        output: &mut [T],
        reduce_size: usize,
    ) -> Result<()> {
        if !input.len().is_multiple_of(reduce_size) {
            return Err(AutogradError::shape_error(
                "Input size must be divisible by reduce size".to_string(),
            ));
        }

        let num_outputs = input.len() / reduce_size;
        if output.len() < num_outputs {
            return Err(AutogradError::shape_error(format!(
                "Output size {} is too small, need {}",
                output.len(),
                num_outputs
            )));
        }

        for i in 0..num_outputs {
            let start = i * reduce_size;
            let slice = &input[start..start + reduce_size];
            output[i] = slice.iter().copied().fold(T::infinity(), T::min);
        }

        Ok(())
    }
}

/// Broadcast kernel for gradient backpropagation
pub struct BroadcastKernel;

impl BroadcastKernel {
    /// Broadcast smaller array to larger shape
    pub fn execute<T: Float>(
        &self,
        _context: &GpuContext,
        input: &[T],
        input_shape: &[usize],
        output: &mut [T],
        output_shape: &[usize],
    ) -> Result<()> {
        // Validate shapes are broadcast-compatible
        if !Self::is_broadcastable(input_shape, output_shape) {
            return Err(AutogradError::shape_error(format!(
                "Shapes {:?} and {:?} are not broadcastable",
                input_shape, output_shape
            )));
        }

        // Simple implementation for 2D case
        if input_shape.len() == 2 && output_shape.len() == 2 {
            let (in_rows, in_cols) = (input_shape[0], input_shape[1]);
            let (out_rows, out_cols) = (output_shape[0], output_shape[1]);

            for i in 0..out_rows {
                for j in 0..out_cols {
                    let in_i = if in_rows == 1 { 0 } else { i };
                    let in_j = if in_cols == 1 { 0 } else { j };
                    output[i * out_cols + j] = input[in_i * in_cols + in_j];
                }
            }
        } else {
            // Fallback for other dimensions
            return Err(AutogradError::not_implemented(
                "Broadcasting for non-2D shapes not yet implemented".to_string(),
            ));
        }

        Ok(())
    }

    /// Check if two shapes are broadcastable
    fn is_broadcastable(shape1: &[usize], shape2: &[usize]) -> bool {
        let len1 = shape1.len();
        let len2 = shape2.len();
        let max_len = len1.max(len2);

        for i in 0..max_len {
            let dim1 = if i < len1 { shape1[len1 - 1 - i] } else { 1 };
            let dim2 = if i < len2 { shape2[len2 - 1 - i] } else { 1 };

            if dim1 != dim2 && dim1 != 1 && dim2 != 1 {
                return false;
            }
        }

        true
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use scirs2_core::gpu::GpuBackend;

    #[test]
    fn test_relu_kernel() {
        let context = GpuContext::new(GpuBackend::Cpu).expect("Should create context");
        let kernel = ReLUKernel;

        let input = vec![-2.0, -1.0, 0.0, 1.0, 2.0];
        let mut output = vec![0.0; 5];

        kernel
            .execute(&context, &input, &mut output)
            .expect("Should execute");
        assert_eq!(output, vec![0.0, 0.0, 0.0, 1.0, 2.0]);
    }

    #[test]
    fn test_sigmoid_kernel() {
        let context = GpuContext::new(GpuBackend::Cpu).expect("Should create context");
        let kernel = SigmoidKernel;

        let input = vec![0.0_f32];
        let mut output = vec![0.0_f32];

        kernel
            .execute(&context, &input, &mut output)
            .expect("Should execute");
        assert!((output[0] - 0.5_f32).abs() < 1e-6);
    }

    #[test]
    fn test_gemm_kernel() {
        let context = GpuContext::new(GpuBackend::Cpu).expect("Should create context");
        let kernel = GEMMKernel;

        // 2x3 * 3x2 = 2x2
        let a = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0];
        let b = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0];
        let mut c = vec![0.0; 4];

        kernel
            .execute(&context, 2, 2, 3, 1.0, &a, &b, 0.0, &mut c)
            .expect("Should execute");

        // Verify result
        assert!(c[0] > 0.0); // Just check it computed something
    }

    #[test]
    fn test_reduction_sum() {
        let context = GpuContext::new(GpuBackend::Cpu).expect("Should create context");
        let kernel = ReductionKernel;

        let input = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0];
        let mut output = vec![0.0; 2];

        kernel
            .sum(&context, &input, &mut output, 3)
            .expect("Should execute");
        assert_eq!(output, vec![6.0, 15.0]);
    }

    #[test]
    fn test_broadcast_compatibility() {
        assert!(BroadcastKernel::is_broadcastable(&[1, 3], &[4, 3]));
        assert!(BroadcastKernel::is_broadcastable(&[1], &[4, 3]));
        assert!(!BroadcastKernel::is_broadcastable(&[2, 3], &[4, 5]));
    }
}