scirs2-core 0.4.3

Core utilities and common functionality for SciRS2 (scirs2-core)
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
//! Mobile-specific optimizations for ARM NEON
//!
//! This module provides battery-aware and thermal-aware implementations
//! specifically designed for mobile platforms (iOS/Android).
//!
//! ## Features
//!
//! - Battery-optimized algorithms that reduce power consumption
//! - Thermal-aware processing that prevents device overheating
//! - Memory-efficient chunking for constrained devices
//! - Background task support with reduced CPU usage

#[cfg(target_arch = "aarch64")]
use std::arch::aarch64::*;

/// Battery optimization mode for mobile devices
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BatteryMode {
    /// Maximum performance, highest power consumption
    Performance,
    /// Balanced performance and power consumption
    Balanced,
    /// Maximum battery life, reduced performance
    PowerSaver,
}

/// Thermal state of the device
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum ThermalState {
    /// Normal operating temperature
    Normal,
    /// Slightly elevated temperature
    Warm,
    /// High temperature, should reduce workload
    Hot,
    /// Critical temperature, must throttle immediately
    Critical,
}

/// Mobile-specific optimizer configuration
#[derive(Debug, Clone)]
pub struct MobileOptimizer {
    /// Current battery mode
    pub battery_mode: BatteryMode,
    /// Current thermal state
    pub thermal_state: ThermalState,
    /// Maximum chunk size for processing (bytes)
    pub max_chunk_size: usize,
    /// Enable background processing optimizations
    pub background_mode: bool,
}

impl Default for MobileOptimizer {
    fn default() -> Self {
        Self {
            battery_mode: BatteryMode::Balanced,
            thermal_state: ThermalState::Normal,
            max_chunk_size: 1024 * 1024, // 1MB default
            background_mode: false,
        }
    }
}

impl MobileOptimizer {
    /// Create a new mobile optimizer with default settings
    pub fn new() -> Self {
        Self::default()
    }

    /// Set battery mode
    pub fn with_battery_mode(mut self, mode: BatteryMode) -> Self {
        self.battery_mode = mode;
        self
    }

    /// Set thermal state
    pub fn with_thermal_state(mut self, state: ThermalState) -> Self {
        self.thermal_state = state;
        self
    }

    /// Enable background processing mode
    pub fn with_background_mode(mut self, enabled: bool) -> Self {
        self.background_mode = enabled;
        self
    }

    /// Get optimal chunk size based on current settings
    pub fn get_optimal_chunk_size(&self) -> usize {
        let base_size = match self.battery_mode {
            BatteryMode::Performance => 4096 * 1024, // 4MB
            BatteryMode::Balanced => 1024 * 1024,    // 1MB
            BatteryMode::PowerSaver => 256 * 1024,   // 256KB
        };

        // Reduce chunk size if thermal state is elevated
        let thermal_multiplier = match self.thermal_state {
            ThermalState::Normal => 1.0,
            ThermalState::Warm => 0.75,
            ThermalState::Hot => 0.5,
            ThermalState::Critical => 0.25,
        };

        // Further reduce if in background mode
        let background_multiplier = if self.background_mode { 0.5 } else { 1.0 };

        (base_size as f32 * thermal_multiplier * background_multiplier) as usize
    }

    /// Get delay between chunks (microseconds) for thermal management
    pub fn get_chunk_delay_us(&self) -> u64 {
        match (self.thermal_state, self.battery_mode) {
            (ThermalState::Critical, _) => 10000, // 10ms delay
            (ThermalState::Hot, _) => 5000,       // 5ms delay
            (ThermalState::Warm, BatteryMode::PowerSaver) => 2000, // 2ms delay
            (ThermalState::Warm, _) => 1000,      // 1ms delay
            _ => 0,                               // No delay
        }
    }

    /// Check if processing should be paused due to thermal conditions
    pub fn should_throttle(&self) -> bool {
        self.thermal_state >= ThermalState::Hot
    }
}

