optirs-core 0.3.1

OptiRS core optimization algorithms and utilities
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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
// Gradient accumulation for large batch training
//
// This module provides utilities for accumulating gradients across multiple
// micro-batches to simulate larger batch sizes without increasing memory usage.

use crate::error::{OptimError, Result};
use scirs2_core::ndarray::{Array, Dimension, ScalarOperand, Zip};
use scirs2_core::numeric::Float;
use std::fmt::Debug;

/// Type alias for adaptive step conditions
pub type AdaptiveStepCondition = Box<dyn Fn(usize) -> bool>;

/// Gradient accumulation mode
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum AccumulationMode {
    /// Sum gradients (standard accumulation)
    Sum,
    /// Average gradients (normalize by number of accumulations)
    Average,
}

/// Gradient accumulator for micro-batch training
#[derive(Debug)]
pub struct GradientAccumulator<A: Float, D: Dimension> {
    /// Accumulated gradients
    accumulated_gradients: Vec<Array<A, D>>,
    /// Number of accumulation steps taken
    accumulation_count: usize,
    /// Target number of accumulations before update
    target_accumulations: usize,
    /// Accumulation mode
    mode: AccumulationMode,
    /// Whether accumulator has been initialized
    initialized: bool,
}

impl<A: Float + ScalarOperand + Debug, D: Dimension + Send + Sync> GradientAccumulator<A, D> {
    /// Create a new gradient accumulator
    pub fn new(_targetaccumulations: usize, mode: AccumulationMode) -> Self {
        Self {
            accumulated_gradients: Vec::new(),
            accumulation_count: 0,
            target_accumulations: _targetaccumulations,
            mode,
            initialized: false,
        }
    }

    /// Initialize accumulator with gradient shapes
    pub fn initialize(&mut self, gradients: &[Array<A, D>]) -> Result<()> {
        if self.initialized {
            return Err(OptimError::InvalidConfig(
                "Accumulator already initialized".to_string(),
            ));
        }

        self.accumulated_gradients = gradients
            .iter()
            .map(|g| Array::zeros(g.raw_dim()))
            .collect();

        self.initialized = true;
        Ok(())
    }

    /// Accumulate gradients from a micro-batch
    pub fn accumulate(&mut self, gradients: &[Array<A, D>]) -> Result<()> {
        if !self.initialized {
            self.initialize(gradients)?;
        }

        if gradients.len() != self.accumulated_gradients.len() {
            return Err(OptimError::DimensionMismatch(format!(
                "Expected {} gradient arrays, got {}",
                self.accumulated_gradients.len(),
                gradients.len()
            )));
        }

        // Accumulate gradients
        for (acc_grad, micro_grad) in self.accumulated_gradients.iter_mut().zip(gradients.iter()) {
            if acc_grad.raw_dim() != micro_grad.raw_dim() {
                return Err(OptimError::DimensionMismatch(
                    "Gradient dimensions don't match".to_string(),
                ));
            }

            Zip::from(acc_grad).and(micro_grad).for_each(|acc, &micro| {
                *acc = *acc + micro;
            });
        }

        self.accumulation_count += 1;
        Ok(())
    }

    /// Check if accumulation is complete
    pub fn is_ready(&self) -> bool {
        self.accumulation_count >= self.target_accumulations
    }

    /// Get accumulated gradients and reset accumulator
    pub fn get_and_reset(&mut self) -> Result<Vec<Array<A, D>>> {
        if !self.is_ready() {
            return Err(OptimError::InvalidConfig(format!(
                "Accumulation not ready: {}/{} steps completed",
                self.accumulation_count, self.target_accumulations
            )));
        }

        let mut result = self.accumulated_gradients.clone();

        // Apply accumulation mode
        match self.mode {
            AccumulationMode::Sum => {
                // Gradients are already summed, nothing to do
            }
            AccumulationMode::Average => {
                let scale = A::one() / A::from(self.accumulation_count).expect("unwrap failed");
                for grad in &mut result {
                    grad.mapv_inplace(|x| x * scale);
                }
            }
        }

        // Reset accumulator
        self.reset();

        Ok(result)
    }

