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
//! Fractional pooling operations for 2D tensors
//!
//! Fractional pooling uses stochastic or deterministic sampling to achieve
//! flexible downsampling ratios that aren't constrained to integer factors.

use crate::tensor::TensorStorage;
use crate::{Result, Tensor, TensorError};
use scirs2_core::numeric::{Float, FromPrimitive, Zero};
use scirs2_core::random::{Random, Rng};
use scirs2_core::RngExt;

/// Fractional max pooling 2D operation
/// Uses stochastic or deterministic fractional scaling
pub fn fractional_max_pool2d<T>(
    input: &Tensor<T>,
    pooling_ratio: (f32, f32),
    random_samples: Option<&Tensor<T>>,
) -> Result<Tensor<T>>
where
    T: Clone
        + Default
        + Zero
        + PartialOrd
        + Float
        + FromPrimitive
        + Send
        + Sync
        + 'static
        + bytemuck::Pod
        + bytemuck::Zeroable,
{
    match &input.storage {
        TensorStorage::Cpu(_input_arr) => {
            fractional_max_pool2d_cpu(input, pooling_ratio, random_samples)
        }
        #[cfg(feature = "gpu")]
        TensorStorage::Gpu(_gpu_buffer) => {
            fractional_max_pool2d_gpu(input, pooling_ratio, random_samples)
        }
    }
}

/// Fractional average pooling 2D operation
/// Uses stochastic or deterministic fractional scaling
pub fn fractional_avg_pool2d<T>(
    input: &Tensor<T>,
    pooling_ratio: (f32, f32),
    random_samples: Option<&Tensor<T>>,
) -> Result<Tensor<T>>
where
    T: Clone
        + Default
        + Zero
        + Float
        + FromPrimitive
        + Send
        + Sync
        + 'static
        + bytemuck::Pod
        + bytemuck::Zeroable,
{
    match &input.storage {
        TensorStorage::Cpu(_input_arr) => {
            fractional_avg_pool2d_cpu(input, pooling_ratio, random_samples)
        }
        #[cfg(feature = "gpu")]
        TensorStorage::Gpu(_gpu_buffer) => {
            fractional_avg_pool2d_gpu(input, pooling_ratio, random_samples)
        }
    }
}

// CPU implementations

fn fractional_max_pool2d_cpu<T>(
    input: &Tensor<T>,
    pooling_ratio: (f32, f32),
    random_samples: Option<&Tensor<T>>,
) -> Result<Tensor<T>>
where
    T: Clone + Default + Zero + PartialOrd + Float + FromPrimitive + Send + Sync + 'static,
{
    let shape = input.shape();
    if shape.rank() != 4 {
        return Err(TensorError::invalid_shape_simple(format!(
            "FractionalMaxPool2D expects 4D input, got {}D",
            shape.rank()
        )));
    }

    let batch_size = shape.dims()[0];
    let channels = shape.dims()[1];
    let input_height = shape.dims()[2];
    let input_width = shape.dims()[3];

    let output_height = (input_height as f32 * pooling_ratio.0) as usize;
    let output_width = (input_width as f32 * pooling_ratio.1) as usize;

    // Generate pooling regions
    let (row_splits, col_splits) = if let Some(samples) = random_samples {
        // Use provided random samples for deterministic behavior
        generate_pooling_regions_deterministic(
            input_height,
            input_width,
            output_height,
            output_width,
            samples,
        )?
    } else {
        // Generate random pooling regions
        generate_pooling_regions_random(input_height, input_width, output_height, output_width)?
    };

    let mut output_data = vec![T::zero(); batch_size * channels * output_height * output_width];

    for b in 0..batch_size {
        for c in 0..channels {
            for oh in 0..output_height {
                for ow in 0..output_width {
                    let h_start = row_splits[oh];
                    let h_end = row_splits[oh + 1];
                    let w_start = col_splits[ow];
                    let w_end = col_splits[ow + 1];

                    let mut max_val: Option<T> = None;
                    for h in h_start..h_end {
                        for w in w_start..w_end {
                            if let Some(val) = input.get(&[b, c, h, w]) {
                                max_val = match max_val {
                                    None => Some(val),
                                    Some(current_max) => {
                                        if val > current_max {
                                            Some(val)
                                        } else {
                                            Some(current_max)
                                        }
                                    }
                                };
                            }
                        }
                    }

                    let out_idx = b * channels * output_height * output_width
                        + c * output_height * output_width
                        + oh * output_width
                        + ow;
                    output_data[out_idx] = max_val.unwrap_or_else(T::zero);
                }
            }
        }
    }

    Tensor::from_vec(
        output_data,
        &[batch_size, channels, output_height, output_width],
    )
}

