trustformers-optim 0.1.0

Optimizers for TrustformeRS
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
593
594
595
596
597
598
599
600
601
602
603
//! # Asynchronous Optimization Methods
//!
//! This module implements asynchronous optimization algorithms for distributed
//! training where workers can update parameters without strict synchronization.
//!
//! ## Available Methods
//!
//! - **Async SGD**: Asynchronous stochastic gradient descent
//! - **Hogwild!**: Lock-free asynchronous SGD for sparse features
//! - **Delayed Gradient**: Methods that handle stale gradients
//! - **Elastic Averaging SGD**: Combines local and global parameter averaging

use anyhow::Result;
use parking_lot::{Mutex, RwLock};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};
use trustformers_core::tensor::Tensor;

/// Configuration for asynchronous SGD.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AsyncSGDConfig {
    /// Learning rate
    pub learning_rate: f32,
    /// Momentum coefficient
    pub momentum: f32,
    /// Weight decay
    pub weight_decay: f32,
    /// Maximum allowed staleness for gradient updates
    pub max_staleness: usize,
    /// Staleness adaptive factor
    pub staleness_factor: f32,
}

impl Default for AsyncSGDConfig {
    fn default() -> Self {
        Self {
            learning_rate: 1e-3,
            momentum: 0.9,
            weight_decay: 0.0,
            max_staleness: 10,
            staleness_factor: 0.9,
        }
    }
}

/// Configuration for Hogwild! optimizer.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HogwildConfig {
    /// Learning rate
    pub learning_rate: f32,
    /// Sparse update ratio (fraction of parameters updated per step)
    pub sparse_ratio: f32,
    /// Maximum number of concurrent workers
    pub max_workers: usize,
}

impl Default for HogwildConfig {
    fn default() -> Self {
        Self {
            learning_rate: 1e-3,
            sparse_ratio: 0.1,
            max_workers: 4,
        }
    }
}

/// Configuration for delayed gradient methods.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DelayedGradientConfig {
    /// Base learning rate
    pub learning_rate: f32,
    /// Maximum gradient delay (in steps)
    pub max_delay: usize,
    /// Delay compensation method
    pub compensation_method: DelayCompensationMethod,
    /// Compensation factor
    pub compensation_factor: f32,
}

impl Default for DelayedGradientConfig {
    fn default() -> Self {
        Self {
            learning_rate: 1e-3,
            max_delay: 20,
            compensation_method: DelayCompensationMethod::LinearDecay,
            compensation_factor: 0.5,
        }
    }
}

/// Methods for compensating gradient delays.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum DelayCompensationMethod {
    /// No compensation
    None,
    /// Linear decay based on delay
    LinearDecay,
    /// Exponential decay based on delay
    ExponentialDecay,
    /// Adaptive compensation
    Adaptive,
}

/// Configuration for Elastic Averaging SGD.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ElasticAveragingConfig {
    /// Learning rate
    pub learning_rate: f32,
    /// Elastic force coefficient
    pub alpha: f32,
    /// Communication period (steps between synchronization)
    pub tau: usize,
    /// Beta parameter for moving average
    pub beta: f32,
}

impl Default for ElasticAveragingConfig {
    fn default() -> Self {
        Self {
            learning_rate: 1e-3,
            alpha: 0.6,
            tau: 10,
            beta: 0.9,
        }
    }
}

/// Shared parameter server for asynchronous optimization.
pub struct ParameterServer {
    /// Global parameters
    parameters: Arc<RwLock<Vec<Tensor>>>,
    /// Global step counter
    global_step: AtomicUsize,
    /// Parameter version counters
    version_counters: Arc<Mutex<Vec<usize>>>,
    /// Worker update timestamps
    worker_timestamps: Arc<Mutex<HashMap<usize, Instant>>>,
}

impl ParameterServer {
    /// Create a new parameter server.
    pub fn new(initial_parameters: Vec<Tensor>) -> Self {
        let param_count = initial_parameters.len();
        Self {
            parameters: Arc::new(RwLock::new(initial_parameters)),
            global_step: AtomicUsize::new(0),
            version_counters: Arc::new(Mutex::new(vec![0; param_count])),
            worker_timestamps: Arc::new(Mutex::new(HashMap::new())),
        }
    }

    /// Get current parameters for a worker.
    pub fn get_parameters(&self, worker_id: usize) -> Result<(Vec<Tensor>, Vec<usize>)> {
        let params = self.parameters.read().clone();
        let versions = self.version_counters.lock().clone();

        // Update worker timestamp
        let mut timestamps = self.worker_timestamps.lock();
        timestamps.insert(worker_id, Instant::now());

        Ok((params, versions))
    }

