tenflowers-core 0.1.1

Core tensor operations and execution engine for TenfloweRS
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
/// GPU Reduction Kernels for TenfloweRS
///
/// This module implements high-performance GPU reduction operations using
/// tree-based and warp-level primitives for maximum efficiency.
use crate::{Result, Shape, Tensor, TensorError};

/// Reduction operation type
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReductionOp {
    /// Sum reduction
    Sum,
    /// Product reduction
    Prod,
    /// Maximum reduction
    Max,
    /// Minimum reduction
    Min,
    /// Mean (average) reduction
    Mean,
    /// Variance reduction
    Variance,
    /// Standard deviation reduction
    StdDev,
    /// L1 norm reduction
    L1Norm,
    /// L2 norm reduction
    L2Norm,
    /// Any (logical OR) reduction
    Any,
    /// All (logical AND) reduction
    All,
}

impl ReductionOp {
    /// Get the name of this reduction operation
    pub fn name(&self) -> &'static str {
        match self {
            Self::Sum => "sum",
            Self::Prod => "prod",
            Self::Max => "max",
            Self::Min => "min",
            Self::Mean => "mean",
            Self::Variance => "var",
            Self::StdDev => "std",
            Self::L1Norm => "l1_norm",
            Self::L2Norm => "l2_norm",
            Self::Any => "any",
            Self::All => "all",
        }
    }

    /// Get the identity value for this reduction
    pub fn identity_f32(&self) -> f32 {
        match self {
            Self::Sum | Self::Mean | Self::L1Norm | Self::L2Norm => 0.0,
            Self::Prod => 1.0,
            Self::Max => f32::NEG_INFINITY,
            Self::Min => f32::INFINITY,
            Self::Any => 0.0,
            Self::All => 1.0,
            Self::Variance | Self::StdDev => 0.0,
        }
    }

    /// Check if this reduction requires two passes
    pub fn requires_two_passes(&self) -> bool {
        matches!(self, Self::Variance | Self::StdDev | Self::Mean)
    }
}

/// GPU reduction configuration
#[derive(Debug, Clone)]
pub struct GpuReductionConfig {
    /// Block size for reduction
    pub block_size: usize,
    /// Whether to use shared memory
    pub use_shared_memory: bool,
    /// Whether to use warp-level primitives
    pub use_warp_primitives: bool,
    /// Maximum workgroup size
    pub max_workgroup_size: usize,
}

impl Default for GpuReductionConfig {
    fn default() -> Self {
        Self {
            block_size: 256,
            use_shared_memory: true,
            use_warp_primitives: true,
            max_workgroup_size: 1024,
        }
    }
}

/// Perform GPU reduction along an axis
#[cfg(feature = "gpu")]
pub fn gpu_reduce_axis<T>(
    tensor: &Tensor<T>,
    axis: usize,
    op: ReductionOp,
    keep_dims: bool,
) -> Result<Tensor<T>>
where
    T: scirs2_core::num_traits::Float
        + Default
        + bytemuck::Pod
        + Send
        + Sync
        + 'static
        + scirs2_core::num_traits::FromPrimitive
        + scirs2_core::num_traits::ops::mul_add::MulAdd
        + scirs2_core::ndarray::ScalarOperand,
{
    let shape = tensor.shape();
    if axis >= shape.rank() {
        return Err(TensorError::InvalidAxis {
            operation: "reduce".to_string(),
            axis: axis as i32,
            ndim: shape.rank(),
            context: None,
        });
    }

    // Check if tensor is on GPU
    if !tensor.device().is_gpu() {
        // CPU fallback
        return super::statistical::reduce_axis_cpu(tensor, axis, op, keep_dims);
    }

    // Use GPU execution
    let gpu_op = super::gpu_execution::GpuReductionOp::from(op);
    let result = super::gpu_execution::execute_gpu_reduction(tensor, axis, gpu_op, keep_dims)?;

    // Handle special cases (StdDev needs additional sqrt)
    match op {
        ReductionOp::StdDev => {
            // StdDev = sqrt(Variance)
            result.sqrt()
        }
        ReductionOp::L2Norm => {
            // L2Norm = sqrt(sum of squares)
            // Note: This requires preprocessing (abs values before reduction)
            // For now, use CPU fallback for L1/L2 norms
            super::statistical::reduce_axis_cpu(tensor, axis, op, keep_dims)
        }
        ReductionOp::L1Norm => {
            // L1Norm = sum of abs values
            // Note: This requires preprocessing (abs values before reduction)
            super::statistical::reduce_axis_cpu(tensor, axis, op, keep_dims)
        }
        _ => Ok(result),
    }
}