    /// Reset accumulator state
    pub fn reset(&mut self) {
        for grad in &mut self.accumulated_gradients {
            grad.fill(A::zero());
        }
        self.accumulation_count = 0;
    }

    /// Get current accumulation count
    pub fn accumulation_count(&self) -> usize {
        self.accumulation_count
    }

    /// Get target accumulation count
    pub fn target_accumulations(&self) -> usize {
        self.target_accumulations
    }

    /// Set new target accumulation count
    pub fn set_target_accumulations(&mut self, target: usize) {
        self.target_accumulations = target;
    }

    /// Get accumulation mode
    pub fn mode(&self) -> AccumulationMode {
        self.mode
    }

    /// Set accumulation mode
    pub fn set_mode(&mut self, mode: AccumulationMode) {
        self.mode = mode;
    }

    /// Check if accumulator is initialized
    pub fn is_initialized(&self) -> bool {
        self.initialized
    }

    /// Get current progress as a fraction (0.0 to 1.0)
    pub fn progress(&self) -> f64 {
        if self.target_accumulations == 0 {
            1.0
        } else {
            self.accumulation_count as f64 / self.target_accumulations as f64
        }
    }
}

/// Variable accumulation scheduler
pub struct VariableAccumulator<A: Float, D: Dimension> {
    /// Base accumulator
    accumulator: GradientAccumulator<A, D>,
    /// Variable accumulation steps based on conditions
    adaptive_steps: Vec<(AdaptiveStepCondition, usize)>,
    /// Current step count
    step_count: usize,
}

impl<A: Float + ScalarOperand + Debug, D: Dimension + Send + Sync> VariableAccumulator<A, D> {
    /// Create a new variable accumulator
    pub fn new(_initialtarget: usize, mode: AccumulationMode) -> Self {
        Self {
            accumulator: GradientAccumulator::new(_initialtarget, mode),
            adaptive_steps: Vec::new(),
            step_count: 0,
        }
    }

    /// Add a condition-based accumulation rule
    pub fn add_adaptive_rule<F>(&mut self, condition: F, accumulationsteps: usize)
    where
        F: Fn(usize) -> bool + 'static,
    {
        self.adaptive_steps
            .push((Box::new(condition), accumulationsteps));
    }

    /// Update target accumulations based on current step
    fn update_target(&mut self) {
        for (condition, steps) in &self.adaptive_steps {
            if condition(self.step_count) {
                self.accumulator.set_target_accumulations(*steps);
                break;
            }
        }
    }

    /// Accumulate gradients with adaptive targeting
    pub fn accumulate(&mut self, gradients: &[Array<A, D>]) -> Result<()> {
        self.update_target();
        self.accumulator.accumulate(gradients)
    }

    /// Check if accumulation is ready
    pub fn is_ready(&self) -> bool {
        self.accumulator.is_ready()
    }

    /// Get accumulated gradients and advance step
    pub fn get_and_step(&mut self) -> Result<Vec<Array<A, D>>> {
        let result = self.accumulator.get_and_reset()?;
        self.step_count += 1;
        Ok(result)
    }

    /// Get current step count
    pub fn step_count(&self) -> usize {
        self.step_count
    }

    /// Get underlying accumulator
    pub fn accumulator(&self) -> &GradientAccumulator<A, D> {
        &self.accumulator
    }

    /// Get mutable reference to underlying accumulator
    pub fn accumulator_mut(&mut self) -> &mut GradientAccumulator<A, D> {
        &mut self.accumulator
    }
}

