Skip to main content

tenrso_ad/
parallel.rs

1//! Parallel gradient computation using Rayon
2//!
3//! This module provides parallel implementations of gradient operations
4//! for improved performance on multi-core systems.
5//!
6//! # Features
7//!
8//! - Parallel element-wise gradient computation
9//! - Parallel gradient accumulation
10//! - Parallel batch gradient processing
11//! - Work-stealing via Rayon thread pool
12//!
13//! # Performance
14//!
15//! Parallel operations are beneficial when:
16//! - Tensor size > 10,000 elements
17//! - Multiple independent gradients to compute
18//! - Batch size > 4
19//!
20//! For smaller tensors, sequential processing may be faster due to overhead.
21
22use anyhow::Result;
23use rayon::prelude::*;
24use scirs2_core::ndarray_ext::{Array, IxDyn, Zip};
25use scirs2_core::numeric::Float;
26use tenrso_core::DenseND;
27
28/// Configuration for parallel gradient computation
29#[derive(Debug, Clone)]
30pub struct ParallelConfig {
31    /// Minimum tensor size to use parallel processing (default: 10,000)
32    pub min_parallel_size: usize,
33
34    /// Number of threads to use (None = use all available cores)
35    pub num_threads: Option<usize>,
36
37    /// Chunk size for parallel iteration (None = auto)
38    pub chunk_size: Option<usize>,
39}
40
41impl Default for ParallelConfig {
42    fn default() -> Self {
43        Self {
44            min_parallel_size: 10_000,
45            num_threads: None,
46            chunk_size: None,
47        }
48    }
49}
50
51/// Parallel element-wise gradient computation
52///
53/// Computes `grad_x = grad_y * f'(x)` in parallel for element-wise operations.
54///
55/// # Arguments
56///
57/// * `input` - Input tensor from forward pass
58/// * `output_grad` - Gradient w.r.t. output
59/// * `derivative` - Derivative function f'(x)
60/// * `config` - Parallel configuration
61///
62/// # Returns
63///
64/// Gradient w.r.t. input
65///
66/// # Example
67///
68/// ```rust,ignore
69/// let grad = parallel_elementwise_vjp(
70///     &x,
71///     &grad_y,
72///     |x| 2.0 * x,  // derivative of x^2
73///     &ParallelConfig::default(),
74/// )?;
75/// ```
76pub fn parallel_elementwise_vjp<T, F>(
77    input: &DenseND<T>,
78    output_grad: &DenseND<T>,
79    derivative: F,
80    config: &ParallelConfig,
81) -> Result<DenseND<T>>
82where
83    T: Float + Send + Sync,
84    F: Fn(&T) -> T + Send + Sync,
85{
86    if input.shape() != output_grad.shape() {
87        return Err(anyhow::anyhow!(
88            "Shape mismatch: input {:?} vs output_grad {:?}",
89            input.shape(),
90            output_grad.shape()
91        ));
92    }
93
94    let input_arr = input.as_array();
95    let grad_arr = output_grad.as_array();
96
97    // Check if parallel processing is beneficial
98    let total_elements = input.len();
99    let use_parallel = total_elements >= config.min_parallel_size;
100
101    if use_parallel {
102        // Parallel computation using Rayon
103        // First collect to vectors to ensure consistent ordering
104        let shape = input.shape().to_vec();
105        let input_flat: Vec<T> = input_arr.iter().copied().collect();
106        let grad_flat: Vec<T> = grad_arr.iter().copied().collect();
107
108        // Use parallel iteration over vectors which preserves order
109        let grad_data: Vec<T> = input_flat
110            .par_iter()
111            .zip(grad_flat.par_iter())
112            .map(|(x, g)| {
113                let deriv = derivative(x);
114                deriv * *g
115            })
116            .collect();
117
118        let result_arr = Array::from_shape_vec(IxDyn(&shape), grad_data)
119            .map_err(|e| anyhow::anyhow!("Failed to create result array: {}", e))?;
120
121        Ok(DenseND::from_array(result_arr))
122    } else {
123        // Sequential computation for small tensors
124        let result_arr = Zip::from(input_arr).and(grad_arr).map_collect(|x, g| {
125            let deriv = derivative(x);
126            deriv * *g
127        });
128
129        Ok(DenseND::from_array(result_arr))
130    }
131}
132
133/// Parallel gradient accumulation for multiple gradients
134///
135/// Efficiently accumulates multiple gradients in parallel.
136///
137/// # Arguments
138///
139/// * `gradients` - Slice of gradient tensors to accumulate
140/// * `config` - Parallel configuration
141///
142/// # Returns
143///
144/// Accumulated gradient
145///
146/// # Example
147///
148/// ```rust,ignore
149/// let total_grad = parallel_accumulate_gradients(
150///     &[grad1, grad2, grad3],
151///     &ParallelConfig::default(),
152/// )?;
153/// ```
154pub fn parallel_accumulate_gradients<T>(
155    gradients: &[DenseND<T>],
156    config: &ParallelConfig,
157) -> Result<DenseND<T>>
158where
159    T: Float + Send + Sync,
160{
161    if gradients.is_empty() {
162        return Err(anyhow::anyhow!("No gradients to accumulate"));
163    }
164
165    let shape = gradients[0].shape();
166
167    // Verify all gradients have same shape
168    for grad in gradients.iter() {
169        if grad.shape() != shape {
170            return Err(anyhow::anyhow!(
171                "Shape mismatch in gradient accumulation: expected {:?}, got {:?}",
172                shape,
173                grad.shape()
174            ));
175        }
176    }
177
178    let total_elements = gradients[0].len();
179    let use_parallel = total_elements >= config.min_parallel_size;
180
181    if use_parallel {
182        // Parallel reduction - accumulate gradients
183        let mut result = gradients[0].clone();
184        for grad in gradients.iter().skip(1) {
185            let result_arr = result.as_array();
186            let grad_arr = grad.as_array();
187            let sum_arr = result_arr + grad_arr;
188            result = DenseND::from_array(sum_arr);
189        }
190        Ok(result)
191    } else {
192        // Sequential accumulation
193        let mut result = gradients[0].clone();
194        for grad in gradients.iter().skip(1) {
195            result = &result + grad;
196        }
197        Ok(result)
198    }
199}
200
201/// Parallel batch gradient computation
202///
203/// Computes gradients for a batch of inputs in parallel.
204///
205/// # Arguments
206///
207/// * `inputs` - Batch of input tensors
208/// * `output_grads` - Batch of output gradients
209/// * `gradient_fn` - Function to compute gradient for single input
210/// * `config` - Parallel configuration
211///
212/// # Returns
213///
214/// Vector of input gradients
215///
216/// # Example
217///
218/// ```rust,ignore
219/// let input_grads = parallel_batch_gradients(
220///     &batch_inputs,
221///     &batch_output_grads,
222///     |input, output_grad| compute_single_grad(input, output_grad),
223///     &ParallelConfig::default(),
224/// )?;
225/// ```
226pub fn parallel_batch_gradients<T, F>(
227    inputs: &[DenseND<T>],
228    output_grads: &[DenseND<T>],
229    gradient_fn: F,
230    _config: &ParallelConfig,
231) -> Result<Vec<DenseND<T>>>
232where
233    T: Float + Send + Sync,
234    F: Fn(&DenseND<T>, &DenseND<T>) -> Result<DenseND<T>> + Send + Sync,
235{
236    if inputs.len() != output_grads.len() {
237        return Err(anyhow::anyhow!(
238            "Batch size mismatch: {} inputs vs {} output grads",
239            inputs.len(),
240            output_grads.len()
241        ));
242    }
243
244    let batch_size = inputs.len();
245    let use_parallel = batch_size > 1;
246
247    if use_parallel {
248        // Parallel batch processing
249        let results: Result<Vec<_>> = inputs
250            .par_iter()
251            .zip(output_grads.par_iter())
252            .map(|(input, output_grad)| gradient_fn(input, output_grad))
253            .collect();
254
255        results
256    } else {
257        // Sequential for single item
258        inputs
259            .iter()
260            .zip(output_grads.iter())
261            .map(|(input, output_grad)| gradient_fn(input, output_grad))
262            .collect()
263    }
264}
265
266/// Parallel reduction gradient computation
267///
268/// Computes gradients for reduction operations in parallel.
269///
270/// # Arguments
271///
272/// * `input_shape` - Shape of original input
273/// * `output_grad` - Gradient w.r.t. output (reduced)
274/// * `scaling` - Scaling factor (e.g., 1/n for mean)
275/// * `config` - Parallel configuration
276///
277/// # Returns
278///
279/// Gradient w.r.t. input (broadcasted)
280pub fn parallel_reduction_grad<T>(
281    input_shape: &[usize],
282    output_grad: &DenseND<T>,
283    scaling: T,
284    config: &ParallelConfig,
285) -> Result<DenseND<T>>
286where
287    T: Float + Send + Sync,
288{
289    let total_elements: usize = input_shape.iter().product();
290    let use_parallel = total_elements >= config.min_parallel_size;
291
292    // Get the scalar gradient value
293    let grad_value = if output_grad.len() == 1 {
294        *output_grad
295            .get(&[])
296            .or_else(|| output_grad.get(&[0]))
297            .ok_or_else(|| anyhow::anyhow!("Failed to get gradient value"))?
298    } else {
299        return Err(anyhow::anyhow!(
300            "Expected scalar output gradient for full reduction"
301        ));
302    };
303
304    let scaled_grad = grad_value * scaling;
305
306    if use_parallel {
307        // Parallel fill
308        let grad_data: Vec<T> = (0..total_elements)
309            .into_par_iter()
310            .map(|_| scaled_grad)
311            .collect();
312
313        let result_arr = Array::from_shape_vec(IxDyn(input_shape), grad_data)
314            .map_err(|e| anyhow::anyhow!("Failed to create result array: {}", e))?;
315
316        Ok(DenseND::from_array(result_arr))
317    } else {
318        // Sequential fill
319        Ok(DenseND::from_elem(input_shape, scaled_grad))
320    }
321}
322
323/// Configure global Rayon thread pool
324///
325/// Sets the number of threads for parallel computation.
326///
327/// # Arguments
328///
329/// * `num_threads` - Number of threads (None = use all available cores)
330///
331/// # Example
332///
333/// ```rust,ignore
334/// configure_thread_pool(Some(4)); // Use 4 threads
335/// configure_thread_pool(None);    // Use all cores
336/// ```
337pub fn configure_thread_pool(num_threads: Option<usize>) -> Result<()> {
338    if let Some(n) = num_threads {
339        rayon::ThreadPoolBuilder::new()
340            .num_threads(n)
341            .build_global()
342            .map_err(|e| anyhow::anyhow!("Failed to configure thread pool: {}", e))?;
343    }
344    Ok(())
345}
346
347#[cfg(test)]
348mod tests {
349    use super::*;
350
351    #[test]
352    fn test_parallel_elementwise_vjp() {
353        let x = DenseND::from_vec(vec![1.0, 2.0, 3.0, 4.0], &[4]).unwrap();
354        let grad_y = DenseND::ones(&[4]);
355
356        let config = ParallelConfig {
357            min_parallel_size: 1, // Force parallel for testing
358            ..Default::default()
359        };
360
361        // Test derivative of x^2: f'(x) = 2x
362        let grad_x = parallel_elementwise_vjp(&x, &grad_y, |x| 2.0 * x, &config).unwrap();
363
364        assert_eq!(grad_x.shape(), &[4]);
365
366        // Check values with array access
367        let grad_arr = grad_x.as_array();
368        let values: Vec<f64> = grad_arr.iter().copied().collect();
369
370        assert!(
371            (values[0] - 2.0).abs() < 1e-8,
372            "grad[0] = {}, expected 2.0",
373            values[0]
374        );
375        assert!(
376            (values[1] - 4.0).abs() < 1e-8,
377            "grad[1] = {}, expected 4.0",
378            values[1]
379        );
380        assert!(
381            (values[2] - 6.0).abs() < 1e-8,
382            "grad[2] = {}, expected 6.0",
383            values[2]
384        );
385        assert!(
386            (values[3] - 8.0).abs() < 1e-8,
387            "grad[3] = {}, expected 8.0",
388            values[3]
389        );
390    }
391
392    #[test]
393    fn test_parallel_accumulate_gradients() {
394        let grad1 = DenseND::from_vec(vec![1.0, 2.0, 3.0], &[3]).unwrap();
395        let grad2 = DenseND::from_vec(vec![4.0, 5.0, 6.0], &[3]).unwrap();
396        let grad3 = DenseND::from_vec(vec![7.0, 8.0, 9.0], &[3]).unwrap();
397
398        let config = ParallelConfig {
399            min_parallel_size: 1,
400            ..Default::default()
401        };
402
403        let result = parallel_accumulate_gradients(&[grad1, grad2, grad3], &config).unwrap();
404
405        assert_eq!(result.shape(), &[3]);
406        assert!((result.get(&[0]).unwrap() - 12.0).abs() < 1e-10);
407        assert!((result.get(&[1]).unwrap() - 15.0).abs() < 1e-10);
408        assert!((result.get(&[2]).unwrap() - 18.0).abs() < 1e-10);
409    }
410
411    #[test]
412    fn test_parallel_batch_gradients() {
413        let inputs = vec![
414            DenseND::from_vec(vec![1.0, 2.0], &[2]).unwrap(),
415            DenseND::from_vec(vec![3.0, 4.0], &[2]).unwrap(),
416        ];
417        let output_grads = vec![DenseND::ones(&[2]), DenseND::ones(&[2])];
418
419        let config = ParallelConfig::default();
420
421        let gradient_fn = |input: &DenseND<f64>, output_grad: &DenseND<f64>| {
422            parallel_elementwise_vjp(input, output_grad, |x| 2.0 * x, &config)
423        };
424
425        let results =
426            parallel_batch_gradients(&inputs, &output_grads, gradient_fn, &config).unwrap();
427
428        assert_eq!(results.len(), 2);
429        assert!((results[0].get(&[0]).unwrap() - 2.0).abs() < 1e-10);
430        assert!((results[0].get(&[1]).unwrap() - 4.0).abs() < 1e-10);
431        assert!((results[1].get(&[0]).unwrap() - 6.0).abs() < 1e-10);
432        assert!((results[1].get(&[1]).unwrap() - 8.0).abs() < 1e-10);
433    }
434
435    #[test]
436    fn test_parallel_reduction_grad() {
437        let input_shape = vec![2, 3];
438        let output_grad = DenseND::from_elem(&[], 5.0);
439        let scaling = 0.5;
440
441        let config = ParallelConfig {
442            min_parallel_size: 1,
443            ..Default::default()
444        };
445
446        let result = parallel_reduction_grad(&input_shape, &output_grad, scaling, &config).unwrap();
447
448        assert_eq!(result.shape(), &[2, 3]);
449        for i in 0..2 {
450            for j in 0..3 {
451                assert!((result.get(&[i, j]).unwrap() - 2.5).abs() < 1e-10);
452            }
453        }
454    }
455
456    #[test]
457    fn test_sequential_fallback_small_tensor() {
458        // Small tensor should use sequential path
459        let x = DenseND::from_vec(vec![1.0, 2.0, 3.0], &[3]).unwrap();
460        let grad_y = DenseND::ones(&[3]);
461
462        let config = ParallelConfig {
463            min_parallel_size: 1000, // Set high threshold
464            ..Default::default()
465        };
466
467        let grad_x = parallel_elementwise_vjp(&x, &grad_y, |x| 2.0 * x, &config).unwrap();
468
469        assert_eq!(grad_x.shape(), &[3]);
470        assert!((grad_x.get(&[0]).unwrap() - 2.0).abs() < 1e-10);
471    }
472}