/// Perform GPU full reduction (reduce all elements)
#[cfg(feature = "gpu")]
pub fn gpu_reduce_all<T>(tensor: &Tensor<T>, op: ReductionOp) -> Result<T>
where
    T: scirs2_core::num_traits::Float
        + Default
        + bytemuck::Pod
        + Send
        + Sync
        + 'static
        + scirs2_core::num_traits::FromPrimitive
        + scirs2_core::num_traits::ops::mul_add::MulAdd
        + scirs2_core::ndarray::ScalarOperand,
{
    // Check if tensor is on GPU
    if !tensor.device().is_gpu() {
        // CPU fallback
        return super::statistical::reduce_all_cpu(tensor, op);
    }

    // For full reduction, reduce along all axes sequentially
    // Start with axis 0, then reduce the result along axis 0 again (since dimensions shift)
    let mut result = tensor.clone();
    let rank = tensor.shape().rank();

    for _ in 0..rank {
        result = gpu_reduce_axis(&result, 0, op, false)?;
    }

    // Extract scalar value
    let data = result.data();
    if data.is_empty() {
        return Err(TensorError::invalid_operation_simple(
            "Reduction produced empty result".to_string(),
        ));
    }
    Ok(data[0])
}

/// GPU sum reduction along axis
pub fn gpu_sum_axis<T>(tensor: &Tensor<T>, axis: usize, keep_dims: bool) -> Result<Tensor<T>>
where
    T: scirs2_core::num_traits::Float
        + Default
        + bytemuck::Pod
        + Send
        + Sync
        + 'static
        + scirs2_core::num_traits::FromPrimitive
        + scirs2_core::num_traits::ops::mul_add::MulAdd
        + scirs2_core::ndarray::ScalarOperand,
{
    #[cfg(feature = "gpu")]
    {
        if tensor.device().is_gpu() {
            return gpu_reduce_axis(tensor, axis, ReductionOp::Sum, keep_dims);
        }
    }

    // CPU fallback
    super::statistical::reduce_axis_cpu(tensor, axis, ReductionOp::Sum, keep_dims)
}

/// GPU mean reduction along axis
pub fn gpu_mean_axis<T>(tensor: &Tensor<T>, axis: usize, keep_dims: bool) -> Result<Tensor<T>>
where
    T: scirs2_core::num_traits::Float
        + Default
        + bytemuck::Pod
        + Send
        + Sync
        + 'static
        + scirs2_core::num_traits::FromPrimitive
        + scirs2_core::num_traits::ops::mul_add::MulAdd
        + scirs2_core::ndarray::ScalarOperand,
{
    #[cfg(feature = "gpu")]
    {
        if tensor.device().is_gpu() {
            return gpu_reduce_axis(tensor, axis, ReductionOp::Mean, keep_dims);
        }
    }

    // CPU fallback
    super::statistical::reduce_axis_cpu(tensor, axis, ReductionOp::Mean, keep_dims)
}

/// GPU max reduction along axis
pub fn gpu_max_axis<T>(tensor: &Tensor<T>, axis: usize, keep_dims: bool) -> Result<Tensor<T>>
where
    T: scirs2_core::num_traits::Float
        + Default
        + bytemuck::Pod
        + Send
        + Sync
        + 'static
        + scirs2_core::num_traits::FromPrimitive
        + scirs2_core::num_traits::ops::mul_add::MulAdd
        + scirs2_core::ndarray::ScalarOperand,
{
    #[cfg(feature = "gpu")]
    {
        if tensor.device().is_gpu() {
            return gpu_reduce_axis(tensor, axis, ReductionOp::Max, keep_dims);
        }
    }

    // CPU fallback
    super::statistical::reduce_axis_cpu(tensor, axis, ReductionOp::Max, keep_dims)
}