/// Battery-optimized dot product for f32
///
/// Adapts processing based on battery mode:
/// - Performance: No optimization, maximum speed
/// - Balanced: Chunked processing with moderate delays
/// - PowerSaver: Small chunks with sleep intervals
pub fn neon_dot_battery_optimized(a: &[f32], b: &[f32], optimizer: &MobileOptimizer) -> f32 {
    let len = a.len().min(b.len());
    let chunk_size = optimizer.get_optimal_chunk_size() / std::mem::size_of::<f32>();
    let delay_us = optimizer.get_chunk_delay_us();

    let mut result = 0.0;
    let mut offset = 0;

    while offset < len {
        let chunk_end = (offset + chunk_size).min(len);
        let chunk_a = &a[offset..chunk_end];
        let chunk_b = &b[offset..chunk_end];

        // Process chunk
        #[cfg(target_arch = "aarch64")]
        {
            if std::arch::is_aarch64_feature_detected!("neon") {
                result += unsafe { neon_dot_chunk_f32(chunk_a, chunk_b) };
            } else {
                result += scalar_dot_f32(chunk_a, chunk_b);
            }
        }
        #[cfg(not(target_arch = "aarch64"))]
        {
            result += scalar_dot_f32(chunk_a, chunk_b);
        }

        offset = chunk_end;

        // Thermal management: insert delay between chunks if needed
        if delay_us > 0 && offset < len {
            std::thread::sleep(std::time::Duration::from_micros(delay_us));
        }
    }

    result
}

/// NEON-optimized chunk processing for dot product
#[cfg(target_arch = "aarch64")]
#[target_feature(enable = "neon")]
unsafe fn neon_dot_chunk_f32(a: &[f32], b: &[f32]) -> f32 {
    let len = a.len().min(b.len());
    let mut i = 0;
    let mut sum = vdupq_n_f32(0.0);

    while i + 4 <= len {
        let va = vld1q_f32(a.as_ptr().add(i));
        let vb = vld1q_f32(b.as_ptr().add(i));
        sum = vfmaq_f32(sum, va, vb);
        i += 4;
    }

    let mut result = vaddvq_f32(sum);

    while i < len {
        result += a[i] * b[i];
        i += 1;
    }

    result
}

/// Scalar fallback for dot product
fn scalar_dot_f32(a: &[f32], b: &[f32]) -> f32 {
    let len = a.len().min(b.len());
    let mut sum = 0.0;
    for i in 0..len {
        sum += a[i] * b[i];
    }
    sum
}

/// Battery-optimized GEMM for mobile devices
pub fn neon_gemm_battery_optimized(
    m: usize,
    n: usize,
    k: usize,
    alpha: f32,
    a: &[f32],
    b: &[f32],
    beta: f32,
    c: &mut [f32],
    optimizer: &MobileOptimizer,
) {
    // Adjust block sizes based on battery mode
    let (mc, nc, kc) = match optimizer.battery_mode {
        BatteryMode::Performance => (128, 512, 256),
        BatteryMode::Balanced => (64, 256, 128),
        BatteryMode::PowerSaver => (32, 128, 64),
    };

    let delay_us = optimizer.get_chunk_delay_us();

    #[cfg(target_arch = "aarch64")]
    {
        if std::arch::is_aarch64_feature_detected!("neon") {
            unsafe { neon_gemm_chunked(m, n, k, alpha, a, b, beta, c, mc, nc, kc, delay_us) }
        } else {
            fallback_gemm_chunked(m, n, k, alpha, a, b, beta, c, mc, nc, kc, delay_us)
        }
    }
    #[cfg(not(target_arch = "aarch64"))]
    {
        fallback_gemm_chunked(m, n, k, alpha, a, b, beta, c, mc, nc, kc, delay_us)
    }
}

/// NEON-optimized chunked GEMM with thermal management
#[cfg(target_arch = "aarch64")]
#[target_feature(enable = "neon")]
unsafe fn neon_gemm_chunked(
    m: usize,
    n: usize,
    k: usize,
    alpha: f32,
    a: &[f32],
    b: &[f32],
    beta: f32,
    c: &mut [f32],
    mc: usize,
    nc: usize,
    kc: usize,
    delay_us: u64,
) {
    for jc in (0..n).step_by(nc) {
        let nc_actual = (jc + nc).min(n) - jc;

        for pc in (0..k).step_by(kc) {
            let kc_actual = (pc + kc).min(k) - pc;

            for ic in (0..m).step_by(mc) {
                let mc_actual = (ic + mc).min(m) - ic;

                // Process micro-kernel
                for i in 0..mc_actual {
                    for j in 0..nc_actual {
                        let mut sum = vdupq_n_f32(0.0);
                        let mut p = 0;

                        while p + 4 <= kc_actual {
                            let va = vld1q_f32(a.as_ptr().add((ic + i) * k + pc + p));
                            let vb = vld1q_f32(b.as_ptr().add((pc + p) * n + jc + j));
                            sum = vfmaq_f32(sum, va, vb);
                            p += 4;
                        }

                        let mut dot = vaddvq_f32(sum);

                        while p < kc_actual {
                            dot += a[(ic + i) * k + pc + p] * b[(pc + p) * n + jc + j];
                            p += 1;
                        }

                        let c_idx = (ic + i) * n + jc + j;
                        if pc == 0 {
                            c[c_idx] = alpha * dot + beta * c[c_idx];
                        } else {
                            c[c_idx] += alpha * dot;
                        }
                    }
                }

                // Insert delay for thermal management if needed
                if delay_us > 0 {
                    std::thread::sleep(std::time::Duration::from_micros(delay_us));
                }
            }
        }
    }
}