    /// Update parameters with gradients from a worker.
    pub fn update_parameters(
        &self,
        worker_id: usize,
        gradients: Vec<Tensor>,
        param_versions: Vec<usize>,
        learning_rate: f32,
    ) -> Result<()> {
        let _current_step = self.global_step.load(Ordering::SeqCst);

        // Check staleness
        let staleness = self.compute_staleness(worker_id, &param_versions)?;
        if staleness > 10 {
            // Skip very stale updates
            return Ok(());
        }

        // Apply staleness compensation
        let compensated_lr = learning_rate * (1.0 / (1.0 + staleness as f32 * 0.1));

        // Update parameters
        {
            let mut params = self.parameters.write();
            let mut versions = self.version_counters.lock();

            for (i, gradient) in gradients.iter().enumerate() {
                if i < params.len() {
                    let update = gradient.mul_scalar(compensated_lr)?;
                    params[i] = params[i].sub(&update)?;
                    versions[i] += 1;
                }
            }
        }

        self.global_step.fetch_add(1, Ordering::SeqCst);
        Ok(())
    }

    fn compute_staleness(&self, _worker_id: usize, param_versions: &[usize]) -> Result<usize> {
        let current_versions = self.version_counters.lock();
        let max_staleness = param_versions
            .iter()
            .zip(current_versions.iter())
            .map(|(old, new)| new.saturating_sub(*old))
            .max()
            .unwrap_or(0);
        Ok(max_staleness)
    }

    /// Get current global step.
    pub fn get_global_step(&self) -> usize {
        self.global_step.load(Ordering::SeqCst)
    }
}

/// Asynchronous SGD optimizer.
pub struct AsyncSGD {
    config: AsyncSGDConfig,
    worker_id: usize,
    parameter_server: Arc<ParameterServer>,
    momentum_buffers: Vec<Tensor>,
    local_parameters: Vec<Tensor>,
    param_versions: Vec<usize>,
    last_sync_step: usize,
}

impl AsyncSGD {
    /// Create a new async SGD optimizer.
    pub fn new(
        config: AsyncSGDConfig,
        worker_id: usize,
        parameter_server: Arc<ParameterServer>,
    ) -> Result<Self> {
        let (params, versions) = parameter_server.get_parameters(worker_id)?;
        let param_count = params.len();

        Ok(Self {
            config,
            worker_id,
            parameter_server,
            momentum_buffers: (0..param_count)
                .map(|i| Tensor::zeros(&params[i].shape()).map_err(anyhow::Error::from))
                .collect::<Result<Vec<_>>>()?,
            local_parameters: params,
            param_versions: versions,
            last_sync_step: 0,
        })
    }

    /// Perform an optimization step.
    pub fn step(&mut self, gradients: &[Tensor]) -> Result<()> {
        // Check if we need to sync with parameter server
        let current_step = self.parameter_server.get_global_step();
        let staleness = current_step - self.last_sync_step;

        if staleness > self.config.max_staleness {
            self.sync_with_server()?;
        }

        // Apply momentum and update local parameters
        for (i, gradient) in gradients.iter().enumerate() {
            if i < self.local_parameters.len() {
                // Apply weight decay
                let effective_grad = if self.config.weight_decay > 0.0 {
                    gradient.add(&self.local_parameters[i].mul_scalar(self.config.weight_decay)?)?
                } else {
                    gradient.clone()
                };

                // Update momentum
                self.momentum_buffers[i] = self.momentum_buffers[i]
                    .mul_scalar(self.config.momentum)?
                    .add(&effective_grad)?;

                // Apply staleness compensation
                let staleness_factor = self.config.staleness_factor.powi(staleness as i32);
                let compensated_lr = self.config.learning_rate * staleness_factor;

                // Update local parameters
                let update = self.momentum_buffers[i].mul_scalar(compensated_lr)?;
                self.local_parameters[i] = self.local_parameters[i].sub(&update)?;
            }
        }

        // Send updates to parameter server periodically
        if current_step % 5 == 0 {
            self.push_to_server(gradients)?;
        }

        Ok(())
    }

    fn sync_with_server(&mut self) -> Result<()> {
        let (params, versions) = self.parameter_server.get_parameters(self.worker_id)?;
        self.local_parameters = params;
        self.param_versions = versions;
        self.last_sync_step = self.parameter_server.get_global_step();
        Ok(())
    }

    fn push_to_server(&self, gradients: &[Tensor]) -> Result<()> {
        self.parameter_server.update_parameters(
            self.worker_id,
            gradients.to_vec(),
            self.param_versions.clone(),
            self.config.learning_rate,
        )
    }

