Skip to main content

sklears_dummy/performance/
parallel.rs

1//! Parallel computation utilities for high-performance dummy estimator operations
2
3use rayon::prelude::*;
4use scirs2_core::ndarray::{Array2, ArrayView1, Axis};
5use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
6
7/// Parallel prediction for large datasets
8pub fn parallel_predict_classification<F>(
9    x: &Array2<f64>,
10    predict_fn: F,
11    chunk_size: Option<usize>,
12) -> Vec<i32>
13where
14    F: Fn(ArrayView1<f64>) -> i32 + Sync + Send,
15{
16    let chunk_size = chunk_size.unwrap_or(1000);
17
18    if x.nrows() <= chunk_size {
19        // Small dataset - use sequential processing
20        return x.rows().into_iter().map(predict_fn).collect();
21    }
22
23    // Large dataset - use parallel processing with order preservation
24    let mut results: Vec<(usize, Vec<i32>)> = x
25        .axis_chunks_iter(Axis(0), chunk_size)
26        .enumerate()
27        .par_bridge()
28        .map(|(chunk_idx, chunk)| {
29            let chunk_results: Vec<i32> = chunk.rows().into_iter().map(&predict_fn).collect();
30            (chunk_idx, chunk_results)
31        })
32        .collect();
33
34    // Sort by chunk index to preserve order
35    results.sort_by_key(|(idx, _)| *idx);
36
37    // Flatten results
38    results
39        .into_iter()
40        .flat_map(|(_, chunk_results)| chunk_results)
41        .collect()
42}
43
44/// Parallel prediction for regression
45pub fn parallel_predict_regression<F>(
46    x: &Array2<f64>,
47    predict_fn: F,
48    chunk_size: Option<usize>,
49) -> Vec<f64>
50where
51    F: Fn(ArrayView1<f64>) -> f64 + Sync + Send,
52{
53    let chunk_size = chunk_size.unwrap_or(1000);
54
55    if x.nrows() <= chunk_size {
56        return x.rows().into_iter().map(predict_fn).collect();
57    }
58
59    // Large dataset - use parallel processing with order preservation
60    let mut results: Vec<(usize, Vec<f64>)> = x
61        .axis_chunks_iter(Axis(0), chunk_size)
62        .enumerate()
63        .par_bridge()
64        .map(|(chunk_idx, chunk)| {
65            let chunk_results: Vec<f64> = chunk.rows().into_iter().map(&predict_fn).collect();
66            (chunk_idx, chunk_results)
67        })
68        .collect();
69
70    // Sort by chunk index to preserve order
71    results.sort_by_key(|(idx, _)| *idx);
72
73    // Flatten results
74    results
75        .into_iter()
76        .flat_map(|(_, chunk_results)| chunk_results)
77        .collect()
78}
79
80/// Parallel statistical computation
81pub fn parallel_statistics(data: &Array2<f64>) -> ParallelStats {
82    let chunk_size = (data.nrows() / rayon::current_num_threads()).max(1000);
83
84    let results: Vec<_> = data
85        .axis_chunks_iter(Axis(0), chunk_size)
86        .par_bridge()
87        .map(|chunk| {
88            let mut local_stats = ParallelStats::new(data.ncols());
89            for row in chunk.rows() {
90                local_stats.update_row(row);
91            }
92            local_stats
93        })
94        .collect();
95
96    // Combine results
97    let mut combined = ParallelStats::new(data.ncols());
98    for stats in results {
99        combined.merge(stats);
100    }
101    combined.finalize();
102    combined
103}
104
105/// Thread-safe statistics accumulator
106#[derive(Debug)]
107pub struct ParallelStats {
108    /// count
109    pub count: AtomicUsize,
110    /// sums
111    pub sums: Vec<AtomicU64>, // Use atomic for thread-safe f64 accumulation
112    /// sum_squares
113    pub sum_squares: Vec<AtomicU64>,
114    /// mins
115    pub mins: Vec<f64>,
116    /// maxs
117    pub maxs: Vec<f64>,
118}
119
120impl ParallelStats {
121    pub fn new(n_features: usize) -> Self {
122        Self {
123            count: AtomicUsize::new(0),
124            sums: (0..n_features).map(|_| AtomicU64::new(0)).collect(),
125            sum_squares: (0..n_features).map(|_| AtomicU64::new(0)).collect(),
126            mins: vec![f64::INFINITY; n_features],
127            maxs: vec![f64::NEG_INFINITY; n_features],
128        }
129    }
130
131    pub fn update_row(&mut self, row: ArrayView1<f64>) {
132        self.count.fetch_add(1, Ordering::Relaxed);
133
134        for (i, &value) in row.iter().enumerate() {
135            // Use bit manipulation for atomic f64 operations
136            let value_bits = value.to_bits();
137            let squared_bits = (value * value).to_bits();
138
139            self.sums[i].fetch_add(value_bits, Ordering::Relaxed);
140            self.sum_squares[i].fetch_add(squared_bits, Ordering::Relaxed);
141
142            // Note: mins/maxs are not thread-safe in this simple implementation
143            // For production use, consider using atomic operations or locks
144            if value < self.mins[i] {
145                self.mins[i] = value;
146            }
147            if value > self.maxs[i] {
148                self.maxs[i] = value;
149            }
150        }
151    }
152
153    pub fn merge(&mut self, other: ParallelStats) {
154        self.count
155            .fetch_add(other.count.load(Ordering::Relaxed), Ordering::Relaxed);
156
157        for i in 0..self.sums.len() {
158            self.sums[i].fetch_add(other.sums[i].load(Ordering::Relaxed), Ordering::Relaxed);
159            self.sum_squares[i].fetch_add(
160                other.sum_squares[i].load(Ordering::Relaxed),
161                Ordering::Relaxed,
162            );
163
164            self.mins[i] = self.mins[i].min(other.mins[i]);
165            self.maxs[i] = self.maxs[i].max(other.maxs[i]);
166        }
167    }
168
169    pub fn finalize(&self) {
170        // Convert back from bit representation
171        // This is where you'd implement proper finalization
172    }
173
174    pub fn get_means(&self) -> Vec<f64> {
175        let count = self.count.load(Ordering::Relaxed) as f64;
176        self.sums
177            .iter()
178            .map(|sum| f64::from_bits(sum.load(Ordering::Relaxed)) / count)
179            .collect()
180    }
181
182    pub fn get_variances(&self) -> Vec<f64> {
183        let count = self.count.load(Ordering::Relaxed) as f64;
184        let means = self.get_means();
185
186        self.sum_squares
187            .iter()
188            .zip(means.iter())
189            .map(|(sum_sq, &mean)| {
190                let sum_sq_val = f64::from_bits(sum_sq.load(Ordering::Relaxed));
191                (sum_sq_val / count) - (mean * mean)
192            })
193            .collect()
194    }
195}