fn fractional_avg_pool2d_cpu<T>(
    input: &Tensor<T>,
    pooling_ratio: (f32, f32),
    random_samples: Option<&Tensor<T>>,
) -> Result<Tensor<T>>
where
    T: Clone + Default + Zero + Float + FromPrimitive + Send + Sync + 'static,
{
    let shape = input.shape();
    if shape.rank() != 4 {
        return Err(TensorError::invalid_shape_simple(format!(
            "FractionalAvgPool2D expects 4D input, got {}D",
            shape.rank()
        )));
    }

    let batch_size = shape.dims()[0];
    let channels = shape.dims()[1];
    let input_height = shape.dims()[2];
    let input_width = shape.dims()[3];

    let output_height = (input_height as f32 * pooling_ratio.0) as usize;
    let output_width = (input_width as f32 * pooling_ratio.1) as usize;

    // Generate pooling regions
    let (row_splits, col_splits) = if let Some(samples) = random_samples {
        // Use provided random samples for deterministic behavior
        generate_pooling_regions_deterministic(
            input_height,
            input_width,
            output_height,
            output_width,
            samples,
        )?
    } else {
        // Generate random pooling regions
        generate_pooling_regions_random(input_height, input_width, output_height, output_width)?
    };

    let mut output_data = vec![T::zero(); batch_size * channels * output_height * output_width];

    for b in 0..batch_size {
        for c in 0..channels {
            for oh in 0..output_height {
                for ow in 0..output_width {
                    let h_start = row_splits[oh];
                    let h_end = row_splits[oh + 1];
                    let w_start = col_splits[ow];
                    let w_end = col_splits[ow + 1];

                    let mut sum = T::zero();
                    let mut count = 0;

                    for h in h_start..h_end {
                        for w in w_start..w_end {
                            if let Some(val) = input.get(&[b, c, h, w]) {
                                sum = sum + val;
                                count += 1;
                            }
                        }
                    }

                    let out_idx = b * channels * output_height * output_width
                        + c * output_height * output_width
                        + oh * output_width
                        + ow;
                    if count > 0 {
                        output_data[out_idx] = sum
                            / T::from(count).expect("count must be convertible to tensor dtype");
                    } else {
                        output_data[out_idx] = T::zero();
                    }
                }
            }
        }
    }

    Tensor::from_vec(
        output_data,
        &[batch_size, channels, output_height, output_width],
    )
}

// Helper functions for generating pooling regions

/// Generate random pooling regions for fractional pooling
fn generate_pooling_regions_random(
    input_height: usize,
    input_width: usize,
    output_height: usize,
    output_width: usize,
) -> Result<(Vec<usize>, Vec<usize>)> {
    let mut rng = scirs2_core::random::rng();

    // Generate random split points for rows
    let mut row_splits = vec![0];
    for _ in 0..output_height {
        let last_split = *row_splits.last().expect("collection should not be empty");
        let remaining_height = input_height - last_split;
        let remaining_outputs = output_height - (row_splits.len() - 1);

        if remaining_outputs == 0 {
            break;
        }

        let min_step = remaining_height / remaining_outputs;
        let max_step = if remaining_outputs == 1 {
            remaining_height
        } else {
            std::cmp::min(remaining_height, min_step * 2)
        };

        let step = if min_step == max_step {
            min_step
        } else {
            rng.random_range(min_step..=max_step)
        };

        row_splits.push(last_split + step);
    }
    row_splits.push(input_height);

    // Generate random split points for columns
    let mut col_splits = vec![0];
    for _ in 0..output_width {
        let last_split = *col_splits.last().expect("collection should not be empty");
        let remaining_width = input_width - last_split;
        let remaining_outputs = output_width - (col_splits.len() - 1);

        if remaining_outputs == 0 {
            break;
        }

        let min_step = remaining_width / remaining_outputs;
        let max_step = if remaining_outputs == 1 {
            remaining_width
        } else {
            std::cmp::min(remaining_width, min_step * 2)
        };

        let step = if min_step == max_step {
            min_step
        } else {
            rng.random_range(min_step..=max_step)
        };

        col_splits.push(last_split + step);
    }
    col_splits.push(input_width);

    Ok((row_splits, col_splits))
}

/// Generate deterministic pooling regions for fractional pooling
fn generate_pooling_regions_deterministic<T>(
    input_height: usize,
    input_width: usize,
    output_height: usize,
    output_width: usize,
    random_samples: &Tensor<T>,
) -> Result<(Vec<usize>, Vec<usize>)>
where
    T: Clone + Float + FromPrimitive,
{
    // For deterministic fractional pooling, we use the provided random samples
    // to generate consistent pooling regions
    let samples = random_samples.as_slice().ok_or_else(|| {
        TensorError::device_error_simple("Cannot access random samples tensor data".to_string())
    })?;

    let expected_samples = output_height + output_width;
    if samples.len() < expected_samples {
        return Err(TensorError::invalid_shape_simple(format!(
            "Need at least {} random samples, got {}",
            expected_samples,
            samples.len()
        )));
    }

    // Generate deterministic split points for rows
    let mut row_splits = vec![0];
    #[allow(clippy::needless_range_loop)]
    for i in 0..output_height {
        let last_split = *row_splits.last().expect("collection should not be empty");
        let remaining_height = input_height - last_split;
        let remaining_outputs = output_height - (row_splits.len() - 1);

        if remaining_outputs == 0 {
            break;
        }

        let min_step = remaining_height / remaining_outputs;
        let max_step = if remaining_outputs == 1 {
            remaining_height
        } else {
            std::cmp::min(remaining_height, min_step * 2)
        };

        let random_val = samples[i].to_f32().unwrap_or(0.5);
        let step = min_step + ((max_step - min_step) as f32 * random_val) as usize;
        row_splits.push(last_split + step);
    }
    row_splits.push(input_height);

    // Generate deterministic split points for columns
    let mut col_splits = vec![0];
    #[allow(clippy::needless_range_loop)]
    for i in 0..output_width {
        let last_split = *col_splits.last().expect("collection should not be empty");
        let remaining_width = input_width - last_split;
        let remaining_outputs = output_width - (col_splits.len() - 1);

        if remaining_outputs == 0 {
            break;
        }

        let min_step = remaining_width / remaining_outputs;
        let max_step = if remaining_outputs == 1 {
            remaining_width
        } else {
            std::cmp::min(remaining_width, min_step * 2)
        };

        let random_val = samples[output_height + i].to_f32().unwrap_or(0.5);
        let step = min_step + ((max_step - min_step) as f32 * random_val) as usize;
        col_splits.push(last_split + step);
    }
    col_splits.push(input_width);

    Ok((row_splits, col_splits))
}