/// Micro-batch trainer that uses gradient accumulation
#[derive(Debug)]
pub struct MicroBatchTrainer<A: Float, D: Dimension> {
    /// Gradient accumulator
    accumulator: GradientAccumulator<A, D>,
    /// Micro-batch size
    micro_batch_size: usize,
    /// Effective batch size (micro_batch_size * accumulation_steps)
    effective_batch_size: usize,
}

impl<A: Float + ScalarOperand + Debug, D: Dimension + Send + Sync> MicroBatchTrainer<A, D> {
    /// Create a new micro-batch trainer
    pub fn new(
        micro_batch_size: usize,
        effective_batch_size: usize,
        mode: AccumulationMode,
    ) -> Result<Self> {
        if effective_batch_size < micro_batch_size {
            return Err(OptimError::InvalidConfig(
                "Effective batch _size must be >= micro batch _size".to_string(),
            ));
        }

        let accumulation_steps = effective_batch_size / micro_batch_size;
        let accumulator = GradientAccumulator::new(accumulation_steps, mode);

        Ok(Self {
            accumulator,
            micro_batch_size,
            effective_batch_size,
        })
    }

    /// Process a micro-batch and accumulate gradients
    pub fn process_micro_batch(&mut self, gradients: &[Array<A, D>]) -> Result<()> {
        self.accumulator.accumulate(gradients)
    }

    /// Check if ready for optimizer step
    pub fn ready_for_step(&self) -> bool {
        self.accumulator.is_ready()
    }

    /// Get accumulated gradients for optimizer step
    pub fn get_accumulated_gradients(&mut self) -> Result<Vec<Array<A, D>>> {
        self.accumulator.get_and_reset()
    }

    /// Get micro-batch size
    pub fn micro_batch_size(&self) -> usize {
        self.micro_batch_size
    }

    /// Get effective batch size
    pub fn effective_batch_size(&self) -> usize {
        self.effective_batch_size
    }

    /// Get accumulation progress
    pub fn progress(&self) -> f64 {
        self.accumulator.progress()
    }

    /// Set new effective batch size
    pub fn set_effective_batch_size(&mut self, effective_batchsize: usize) -> Result<()> {
        if effective_batchsize < self.micro_batch_size {
            return Err(OptimError::InvalidConfig(
                "Effective batch _size must be >= micro batch _size".to_string(),
            ));
        }

        self.effective_batch_size = effective_batchsize;
        let accumulation_steps = effective_batchsize / self.micro_batch_size;
        self.accumulator
            .set_target_accumulations(accumulation_steps);
        Ok(())
    }
}

/// Utility functions for gradient accumulation
pub mod utils {
    use super::*;

    /// Calculate optimal micro-batch size given memory constraints
    pub fn calculate_micro_batch_size(
        total_batch_size: usize,
        max_memory_mb: usize,
        param_count: usize,
        bytes_per_param: usize,
    ) -> usize {
        // Estimate memory usage per sample
        let memory_per_sample = param_count * bytes_per_param * 3; // params + grads + activations
        let max_samples = (max_memory_mb * 1_000_000) / memory_per_sample;

        // Choose micro-batch _size that divides total batch _size evenly
        let mut micro_batch_size = max_samples.min(total_batch_size);
        while !total_batch_size.is_multiple_of(micro_batch_size) && micro_batch_size > 1 {
            micro_batch_size -= 1;
        }

        micro_batch_size.max(1)
    }

    /// Calculate accumulation steps needed
    pub fn calculate_accumulation_steps(
        _total_batch_size: usize,
        micro_batch_size: usize,
    ) -> usize {
        _total_batch_size.div_ceil(micro_batch_size) // Ceiling division
    }