/// GPU min reduction along axis
pub fn gpu_min_axis<T>(tensor: &Tensor<T>, axis: usize, keep_dims: bool) -> Result<Tensor<T>>
where
    T: scirs2_core::num_traits::Float
        + Default
        + bytemuck::Pod
        + Send
        + Sync
        + 'static
        + scirs2_core::num_traits::FromPrimitive
        + scirs2_core::num_traits::ops::mul_add::MulAdd
        + scirs2_core::ndarray::ScalarOperand,
{
    #[cfg(feature = "gpu")]
    {
        if tensor.device().is_gpu() {
            return gpu_reduce_axis(tensor, axis, ReductionOp::Min, keep_dims);
        }
    }

    // CPU fallback
    super::statistical::reduce_axis_cpu(tensor, axis, ReductionOp::Min, keep_dims)
}

/// GPU variance reduction along axis
pub fn gpu_var_axis<T>(tensor: &Tensor<T>, axis: usize, keep_dims: bool) -> Result<Tensor<T>>
where
    T: scirs2_core::num_traits::Float
        + Default
        + bytemuck::Pod
        + Send
        + Sync
        + 'static
        + scirs2_core::num_traits::FromPrimitive
        + scirs2_core::num_traits::ops::mul_add::MulAdd
        + scirs2_core::ndarray::ScalarOperand,
{
    #[cfg(feature = "gpu")]
    {
        if tensor.device().is_gpu() {
            return gpu_reduce_axis(tensor, axis, ReductionOp::Variance, keep_dims);
        }
    }

    // CPU fallback
    super::statistical::reduce_axis_cpu(tensor, axis, ReductionOp::Variance, keep_dims)
}

/// GPU standard deviation reduction along axis
pub fn gpu_std_axis<T>(tensor: &Tensor<T>, axis: usize, keep_dims: bool) -> Result<Tensor<T>>
where
    T: scirs2_core::num_traits::Float
        + Default
        + bytemuck::Pod
        + Send
        + Sync
        + 'static
        + scirs2_core::num_traits::FromPrimitive
        + scirs2_core::num_traits::ops::mul_add::MulAdd
        + scirs2_core::ndarray::ScalarOperand,
{
    #[cfg(feature = "gpu")]
    {
        if tensor.device().is_gpu() {
            return gpu_reduce_axis(tensor, axis, ReductionOp::StdDev, keep_dims);
        }
    }

    // CPU fallback
    super::statistical::reduce_axis_cpu(tensor, axis, ReductionOp::StdDev, keep_dims)
}

/// GPU L1 norm along axis
pub fn gpu_l1_norm_axis<T>(tensor: &Tensor<T>, axis: usize, keep_dims: bool) -> Result<Tensor<T>>
where
    T: scirs2_core::num_traits::Float
        + Default
        + bytemuck::Pod
        + Send
        + Sync
        + 'static
        + scirs2_core::num_traits::FromPrimitive
        + scirs2_core::num_traits::ops::mul_add::MulAdd
        + scirs2_core::ndarray::ScalarOperand,
{
    #[cfg(feature = "gpu")]
    {
        if tensor.device().is_gpu() {
            return gpu_reduce_axis(tensor, axis, ReductionOp::L1Norm, keep_dims);
        }
    }

    // CPU fallback
    super::statistical::reduce_axis_cpu(tensor, axis, ReductionOp::L1Norm, keep_dims)
}

/// GPU L2 norm along axis
pub fn gpu_l2_norm_axis<T>(tensor: &Tensor<T>, axis: usize, keep_dims: bool) -> Result<Tensor<T>>
where
    T: scirs2_core::num_traits::Float
        + Default
        + bytemuck::Pod
        + Send
        + Sync
        + 'static
        + scirs2_core::num_traits::FromPrimitive
        + scirs2_core::num_traits::ops::mul_add::MulAdd
        + scirs2_core::ndarray::ScalarOperand,
{
    #[cfg(feature = "gpu")]
    {
        if tensor.device().is_gpu() {
            return gpu_reduce_axis(tensor, axis, ReductionOp::L2Norm, keep_dims);
        }
    }

    // CPU fallback
    super::statistical::reduce_axis_cpu(tensor, axis, ReductionOp::L2Norm, keep_dims)
}