    /// Get current local parameters.
    pub fn get_parameters(&self) -> &[Tensor] {
        &self.local_parameters
    }
}

/// Hogwild! optimizer for sparse features.
pub struct Hogwild {
    config: HogwildConfig,
    #[allow(dead_code)]
    worker_id: usize,
    shared_parameters: Arc<RwLock<Vec<Tensor>>>,
    local_step: usize,
}

impl Hogwild {
    /// Create a new Hogwild! optimizer.
    pub fn new(
        config: HogwildConfig,
        worker_id: usize,
        shared_parameters: Arc<RwLock<Vec<Tensor>>>,
    ) -> Self {
        Self {
            config,
            worker_id,
            shared_parameters,
            local_step: 0,
        }
    }

    /// Perform sparse parameter update.
    pub fn sparse_step(&mut self, sparse_gradients: &[(usize, Tensor)]) -> Result<()> {
        // Lock-free updates for sparse gradients
        // In practice, this would use atomic operations for true lock-free behavior

        for &(param_idx, ref gradient) in sparse_gradients {
            {
                let params = self.shared_parameters.read();
                if param_idx >= params.len() {
                    continue;
                }
            } // Release read lock

            // This is a simplified version - real Hogwild! uses lock-free atomic updates
            let mut params_write = self.shared_parameters.write();
            let update = gradient.mul_scalar(self.config.learning_rate)?;
            params_write[param_idx] = params_write[param_idx].sub(&update)?;
        }

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

    /// Generate sparse gradient indices based on sparse ratio.
    pub fn select_sparse_indices(&self, total_params: usize) -> Vec<usize> {
        use scirs2_core::random::*; // SciRS2 Integration Policy

        let num_sparse = (total_params as f32 * self.config.sparse_ratio) as usize;
        let mut indices: Vec<usize> = (0..total_params).collect();
        let mut rng = thread_rng();
        indices.shuffle(rng.rng_mut());
        indices.truncate(num_sparse);
        indices
    }
}

/// Delayed gradient optimizer.
pub struct DelayedGradient {
    config: DelayedGradientConfig,
    parameters: Vec<Tensor>,
    gradient_buffer: Vec<(Tensor, usize, Instant)>, // (gradient, delay, timestamp)
    current_step: usize,
}

impl DelayedGradient {
    /// Create a new delayed gradient optimizer.
    pub fn new(config: DelayedGradientConfig, initial_parameters: Vec<Tensor>) -> Self {
        Self {
            config,
            parameters: initial_parameters,
            gradient_buffer: Vec::new(),
            current_step: 0,
        }
    }

    /// Add a delayed gradient to the buffer.
    pub fn add_delayed_gradient(&mut self, gradient: Tensor, delay: usize) {
        self.gradient_buffer.push((gradient, delay, Instant::now()));
    }

    /// Process delayed gradients and update parameters.
    pub fn step(&mut self) -> Result<()> {
        self.current_step += 1;

        // Process gradients that are ready
        let mut i = 0;
        while i < self.gradient_buffer.len() {
            let (ref gradient, delay, timestamp) = &self.gradient_buffer[i];
            let age = timestamp.elapsed();

            if age >= Duration::from_millis((*delay as u64) * 10) {
                // Apply delay compensation
                let compensation = self.compute_delay_compensation(*delay)?;
                let compensated_lr = self.config.learning_rate * compensation;

                // Update parameters
                for (j, param) in self.parameters.iter_mut().enumerate() {
                    if j < 1 {
                        // Assuming single parameter for simplicity
                        let update = gradient.mul_scalar(compensated_lr)?;
                        *param = param.sub(&update)?;
                    }
                }

                self.gradient_buffer.remove(i);
            } else {
                i += 1;
            }
        }

        Ok(())
    }

    fn compute_delay_compensation(&self, delay: usize) -> Result<f32> {
        if delay > self.config.max_delay {
            return Ok(0.0); // Discard very old gradients
        }

        let delay_ratio = delay as f32 / self.config.max_delay as f32;

        let compensation = match self.config.compensation_method {
            DelayCompensationMethod::None => 1.0,
            DelayCompensationMethod::LinearDecay => {
                1.0 - delay_ratio * self.config.compensation_factor
            },
            DelayCompensationMethod::ExponentialDecay => {
                (-delay_ratio * self.config.compensation_factor).exp()
            },
            DelayCompensationMethod::Adaptive => {
                // Simple adaptive scheme
                1.0 / (1.0 + delay_ratio * self.config.compensation_factor)
            },
        };

        Ok(compensation.max(0.1)) // Minimum 10% of original learning rate
    }