    /// Validate gradient accumulation configuration
    pub fn validate_config(
        micro_batch_size: usize,
        effective_batch_size: usize,
        accumulation_steps: usize,
    ) -> Result<()> {
        if micro_batch_size == 0 {
            return Err(OptimError::InvalidConfig(
                "Micro batch _size must be > 0".to_string(),
            ));
        }

        if effective_batch_size == 0 {
            return Err(OptimError::InvalidConfig(
                "Effective batch _size must be > 0".to_string(),
            ));
        }

        if accumulation_steps == 0 {
            return Err(OptimError::InvalidConfig(
                "Accumulation _steps must be > 0".to_string(),
            ));
        }

        if effective_batch_size != micro_batch_size * accumulation_steps {
            return Err(OptimError::InvalidConfig(format!(
                "Effective batch _size ({}) != micro batch _size ({}) * accumulation _steps ({})",
                effective_batch_size, micro_batch_size, accumulation_steps
            )));
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use approx::assert_relative_eq;
    use scirs2_core::ndarray::Array1;

    #[test]
    fn test_gradient_accumulator_sum() {
        let mut accumulator = GradientAccumulator::new(3, AccumulationMode::Sum);

        // First micro-batch
        let grad1 = vec![Array1::from_vec(vec![1.0, 2.0, 3.0])];
        accumulator.accumulate(&grad1).expect("unwrap failed");
        assert!(!accumulator.is_ready());

        // Second micro-batch
        let grad2 = vec![Array1::from_vec(vec![2.0, 3.0, 4.0])];
        accumulator.accumulate(&grad2).expect("unwrap failed");
        assert!(!accumulator.is_ready());

        // Third micro-batch
        let grad3 = vec![Array1::from_vec(vec![1.0, 1.0, 1.0])];
        accumulator.accumulate(&grad3).expect("unwrap failed");
        assert!(accumulator.is_ready());

        // Get accumulated gradients
        let result = accumulator.get_and_reset().expect("unwrap failed");
        assert_eq!(result.len(), 1);
        assert_eq!(
            result[0].as_slice().expect("unwrap failed"),
            &[4.0, 6.0, 8.0]
        ); // Sum of all gradients

        // Should be reset
        assert!(!accumulator.is_ready());
        assert_eq!(accumulator.accumulation_count(), 0);
    }

    #[test]
    fn test_gradient_accumulator_average() {
        let mut accumulator = GradientAccumulator::new(2, AccumulationMode::Average);

        let grad1 = vec![Array1::from_vec(vec![2.0, 4.0])];
        let grad2 = vec![Array1::from_vec(vec![4.0, 2.0])];

        accumulator.accumulate(&grad1).expect("unwrap failed");
        accumulator.accumulate(&grad2).expect("unwrap failed");

        let result = accumulator.get_and_reset().expect("unwrap failed");
        assert_eq!(result[0].as_slice().expect("unwrap failed"), &[3.0, 3.0]); // Average of gradients
    }

    #[test]
    fn test_variable_accumulator() {
        let mut var_accumulator = VariableAccumulator::new(2, AccumulationMode::Sum);

        // Add rule: if step > 5, use 4 accumulation steps
        var_accumulator.add_adaptive_rule(|step| step > 5, 4);

        // First few steps should use 2 accumulations
        let grad = vec![Array1::from_vec(vec![1.0])];
        var_accumulator.accumulate(&grad).expect("unwrap failed");
        var_accumulator.accumulate(&grad).expect("unwrap failed");
        assert!(var_accumulator.is_ready());

        let _result = var_accumulator.get_and_step().expect("unwrap failed");

        // Simulate more steps to trigger adaptive rule
        for _ in 0..6 {
            var_accumulator.accumulate(&grad).expect("unwrap failed");
            var_accumulator.accumulate(&grad).expect("unwrap failed");
            if var_accumulator.is_ready() {
                var_accumulator.get_and_step().expect("unwrap failed");
            }
        }

        // Now should require 4 accumulations
        assert_eq!(var_accumulator.accumulator().target_accumulations(), 4);
    }

    #[test]
    fn test_micro_batch_trainer() {
        let mut trainer = MicroBatchTrainer::new(
            2, // micro batch size
            6, // effective batch size
            AccumulationMode::Sum,
        )
        .expect("unwrap failed");

        assert_eq!(trainer.micro_batch_size(), 2);
        assert_eq!(trainer.effective_batch_size(), 6);

        let grad = vec![Array1::from_vec(vec![1.0, 1.0])];

        // Process 3 micro-batches (to reach effective batch size of 6)
        trainer.process_micro_batch(&grad).expect("unwrap failed");
        assert!(!trainer.ready_for_step());

        trainer.process_micro_batch(&grad).expect("unwrap failed");
        assert!(!trainer.ready_for_step());

        trainer.process_micro_batch(&grad).expect("unwrap failed");
        assert!(trainer.ready_for_step());

        let result = trainer.get_accumulated_gradients().expect("unwrap failed");
        assert_eq!(result[0].as_slice().expect("unwrap failed"), &[3.0, 3.0]); // Sum of 3 micro-batches
    }

    #[test]
    fn test_calculate_micro_batch_size() {
        let micro_batch = utils::calculate_micro_batch_size(
            128,  // total batch size
            100,  // max memory MB
            1000, // param count
            8,    // bytes per param (f64)
        );

        // Should return a size that divides 128 evenly
        assert!(128 % micro_batch == 0);
        assert!(micro_batch > 0);
    }

    #[test]
    fn test_accumulation_steps_calculation() {
        assert_eq!(utils::calculate_accumulation_steps(128, 32), 4);
        assert_eq!(utils::calculate_accumulation_steps(100, 32), 4); // Ceiling division
        assert_eq!(utils::calculate_accumulation_steps(96, 32), 3);
    }

    #[test]
    fn test_config_validation() {
        // Valid config
        utils::validate_config(32, 128, 4).expect("unwrap failed");

        // Invalid: micro batch size is 0
        assert!(utils::validate_config(0, 128, 4).is_err());

        // Invalid: sizes don't match
        assert!(utils::validate_config(32, 100, 4).is_err());
    }

    #[test]
    fn test_accumulator_progress() {
        let mut accumulator = GradientAccumulator::new(4, AccumulationMode::Sum);

        assert_relative_eq!(accumulator.progress(), 0.0);

        let grad = vec![Array1::from_vec(vec![1.0])];

        accumulator.accumulate(&grad).expect("unwrap failed");
        assert_relative_eq!(accumulator.progress(), 0.25);

        accumulator.accumulate(&grad).expect("unwrap failed");
        assert_relative_eq!(accumulator.progress(), 0.5);

        accumulator.accumulate(&grad).expect("unwrap failed");
        assert_relative_eq!(accumulator.progress(), 0.75);

        accumulator.accumulate(&grad).expect("unwrap failed");
        assert_relative_eq!(accumulator.progress(), 1.0);
    }

    #[test]
    fn test_dimension_mismatch_error() {
        let mut accumulator = GradientAccumulator::new(2, AccumulationMode::Sum);

        let grad1 = vec![Array1::from_vec(vec![1.0, 2.0])];
        accumulator.accumulate(&grad1).expect("unwrap failed");

        // Try to accumulate gradients with different dimensions
        let grad2 = vec![Array1::from_vec(vec![1.0, 2.0, 3.0])];
        assert!(accumulator.accumulate(&grad2).is_err());

        // Try to accumulate different number of arrays
        let grad3 = vec![
            Array1::from_vec(vec![1.0, 2.0]),
            Array1::from_vec(vec![3.0, 4.0]),
        ];
        assert!(accumulator.accumulate(&grad3).is_err());
    }

    #[test]
    fn test_get_before_ready_error() {
        let mut accumulator = GradientAccumulator::new(3, AccumulationMode::Sum);

        let grad = vec![Array1::from_vec(vec![1.0])];
        accumulator.accumulate(&grad).expect("unwrap failed");

        // Try to get gradients before accumulation is complete
        assert!(accumulator.get_and_reset().is_err());
    }
}