Skip to main content

torsh_functional/
parallel.rs

1//! Multi-threaded execution for large tensor operations
2//!
3//! This module provides parallel implementations of tensor operations
4//! for improved performance on large tensors.
5//!
6//! **SciRS2 POLICY COMPLIANCE**: Uses `scirs2_core::parallel_ops` for all
7//! parallel operations instead of direct rayon imports.
8
9// ✅ SciRS2 POLICY: Use scirs2_core::parallel_ops instead of direct rayon
10use scirs2_core::parallel_ops::*;
11use torsh_core::Result as TorshResult;
12use torsh_tensor::Tensor;
13// use std::sync::Arc;
14
15/// Configuration for parallel execution
16#[derive(Clone, Debug)]
17pub struct ParallelConfig {
18    /// Minimum tensor size to use parallel execution
19    pub size_threshold: usize,
20    /// Chunk size for parallel processing
21    pub chunk_size: usize,
22    /// Maximum number of threads to use (None = use all available)
23    pub max_threads: Option<usize>,
24    /// Whether to use adaptive chunk sizing
25    pub adaptive_chunking: bool,
26}
27
28impl Default for ParallelConfig {
29    fn default() -> Self {
30        Self {
31            size_threshold: 1000,
32            chunk_size: 1000,
33            max_threads: None,
34            adaptive_chunking: true,
35        }
36    }
37}
38
39/// Initialize the thread pool with custom configuration
40///
41/// **SciRS2 POLICY**: Uses re-exported types from scirs2_core::parallel_ops
42#[allow(dead_code)]
43pub fn init_thread_pool(config: &ParallelConfig) -> Result<(), Box<dyn std::error::Error>> {
44    let mut builder = ThreadPoolBuilder::new();
45
46    if let Some(max_threads) = config.max_threads {
47        builder = builder.num_threads(max_threads);
48    }
49
50    let pool = builder.build_global();
51    pool.map_err(|e| Box::new(e) as Box<dyn std::error::Error>)
52}
53
54/// Determine optimal chunk size based on data size and thread count
55///
56/// **SciRS2 POLICY**: Uses re-exported functions from scirs2_core::parallel_ops
57fn optimal_chunk_size(data_size: usize, config: &ParallelConfig) -> usize {
58    if !config.adaptive_chunking {
59        return config.chunk_size;
60    }
61
62    let num_threads = current_num_threads();
63    let chunks_per_thread = 4; // Aim for 4 chunks per thread for good load balancing
64    let optimal_chunks = num_threads * chunks_per_thread;
65    let optimal_size = (data_size / optimal_chunks).max(config.chunk_size);
66
67    optimal_size
68}
69
70/// Parallel element-wise operation on a single tensor
71#[allow(dead_code)]
72pub fn parallel_elementwise<F>(
73    input: &Tensor,
74    operation: F,
75    config: Option<ParallelConfig>,
76) -> TorshResult<Tensor>
77where
78    F: Fn(f32) -> f32 + Send + Sync,
79{
80    let config = config.unwrap_or_default();
81    let data = input.data()?;
82
83    if data.len() < config.size_threshold {
84        // Use sequential processing for small tensors
85        let result_data: Vec<f32> = data.iter().map(|&x| operation(x)).collect();
86        return Tensor::from_data(result_data, input.shape().dims().to_vec(), input.device());
87    }
88
89    let chunk_size = optimal_chunk_size(data.len(), &config);
90
91    let result_data: Vec<f32> = data
92        .par_chunks(chunk_size)
93        .flat_map(|chunk| chunk.iter().map(|&x| operation(x)).collect::<Vec<_>>())
94        .collect();
95
96    Tensor::from_data(result_data, input.shape().dims().to_vec(), input.device())
97}
98
99/// Parallel element-wise operation on two tensors
100#[allow(dead_code)]
101pub fn parallel_elementwise_binary<F>(
102    a: &Tensor,
103    b: &Tensor,
104    operation: F,
105    config: Option<ParallelConfig>,
106) -> TorshResult<Tensor>
107where
108    F: Fn(f32, f32) -> f32 + Send + Sync,
109{
110    let config = config.unwrap_or_default();
111
112    if a.shape() != b.shape() {
113        return Err(torsh_core::TorshError::ShapeMismatch {
114            expected: a.shape().dims().to_vec(),
115            got: b.shape().dims().to_vec(),
116        });
117    }
118
119    let data_a = a.data()?;
120    let data_b = b.data()?;
121
122    if data_a.len() < config.size_threshold {
123        // Use sequential processing for small tensors
124        let result_data: Vec<f32> = data_a
125            .iter()
126            .zip(data_b.iter())
127            .map(|(&x, &y)| operation(x, y))
128            .collect();
129        return Ok(Tensor::from_data(
130            result_data,
131            a.shape().dims().to_vec(),
132            a.device(),
133        )?);
134    }
135
136    let chunk_size = optimal_chunk_size(data_a.len(), &config);
137
138    let result_data: Vec<f32> = data_a
139        .par_chunks(chunk_size)
140        .zip(data_b.par_chunks(chunk_size))
141        .flat_map(|(chunk_a, chunk_b)| {
142            chunk_a
143                .iter()
144                .zip(chunk_b.iter())
145                .map(|(&x, &y)| operation(x, y))
146                .collect::<Vec<_>>()
147        })
148        .collect();
149
150    Ok(Tensor::from_data(
151        result_data,
152        a.shape().dims().to_vec(),
153        a.device(),
154    )?)
155}
156
157/// Parallel reduction operation
158#[allow(dead_code)]
159pub fn parallel_reduce<F, R>(
160    input: &Tensor,
161    identity: R,
162    map_op: F,
163    reduce_op: fn(R, R) -> R,
164    config: Option<ParallelConfig>,
165) -> TorshResult<R>
166where
167    F: Fn(f32) -> R + Send + Sync,
168    R: Send + Copy + Sync,
169{
170    let config = config.unwrap_or_default();
171    let data = input.data()?;
172
173    if data.len() < config.size_threshold {
174        // Use sequential processing for small tensors
175        return Ok(data.iter().map(|&x| map_op(x)).fold(identity, reduce_op));
176    }
177
178    let chunk_size = optimal_chunk_size(data.len(), &config);
179
180    let result = data
181        .par_chunks(chunk_size)
182        .map(|chunk| chunk.iter().map(|&x| map_op(x)).fold(identity, reduce_op))
183        .reduce(|| identity, reduce_op);
184
185    Ok(result)
186}
187
188/// Parallel matrix multiplication for 2D tensors
189#[allow(dead_code)]
190pub fn parallel_matmul(
191    a: &Tensor,
192    b: &Tensor,
193    config: Option<ParallelConfig>,
194) -> TorshResult<Tensor> {
195    let config = config.unwrap_or_default();
196
197    // Check shapes
198    let a_shape_ref = a.shape();
199    let a_shape = a_shape_ref.dims();
200    let b_shape_ref = b.shape();
201    let b_shape = b_shape_ref.dims();
202
203    if a_shape.len() != 2 || b_shape.len() != 2 {
204        return Err(torsh_core::TorshError::InvalidArgument(
205            "parallel_matmul requires 2D tensors".to_string(),
206        ));
207    }
208
209    if a_shape[1] != b_shape[0] {
210        return Err(torsh_core::TorshError::ShapeMismatch {
211            expected: vec![a_shape[0], a_shape[1]],
212            got: b_shape.to_vec(),
213        });
214    }
215
216    let m = a_shape[0];
217    let n = b_shape[1];
218    let k = a_shape[1];
219
220    let data_a = a.data()?;
221    let data_b = b.data()?;
222
223    // Use parallel processing for large matrices (simplified)
224    if m * n >= config.size_threshold {
225        // For now, use a simpler approach that avoids complex nested parallel/sequential iterator mixing
226        let mut result_data = vec![0.0f32; m * n];
227
228        result_data
229            .par_chunks_mut(n)
230            .enumerate()
231            .for_each(|(i, row)| {
232                for j in 0..n {
233                    let mut sum = 0.0f32;
234                    for kk in 0..k {
235                        sum += data_a[i * k + kk] * data_b[kk * n + j];
236                    }
237                    row[j] = sum;
238                }
239            });
240
241        Ok(Tensor::from_data(result_data, vec![m, n], a.device())?)
242    } else {
243        // Fall back to standard implementation
244        a.matmul(b)
245    }
246}
247
248/// Parallel convolution operation (simplified)
249#[allow(dead_code)]
250pub fn parallel_conv2d_simple(
251    input: &Tensor,
252    weight: &Tensor,
253    stride: [usize; 2],
254    padding: [usize; 2],
255    config: Option<ParallelConfig>,
256) -> TorshResult<Tensor> {
257    let config = config.unwrap_or_default();
258
259    let input_shape_ref = input.shape();
260    let input_shape = input_shape_ref.dims();
261    let weight_shape_ref = weight.shape();
262    let weight_shape = weight_shape_ref.dims();
263
264    // Simplified shape checks (assuming NCHW format)
265    if input_shape.len() != 4 || weight_shape.len() != 4 {
266        return Err(torsh_core::TorshError::InvalidArgument(
267            "parallel_conv2d requires 4D tensors".to_string(),
268        ));
269    }
270
271    let batch_size = input_shape[0];
272    let out_channels = weight_shape[0];
273    let in_channels = input_shape[1];
274    let input_h = input_shape[2];
275    let input_w = input_shape[3];
276    let kernel_h = weight_shape[2];
277    let kernel_w = weight_shape[3];
278
279    let output_h = (input_h + 2 * padding[0] - kernel_h) / stride[0] + 1;
280    let output_w = (input_w + 2 * padding[1] - kernel_w) / stride[1] + 1;
281
282    let output_size = batch_size * out_channels * output_h * output_w;
283
284    // Use parallel processing for large convolutions (simplified)
285    if output_size >= config.size_threshold {
286        // Simplified parallel convolution using chunked processing
287        let input_data = input.data()?;
288        let weight_data = weight.data()?;
289
290        let mut result_data = vec![0.0f32; output_size];
291        let elements_per_batch = out_channels * output_h * output_w;
292
293        result_data
294            .par_chunks_mut(elements_per_batch)
295            .enumerate()
296            .for_each(|(b, batch_output)| {
297                for oc in 0..out_channels {
298                    for oh in 0..output_h {
299                        for ow in 0..output_w {
300                            let mut sum = 0.0;
301                            for ic in 0..in_channels {
302                                for kh in 0..kernel_h {
303                                    for kw in 0..kernel_w {
304                                        let ih = oh * stride[0] + kh;
305                                        let iw = ow * stride[1] + kw;
306
307                                        if ih < padding[0]
308                                            || ih >= input_h + padding[0]
309                                            || iw < padding[1]
310                                            || iw >= input_w + padding[1]
311                                        {
312                                            continue; // Padding
313                                        }
314
315                                        let ih = ih - padding[0];
316                                        let iw = iw - padding[1];
317
318                                        let input_idx = b * in_channels * input_h * input_w
319                                            + ic * input_h * input_w
320                                            + ih * input_w
321                                            + iw;
322                                        let weight_idx = oc * in_channels * kernel_h * kernel_w
323                                            + ic * kernel_h * kernel_w
324                                            + kh * kernel_w
325                                            + kw;
326
327                                        sum += input_data[input_idx] * weight_data[weight_idx];
328                                    }
329                                }
330                            }
331                            let output_idx = oc * output_h * output_w + oh * output_w + ow;
332                            batch_output[output_idx] = sum;
333                        }
334                    }
335                }
336            });
337
338        Ok(Tensor::from_data(
339            result_data,
340            vec![batch_size, out_channels, output_h, output_w],
341            input.device(),
342        )?)
343    } else {
344        // Fall back to standard implementation
345        crate::conv::conv2d(
346            input,
347            weight,
348            None,
349            (stride[0], stride[1]),
350            (padding[0], padding[1]),
351            (1, 1),
352            1,
353        )
354    }
355}
356
357/// Parallel softmax computation
358#[allow(dead_code)]
359pub fn parallel_softmax(
360    input: &Tensor,
361    dim: i32,
362    config: Option<ParallelConfig>,
363) -> TorshResult<Tensor> {
364    let config = config.unwrap_or_default();
365    let shape_ref = input.shape();
366    let shape = shape_ref.dims();
367    let data = input.data()?;
368
369    // Only parallelize for large tensors
370    if data.len() < config.size_threshold {
371        return input.softmax(dim);
372    }
373
374    // Simplified parallel softmax along last dimension for now
375    if dim == -1 || dim as usize == shape.len() - 1 {
376        let last_dim_size = shape[shape.len() - 1];
377        let _outer_size = data.len() / last_dim_size;
378
379        let mut result_data = vec![0.0f32; data.len()];
380
381        result_data
382            .par_chunks_mut(last_dim_size)
383            .enumerate()
384            .for_each(|(i, output_slice)| {
385                let start_idx = i * last_dim_size;
386                let input_slice = &data[start_idx..start_idx + last_dim_size];
387
388                // Find max for numerical stability
389                let max_val = input_slice.iter().fold(f32::NEG_INFINITY, |a, &b| a.max(b));
390
391                // Compute exp(x - max) and sum
392                let mut sum = 0.0f32;
393                for (j, &x) in input_slice.iter().enumerate() {
394                    let exp_val = (x - max_val).exp();
395                    output_slice[j] = exp_val;
396                    sum += exp_val;
397                }
398
399                // Normalize
400                for val in output_slice.iter_mut() {
401                    *val /= sum;
402                }
403            });
404
405        Ok(Tensor::from_data(
406            result_data,
407            shape.to_vec(),
408            input.device(),
409        )?)
410    } else {
411        // Fall back to standard implementation for other dimensions
412        input.softmax(dim)
413    }
414}
415
416/// Parallel activation functions with automatic optimization selection
417pub mod parallel_activations {
418    use super::*;
419
420    /// Parallel ReLU
421    #[allow(dead_code)]
422    pub fn relu(input: &Tensor, config: Option<ParallelConfig>) -> TorshResult<Tensor> {
423        parallel_elementwise(input, |x| x.max(0.0), config)
424    }
425
426    /// Parallel Leaky ReLU
427    #[allow(dead_code)]
428    pub fn leaky_relu(
429        input: &Tensor,
430        negative_slope: f32,
431        config: Option<ParallelConfig>,
432    ) -> TorshResult<Tensor> {
433        parallel_elementwise(
434            input,
435            move |x| if x > 0.0 { x } else { x * negative_slope },
436            config,
437        )
438    }
439
440    /// Parallel ELU
441    #[allow(dead_code)]
442    pub fn elu(input: &Tensor, alpha: f32, config: Option<ParallelConfig>) -> TorshResult<Tensor> {
443        parallel_elementwise(
444            input,
445            move |x| if x > 0.0 { x } else { alpha * (x.exp() - 1.0) },
446            config,
447        )
448    }
449
450    /// Parallel Sigmoid using lookup table for large tensors
451    #[allow(dead_code)]
452    pub fn sigmoid(input: &Tensor, config: Option<ParallelConfig>) -> TorshResult<Tensor> {
453        let config = config.unwrap_or_default();
454
455        // Use lookup table for very large tensors
456        if input.numel() > config.size_threshold * 10 {
457            crate::activation_lookup::sigmoid_lookup(input, None)
458        } else {
459            parallel_elementwise(input, |x| 1.0 / (1.0 + (-x).exp()), Some(config))
460        }
461    }
462}
463
464#[cfg(test)]
465mod tests {
466    use super::*;
467    use torsh_tensor::creation::{ones, rand};
468
469    #[test]
470    fn test_parallel_elementwise() {
471        let input = rand(&[1000]).unwrap();
472        let result = parallel_elementwise(&input, |x| x * 2.0, None).unwrap();
473
474        assert_eq!(input.shape(), result.shape());
475    }
476
477    #[test]
478    fn test_parallel_binary_op() {
479        let a = ones(&[500, 500]).unwrap();
480        let b = ones(&[500, 500]).unwrap();
481        let result = parallel_elementwise_binary(&a, &b, |x, y| x + y, None).unwrap();
482
483        assert_eq!(a.shape(), result.shape());
484    }
485
486    #[test]
487    fn test_parallel_reduce() {
488        let input = ones(&[1000]).unwrap();
489        let sum = parallel_reduce(&input, 0.0, |x| x, |a, b| a + b, None).unwrap();
490
491        assert!((sum - 1000.0).abs() < 1e-6);
492    }
493
494    #[test]
495    fn test_optimal_chunk_size() {
496        let config = ParallelConfig::default();
497        let chunk_size = optimal_chunk_size(10000, &config);
498        assert!(chunk_size > 0);
499        assert!(chunk_size <= 10000);
500    }
501}