// GPU implementations

#[cfg(feature = "gpu")]
fn fractional_max_pool2d_gpu<T>(
    input: &Tensor<T>,
    pooling_ratio: (f32, f32),
    random_samples: Option<&Tensor<T>>,
) -> Result<Tensor<T>>
where
    T: Clone
        + Default
        + Zero
        + PartialOrd
        + Float
        + FromPrimitive
        + Send
        + Sync
        + 'static
        + bytemuck::Pod
        + bytemuck::Zeroable,
{
    if let TensorStorage::Gpu(gpu_buffer) = &input.storage {
        let input_shape = input.shape().dims();
        if input_shape.len() != 4 {
            return Err(TensorError::invalid_shape_simple(
                "Fractional max pool input must be 4D (NCHW format)".to_string(),
            ));
        }

        let batch_size = input_shape[0];
        let channels = input_shape[1];
        let input_height = input_shape[2];
        let input_width = input_shape[3];

        // Calculate output dimensions based on pooling ratio
        let output_height = (input_height as f32 * pooling_ratio.0).round() as usize;
        let output_width = (input_width as f32 * pooling_ratio.1).round() as usize;
        let output_shape = vec![batch_size, channels, output_height, output_width];

        let pooling_ratio_slice = &[pooling_ratio.0, pooling_ratio.1];
        let output_len = output_shape.iter().product();

        let result_gpu = crate::gpu::ops::execute_fractional_pooling_op(
            gpu_buffer,
            crate::gpu::ops::PoolingOp::FractionalMaxPool2D,
            pooling_ratio_slice,
            false, // pseudo_random
            false, // overlapping
            input_shape,
            output_len,
        )?;

        let mut result = Tensor::from_gpu_buffer(result_gpu, crate::Shape::new(output_shape));
        result.set_requires_grad(input.requires_grad());
        Ok(result)
    } else {
        // Fallback to CPU implementation for non-GPU tensors
        fractional_max_pool2d_cpu(input, pooling_ratio, random_samples)
    }
}

#[cfg(feature = "gpu")]
fn fractional_avg_pool2d_gpu<T>(
    input: &Tensor<T>,
    pooling_ratio: (f32, f32),
    random_samples: Option<&Tensor<T>>,
) -> Result<Tensor<T>>
where
    T: Clone
        + Default
        + Zero
        + Float
        + FromPrimitive
        + Send
        + Sync
        + 'static
        + bytemuck::Pod
        + bytemuck::Zeroable,
{
    if let TensorStorage::Gpu(gpu_buffer) = &input.storage {
        let input_shape = input.shape().dims();
        if input_shape.len() != 4 {
            return Err(TensorError::invalid_shape_simple(
                "Fractional avg pool input must be 4D (NCHW format)".to_string(),
            ));
        }

        let batch_size = input_shape[0];
        let channels = input_shape[1];
        let input_height = input_shape[2];
        let input_width = input_shape[3];

        // Calculate output dimensions based on pooling ratio
        let output_height = (input_height as f32 * pooling_ratio.0).round() as usize;
        let output_width = (input_width as f32 * pooling_ratio.1).round() as usize;
        let output_shape = vec![batch_size, channels, output_height, output_width];

        let pooling_ratio_slice = &[pooling_ratio.0, pooling_ratio.1];
        let output_len = output_shape.iter().product();

        let result_gpu = crate::gpu::ops::execute_fractional_pooling_op(
            gpu_buffer,
            crate::gpu::ops::PoolingOp::FractionalAvgPool2D,
            pooling_ratio_slice,
            false, // pseudo_random
            false, // overlapping
            input_shape,
            output_len,
        )?;

        let mut result = Tensor::from_gpu_buffer(result_gpu, crate::Shape::new(output_shape));
        result.set_requires_grad(input.requires_grad());
        Ok(result)
    } else {
        // Fallback to CPU implementation for non-GPU tensors
        fractional_avg_pool2d_cpu(input, pooling_ratio, random_samples)
    }
}