/// Thermal-aware GEMM that automatically throttles based on temperature
pub fn neon_gemm_thermal_aware(
    m: usize,
    n: usize,
    k: usize,
    alpha: f32,
    a: &[f32],
    b: &[f32],
    beta: f32,
    c: &mut [f32],
    thermal_state: ThermalState,
) {
    let optimizer = MobileOptimizer::default().with_thermal_state(thermal_state);
    neon_gemm_battery_optimized(m, n, k, alpha, a, b, beta, c, &optimizer);
}

// Fallback implementation
fn fallback_gemm_chunked(
    m: usize,
    n: usize,
    k: usize,
    alpha: f32,
    a: &[f32],
    b: &[f32],
    beta: f32,
    c: &mut [f32],
    mc: usize,
    nc: usize,
    kc: usize,
    delay_us: u64,
) {
    for jc in (0..n).step_by(nc) {
        let nc_actual = (jc + nc).min(n) - jc;

        for pc in (0..k).step_by(kc) {
            let kc_actual = (pc + kc).min(k) - pc;

            for ic in (0..m).step_by(mc) {
                let mc_actual = (ic + mc).min(m) - ic;

                for i in 0..mc_actual {
                    for j in 0..nc_actual {
                        let mut sum = 0.0;

                        for p in 0..kc_actual {
                            sum += a[(ic + i) * k + pc + p] * b[(pc + p) * n + jc + j];
                        }

                        let c_idx = (ic + i) * n + jc + j;
                        if pc == 0 {
                            c[c_idx] = alpha * sum + beta * c[c_idx];
                        } else {
                            c[c_idx] += alpha * sum;
                        }
                    }
                }

                if delay_us > 0 {
                    std::thread::sleep(std::time::Duration::from_micros(delay_us));
                }
            }
        }
    }
}

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

    #[test]
    fn test_mobile_optimizer_defaults() {
        let opt = MobileOptimizer::new();
        assert_eq!(opt.battery_mode, BatteryMode::Balanced);
        assert_eq!(opt.thermal_state, ThermalState::Normal);
        assert!(!opt.background_mode);
    }

    #[test]
    fn test_battery_mode_chunk_sizes() {
        let perf = MobileOptimizer::new().with_battery_mode(BatteryMode::Performance);
        let balanced = MobileOptimizer::new().with_battery_mode(BatteryMode::Balanced);
        let saver = MobileOptimizer::new().with_battery_mode(BatteryMode::PowerSaver);

        assert!(perf.get_optimal_chunk_size() > balanced.get_optimal_chunk_size());
        assert!(balanced.get_optimal_chunk_size() > saver.get_optimal_chunk_size());
    }

    #[test]
    fn test_thermal_throttling() {
        let normal = MobileOptimizer::new().with_thermal_state(ThermalState::Normal);
        let hot = MobileOptimizer::new().with_thermal_state(ThermalState::Hot);
        let critical = MobileOptimizer::new().with_thermal_state(ThermalState::Critical);

        assert!(!normal.should_throttle());
        assert!(hot.should_throttle());
        assert!(critical.should_throttle());

        assert!(critical.get_chunk_delay_us() > hot.get_chunk_delay_us());
        assert!(hot.get_chunk_delay_us() > normal.get_chunk_delay_us());
    }

    #[test]
    fn test_battery_optimized_dot() {
        let a = vec![1.0, 2.0, 3.0, 4.0];
        let b = vec![1.0, 1.0, 1.0, 1.0];
        let opt = MobileOptimizer::new();

        let result = neon_dot_battery_optimized(&a, &b, &opt);

        assert!((result - 10.0).abs() < 1e-6);
    }
}