    /// Get current parameters.
    pub fn get_parameters(&self) -> &[Tensor] {
        &self.parameters
    }
}

/// Elastic Averaging SGD optimizer.
pub struct ElasticAveraging {
    config: ElasticAveragingConfig,
    #[allow(dead_code)]
    worker_id: usize,
    local_parameters: Vec<Tensor>,
    global_parameters: Arc<RwLock<Vec<Tensor>>>,
    elastic_force: Vec<Tensor>,
    local_step: usize,
    last_communication: usize,
}

impl ElasticAveraging {
    /// Create a new Elastic Averaging SGD optimizer.
    pub fn new(
        config: ElasticAveragingConfig,
        worker_id: usize,
        global_parameters: Arc<RwLock<Vec<Tensor>>>,
    ) -> Result<Self> {
        let global_params = global_parameters.read().clone();
        let param_count = global_params.len();

        Ok(Self {
            config,
            worker_id,
            local_parameters: global_params.clone(),
            global_parameters,
            elastic_force: (0..param_count)
                .map(|i| Tensor::zeros(&global_params[i].shape()).map_err(anyhow::Error::from))
                .collect::<Result<Vec<_>>>()?,
            local_step: 0,
            last_communication: 0,
        })
    }

    /// Perform optimization step with elastic averaging.
    pub fn step(&mut self, gradients: &[Tensor]) -> Result<()> {
        // Update local parameters with gradients
        for (i, gradient) in gradients.iter().enumerate() {
            if i < self.local_parameters.len() {
                let update = gradient.mul_scalar(self.config.learning_rate)?;
                self.local_parameters[i] = self.local_parameters[i].sub(&update)?;
            }
        }

        // Apply elastic force
        let global_params = self.global_parameters.read();
        for i in 0..self.local_parameters.len() {
            let diff = self.local_parameters[i].sub(&global_params[i])?;
            self.elastic_force[i] = diff.mul_scalar(self.config.alpha)?;
            let elastic_update = self.elastic_force[i].mul_scalar(self.config.learning_rate)?;
            self.local_parameters[i] = self.local_parameters[i].sub(&elastic_update)?;
        }
        drop(global_params);

        self.local_step += 1;

        // Communicate with global parameters periodically
        if self.local_step - self.last_communication >= self.config.tau {
            self.communicate_with_global()?;
            self.last_communication = self.local_step;
        }

        Ok(())
    }

    fn communicate_with_global(&mut self) -> Result<()> {
        let mut global_params = self.global_parameters.write();

        // Update global parameters with moving average
        for i in 0..global_params.len() {
            let local_contrib = self.local_parameters[i].mul_scalar(1.0 - self.config.beta)?;
            let global_contrib = global_params[i].mul_scalar(self.config.beta)?;
            global_params[i] = local_contrib.add(&global_contrib)?;
        }

        // Update local parameters from global
        self.local_parameters = global_params.clone();

        Ok(())
    }

    /// Get current local parameters.
    pub fn get_parameters(&self) -> &[Tensor] {
        &self.local_parameters
    }
}

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

    #[test]
    fn test_async_sgd_config() {
        let config = AsyncSGDConfig::default();
        assert_eq!(config.learning_rate, 1e-3);
        assert_eq!(config.momentum, 0.9);
        assert_eq!(config.max_staleness, 10);
    }

    #[test]
    fn test_hogwild_config() {
        let config = HogwildConfig::default();
        assert_eq!(config.learning_rate, 1e-3);
        assert_eq!(config.sparse_ratio, 0.1);
        assert_eq!(config.max_workers, 4);
    }

    #[test]
    fn test_delayed_gradient_config() {
        let config = DelayedGradientConfig::default();
        assert_eq!(config.learning_rate, 1e-3);
        assert_eq!(config.max_delay, 20);
        assert!(matches!(
            config.compensation_method,
            DelayCompensationMethod::LinearDecay
        ));
    }

    #[test]
    fn test_parameter_server_creation() {
        let params = vec![Tensor::zeros(&[10]).expect("Failed to create tensor")];
        let server = ParameterServer::new(params);
        assert_eq!(server.get_global_step(), 0);
    }

    #[test]
    fn test_elastic_averaging_config() {
        let config = ElasticAveragingConfig::default();
        assert_eq!(config.learning_rate, 1e-3);
        assert_eq!(config.alpha, 0.6);
        assert_eq!(config.tau, 10);
        assert_eq!(config.beta, 0.9);
    }
}