/// Tree reduction implementation for GPU
/// This uses a logarithmic reduction tree for efficiency
#[cfg(feature = "gpu")]
pub struct TreeReduction {
    config: GpuReductionConfig,
}

#[cfg(feature = "gpu")]
impl TreeReduction {
    /// Create a new tree reduction
    pub fn new(config: GpuReductionConfig) -> Self {
        Self { config }
    }

    /// Compute the number of reduction steps needed
    pub fn num_steps(&self, input_size: usize) -> usize {
        (input_size as f64).log2().ceil() as usize
    }

    /// Compute the workgroup size for reduction
    pub fn workgroup_size(&self, input_size: usize) -> usize {
        self.config
            .block_size
            .min(input_size)
            .min(self.config.max_workgroup_size)
    }
}

/// Warp-level reduction primitives
#[cfg(feature = "gpu")]
pub struct WarpReduction {
    warp_size: usize,
}

#[cfg(feature = "gpu")]
impl WarpReduction {
    /// Create a new warp reduction (typically 32 threads per warp)
    pub fn new() -> Self {
        Self { warp_size: 32 }
    }

    /// Get warp size
    pub fn warp_size(&self) -> usize {
        self.warp_size
    }

    /// Check if warp primitives can be used for this size
    pub fn can_use_warp_primitives(&self, size: usize) -> bool {
        size >= self.warp_size
    }
}

#[cfg(feature = "gpu")]
impl Default for WarpReduction {
    fn default() -> Self {
        Self::new()
    }
}

/// Multi-stage reduction for very large tensors
pub struct MultiStageReduction {
    /// Number of elements per stage
    pub stage_size: usize,
    /// Number of stages
    pub num_stages: usize,
}

impl MultiStageReduction {
    /// Create a new multi-stage reduction
    pub fn new(total_elements: usize, max_stage_size: usize) -> Self {
        let num_stages = (total_elements + max_stage_size - 1) / max_stage_size;
        Self {
            stage_size: max_stage_size,
            num_stages,
        }
    }

    /// Get the size of a specific stage
    pub fn stage_size_for(&self, stage: usize) -> usize {
        if stage < self.num_stages - 1 {
            self.stage_size
        } else {
            // Last stage might be smaller
            self.stage_size
        }
    }
}

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

    #[test]
    fn test_reduction_op_identity() {
        assert_eq!(ReductionOp::Sum.identity_f32(), 0.0);
        assert_eq!(ReductionOp::Prod.identity_f32(), 1.0);
        assert_eq!(ReductionOp::Max.identity_f32(), f32::NEG_INFINITY);
        assert_eq!(ReductionOp::Min.identity_f32(), f32::INFINITY);
    }

    #[test]
    fn test_reduction_op_two_passes() {
        assert!(ReductionOp::Variance.requires_two_passes());
        assert!(ReductionOp::StdDev.requires_two_passes());
        assert!(!ReductionOp::Sum.requires_two_passes());
    }

    #[test]
    fn test_multi_stage_reduction() {
        let reduction = MultiStageReduction::new(10_000_000, 1_000_000);
        assert_eq!(reduction.num_stages, 10);
        assert_eq!(reduction.stage_size, 1_000_000);
    }

    #[cfg(feature = "gpu")]
    #[test]
    fn test_tree_reduction() {
        let config = GpuReductionConfig::default();
        let tree = TreeReduction::new(config);

        assert_eq!(tree.num_steps(1024), 10); // log2(1024) = 10
        assert_eq!(tree.num_steps(256), 8); // log2(256) = 8
    }

    #[cfg(feature = "gpu")]
    #[test]
    fn test_warp_reduction() {
        let warp = WarpReduction::new();
        assert_eq!(warp.warp_size(), 32);
        assert!(warp.can_use_warp_primitives(64));
        assert!(warp.can_use_warp_primitives(32));
        assert!(!warp.can_use_warp_primitives(16));
    }
}