trustformers-optim 0.1.1

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
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
use crate::{
    adam::{Adam, AdamW},
    sgd::SGD,
};
/// Hardware-Aware Optimizers
///
/// This module provides optimizers specifically designed for different hardware targets:
/// - GPU optimizers with CUDA/ROCm optimizations
/// - TPU optimizers with reduced precision and specific kernels
/// - Mobile optimizers with memory and computation constraints
/// - Edge computing optimizers for IoT devices
use std::collections::HashMap;
use trustformers_core::{errors::Result, tensor::Tensor, traits::Optimizer};

/// Hardware target for optimization
#[derive(Debug, Clone, PartialEq)]
pub enum HardwareTarget {
    GPU {
        memory_gb: f32,
        compute_capability: f32,
        use_tensor_cores: bool,
    },
    TPU {
        version: TPUVersion,
        num_cores: usize,
        use_bfloat16: bool,
    },
    Mobile {
        memory_mb: usize,
        cpu_cores: usize,
        target_latency_ms: f32,
    },
    Edge {
        memory_mb: usize,
        power_budget_mw: f32,
        quantization_bits: u8,
    },
}

#[derive(Debug, Clone, PartialEq)]
pub enum TPUVersion {
    V2,
    V3,
    V4,
    V5,
}

/// Hardware-aware optimizer configuration
#[derive(Debug, Clone)]
pub struct HardwareAwareConfig {
    pub target: HardwareTarget,
    pub base_learning_rate: f32,
    pub enable_fusion: bool,
    pub memory_efficient: bool,
    pub use_mixed_precision: bool,
    pub gradient_compression: Option<CompressionRatio>,
    pub custom_kernels: bool,
}

#[derive(Debug, Clone)]
pub enum CompressionRatio {
    Half,    // 16-bit
    Quarter, // 8-bit
    Eighth,  // 4-bit
}

/// GPU-optimized Adam optimizer
pub struct GPUAdam {
    base_adam: Adam,
    #[allow(dead_code)]
    config: HardwareAwareConfig,
    use_tensor_cores: bool,
    #[allow(dead_code)]
    memory_pool: Option<GPUMemoryPool>,
    #[allow(dead_code)]
    kernel_fusion_cache: HashMap<String, ComputeKernel>,
}

impl GPUAdam {
    pub fn new(config: HardwareAwareConfig) -> Result<Self> {
        if let HardwareTarget::GPU {
            use_tensor_cores, ..
        } = config.target
        {
            let base_adam = Adam::new(config.base_learning_rate, (0.9, 0.999), 1e-8, 0.0);

            let memory_pool =
                if config.memory_efficient { Some(GPUMemoryPool::new()?) } else { None };

            Ok(Self {
                base_adam,
                config,
                use_tensor_cores,
                memory_pool,
                kernel_fusion_cache: HashMap::new(),
            })
        } else {
            Err(
                trustformers_core::errors::TrustformersError::invalid_config(
                    "GPUAdam requires GPU target".to_string(),
                ),
            )
        }
    }

    /// Optimize for specific GPU architecture
    pub fn optimize_for_gpu(&mut self, compute_capability: f32) -> Result<()> {
        // Enable specific optimizations based on compute capability
        match compute_capability {
            cc if cc >= 8.0 => {
                // Ampere and newer: enable advanced tensor core features
                self.enable_sparse_tensor_cores()?;
                self.enable_async_copy()?;
            },
            cc if cc >= 7.0 => {
                // Turing/Volta: enable basic tensor cores
                self.enable_tensor_cores()?;
            },
            _ => {
                // Older architectures: use standard optimizations
                self.enable_memory_coalescing()?;
            },
        }
        Ok(())
    }

    fn enable_sparse_tensor_cores(&mut self) -> Result<()> {
        // Enable sparse matrix optimizations for Ampere
        // This would interface with cuSPARSE or similar libraries
        Ok(())
    }

    fn enable_async_copy(&mut self) -> Result<()> {
        // Enable asynchronous memory transfers
        Ok(())
    }

    fn enable_tensor_cores(&mut self) -> Result<()> {
        // Enable mixed-precision with tensor cores
        self.use_tensor_cores = true;
        Ok(())
    }

    fn enable_memory_coalescing(&mut self) -> Result<()> {
        // Optimize memory access patterns
        Ok(())
    }
}

impl Optimizer for GPUAdam {
    fn update(&mut self, parameter: &mut Tensor, grad: &Tensor) -> Result<()> {
        self.base_adam.update(parameter, grad)
    }

    fn zero_grad(&mut self) {
        self.base_adam.zero_grad()
    }

    fn step(&mut self) {
        self.base_adam.step()
    }

    fn get_lr(&self) -> f32 {
        self.base_adam.get_lr()
    }

    fn set_lr(&mut self, lr: f32) {
        self.base_adam.set_lr(lr)
    }
}

impl GPUAdam {
    #[allow(dead_code)]
    fn can_fuse_operations(&self, parameters: &[Tensor]) -> bool {
        // Check if parameters are suitable for kernel fusion
        parameters.len() < 100 && self.config.enable_fusion
    }

    #[allow(dead_code)]
    fn fused_adam_step(&mut self, parameters: &mut [Tensor], gradients: &[Tensor]) -> Result<()> {
        // Implement fused Adam kernel
        // This would call optimized CUDA/ROCm kernels
        for (param, grad) in parameters.iter_mut().zip(gradients.iter()) {
            self.base_adam.update(param, grad)?;
        }
        self.base_adam.step();
        Ok(())
    }
}

/// TPU-optimized optimizer
pub struct TPUOptimizer {
    base_optimizer: Box<dyn Optimizer>,
    #[allow(dead_code)]
    config: HardwareAwareConfig,
    #[allow(dead_code)]
    tpu_version: TPUVersion,
    use_bfloat16: bool,
    #[allow(dead_code)]
    sharding_strategy: TPUShardingStrategy,
}

#[derive(Debug, Clone)]
pub enum TPUShardingStrategy {
    FullySharded,
    GradientSharded,
    ParameterSharded,
}

impl TPUOptimizer {
    pub fn new(base_optimizer: Box<dyn Optimizer>, config: HardwareAwareConfig) -> Result<Self> {
        if let HardwareTarget::TPU {
            ref version,
            use_bfloat16,
            ..
        } = config.target
        {
            let tpu_version = version.clone();
            Ok(Self {
                base_optimizer,
                config,
                tpu_version,
                use_bfloat16,
                sharding_strategy: TPUShardingStrategy::FullySharded,
            })
        } else {
            Err(
                trustformers_core::errors::TrustformersError::invalid_config(
                    "TPUOptimizer requires TPU target".to_string(),
                ),
            )
        }
    }

    /// Optimize gradient computation for TPU
    #[allow(dead_code)]
    fn tpu_optimized_gradients(&self, gradients: &[Tensor]) -> Result<Vec<Tensor>> {
        let mut optimized = Vec::new();

        for grad in gradients {
            let mut opt_grad = grad.clone();

            // Convert to bfloat16 if enabled
            if self.use_bfloat16 {
                opt_grad = self.convert_to_bfloat16(&opt_grad)?;
            }

            // Apply TPU-specific optimizations
            opt_grad = self.optimize_for_tpu_memory_layout(&opt_grad)?;

            optimized.push(opt_grad);
        }

        Ok(optimized)
    }

    fn convert_to_bfloat16(&self, tensor: &Tensor) -> Result<Tensor> {
        // Convert to bfloat16 for TPU efficiency
        // This would use specialized TPU libraries
        Ok(tensor.clone())
    }

    fn optimize_for_tpu_memory_layout(&self, tensor: &Tensor) -> Result<Tensor> {
        // Optimize tensor layout for TPU memory hierarchy
        Ok(tensor.clone())
    }
}

impl Optimizer for TPUOptimizer {
    fn update(&mut self, parameter: &mut Tensor, grad: &Tensor) -> Result<()> {
        self.base_optimizer.update(parameter, grad)
    }

    fn zero_grad(&mut self) {
        self.base_optimizer.zero_grad()
    }

    fn step(&mut self) {
        self.base_optimizer.step()
    }

    fn get_lr(&self) -> f32 {
        self.base_optimizer.get_lr()
    }

    fn set_lr(&mut self, lr: f32) {
        self.base_optimizer.set_lr(lr)
    }
}

/// Mobile-optimized optimizer with memory and latency constraints
pub struct MobileOptimizer {
    base_optimizer: Box<dyn Optimizer>,
    #[allow(dead_code)]
    config: HardwareAwareConfig,
    #[allow(dead_code)]
    memory_budget_mb: usize,
    #[allow(dead_code)]
    target_latency_ms: f32,
    #[allow(dead_code)]
    quantized_states: bool,
    gradient_compression: CompressionRatio,
}

impl MobileOptimizer {
    pub fn new(base_optimizer: Box<dyn Optimizer>, config: HardwareAwareConfig) -> Result<Self> {
        if let HardwareTarget::Mobile {
            memory_mb,
            target_latency_ms,
            ..
        } = config.target
        {
            let gradient_compression =
                config.gradient_compression.clone().unwrap_or(CompressionRatio::Half);

            Ok(Self {
                base_optimizer,
                config,
                memory_budget_mb: memory_mb,
                target_latency_ms,
                quantized_states: true,
                gradient_compression,
            })
        } else {
            Err(
                trustformers_core::errors::TrustformersError::invalid_config(
                    "MobileOptimizer requires Mobile target".to_string(),
                ),
            )
        }
    }

    /// Compress gradients for mobile efficiency
    #[allow(dead_code)]
    fn compress_gradients(&self, gradients: &[Tensor]) -> Result<Vec<Tensor>> {
        let mut compressed = Vec::new();

        for grad in gradients {
            let compressed_grad = match self.gradient_compression {
                CompressionRatio::Half => self.to_fp16(grad)?,
                CompressionRatio::Quarter => self.to_int8(grad)?,
                CompressionRatio::Eighth => self.to_int4(grad)?,
            };
            compressed.push(compressed_grad);
        }

        Ok(compressed)
    }

    fn to_fp16(&self, tensor: &Tensor) -> Result<Tensor> {
        // Convert to 16-bit floating point
        match tensor {
            Tensor::F32(data) => {
                // Convert f32 to f16 using IEEE 754 half-precision format
                let fp16_data: Vec<f32> = data
                    .iter()
                    .map(|&x| {
                        // Simple f32 to f16 conversion (approximation)
                        // In a real implementation, you'd use proper f16 conversion
                        if x.is_nan() {
                            f32::NAN
                        } else if x.is_infinite() {
                            if x > 0.0 {
                                65504.0
                            } else {
                                -65504.0
                            } // Max f16 value
                        } else {
                            // Clamp to f16 range and round
                            x.clamp(-65504.0, 65504.0)
                        }
                    })
                    .collect();
                Ok(Tensor::new(fp16_data)?)
            },
            _ => Ok(tensor.clone()),
        }
    }

    fn to_int8(&self, tensor: &Tensor) -> Result<Tensor> {
        // Quantize to 8-bit integers using dynamic range quantization
        match tensor {
            Tensor::F32(data) => {
                if data.is_empty() {
                    return Ok(tensor.clone());
                }

                // Find min and max values for dynamic range quantization
                let min_val = data.iter().fold(f32::INFINITY, |a, &b| a.min(b));
                let max_val = data.iter().fold(f32::NEG_INFINITY, |a, &b| a.max(b));

                // Avoid division by zero
                if (max_val - min_val).abs() < f32::EPSILON {
                    return Ok(tensor.clone());
                }

                // Scale factor for quantization
                let scale = (max_val - min_val) / 255.0;

                // Quantize to 8-bit and dequantize back to f32
                let quantized_data: Vec<f32> = data
                    .iter()
                    .map(|&x| {
                        let quantized = ((x - min_val) / scale).round().clamp(0.0, 255.0) as u8;
                        min_val + (quantized as f32) * scale
                    })
                    .collect();

                Ok(Tensor::new(quantized_data)?)
            },
            _ => Ok(tensor.clone()),
        }
    }

    fn to_int4(&self, tensor: &Tensor) -> Result<Tensor> {
        // Quantize to 4-bit integers using dynamic range quantization
        match tensor {
            Tensor::F32(data) => {
                if data.is_empty() {
                    return Ok(tensor.clone());
                }

                // Find min and max values for dynamic range quantization
                let min_val = data.iter().fold(f32::INFINITY, |a, &b| a.min(b));
                let max_val = data.iter().fold(f32::NEG_INFINITY, |a, &b| a.max(b));

                // Avoid division by zero
                if (max_val - min_val).abs() < f32::EPSILON {
                    return Ok(tensor.clone());
                }

                // Scale factor for 4-bit quantization (0-15 range)
                let scale = (max_val - min_val) / 15.0;

                // Quantize to 4-bit and dequantize back to f32
                let quantized_data: Vec<f32> = data
                    .iter()
                    .map(|&x| {
                        let quantized = ((x - min_val) / scale).round().clamp(0.0, 15.0) as u8;
                        min_val + (quantized as f32) * scale
                    })
                    .collect();

                Ok(Tensor::new(quantized_data)?)
            },
            _ => Ok(tensor.clone()),
        }
    }

    /// Check if memory usage is within budget
    #[allow(dead_code)]
    fn check_memory_budget(&self, parameters: &[Tensor]) -> Result<bool> {
        // Calculate current memory usage and compare to budget
        let mut total_memory_bytes = 0;

        for tensor in parameters {
            match tensor {
                Tensor::F32(data) => {
                    total_memory_bytes += data.len() * 4; // 4 bytes per f32
                },
                // For other tensor types, provide realistic memory estimation based on common sizes
                _ => {
                    // Conservative estimation: assume average tensor has 1000 elements of f32 size
                    // This accounts for various tensor types (I8, I16, I32, F64, etc.)
                    total_memory_bytes += 1000 * 4; // 4KB per unknown tensor (reasonable estimation)
                },
            }
        }

        // Add optimizer state memory overhead (estimated)
        total_memory_bytes += total_memory_bytes; // Assume optimizer state is same size as parameters

        // Convert to MB for comparison
        let total_memory_mb = total_memory_bytes as f32 / (1024.0 * 1024.0);

        // Check against mobile memory budget
        Ok(total_memory_mb <= self.memory_budget_mb as f32 * 0.8) // Use 80% of available memory
    }
}

impl Optimizer for MobileOptimizer {
    fn update(&mut self, parameter: &mut Tensor, grad: &Tensor) -> Result<()> {
        self.base_optimizer.update(parameter, grad)
    }

    fn zero_grad(&mut self) {
        self.base_optimizer.zero_grad()
    }

    fn step(&mut self) {
        self.base_optimizer.step()
    }

    fn get_lr(&self) -> f32 {
        self.base_optimizer.get_lr()
    }

    fn set_lr(&mut self, lr: f32) {
        self.base_optimizer.set_lr(lr)
    }
}

/// Edge computing optimizer for IoT devices
pub struct EdgeOptimizer {
    base_optimizer: Box<dyn Optimizer>,
    #[allow(dead_code)]
    config: HardwareAwareConfig,
    power_budget_mw: f32,
    quantization_bits: u8,
    #[allow(dead_code)]
    adaptive_precision: bool,
}

impl EdgeOptimizer {
    pub fn new(base_optimizer: Box<dyn Optimizer>, config: HardwareAwareConfig) -> Result<Self> {
        if let HardwareTarget::Edge {
            power_budget_mw,
            quantization_bits,
            ..
        } = config.target
        {
            Ok(Self {
                base_optimizer,
                config,
                power_budget_mw,
                quantization_bits,
                adaptive_precision: true,
            })
        } else {
            Err(
                trustformers_core::errors::TrustformersError::invalid_config(
                    "EdgeOptimizer requires Edge target".to_string(),
                ),
            )
        }
    }

    /// Adapt precision based on power constraints
    #[allow(dead_code)]
    fn adapt_precision(&mut self, current_power_mw: f32) -> Result<()> {
        if current_power_mw > self.power_budget_mw * 0.9 {
            // Reduce precision to save power
            self.quantization_bits = std::cmp::max(4, self.quantization_bits - 1);
        } else if current_power_mw < self.power_budget_mw * 0.5 {
            // Increase precision when power budget allows
            self.quantization_bits = std::cmp::min(16, self.quantization_bits + 1);
        }
        Ok(())
    }

    /// Quantize gradients to specified bit width
    #[allow(dead_code)]
    fn quantize_gradients(&self, gradients: &[Tensor]) -> Result<Vec<Tensor>> {
        let mut quantized = Vec::new();

        for grad in gradients {
            let quantized_grad = self.quantize_tensor(grad, self.quantization_bits)?;
            quantized.push(quantized_grad);
        }

        Ok(quantized)
    }

    #[allow(dead_code)]
    fn quantize_tensor(&self, tensor: &Tensor, bits: u8) -> Result<Tensor> {
        // Implement quantization to specified bit width using dynamic range quantization
        match tensor {
            Tensor::F32(data) => {
                if data.is_empty() || bits == 0 || bits > 8 {
                    return Ok(tensor.clone());
                }

                // Find min and max values for dynamic range quantization
                let min_val = data.iter().fold(f32::INFINITY, |a, &b| a.min(b));
                let max_val = data.iter().fold(f32::NEG_INFINITY, |a, &b| a.max(b));

                // Avoid division by zero
                if (max_val - min_val).abs() < f32::EPSILON {
                    return Ok(tensor.clone());
                }

                // Calculate quantization levels
                let levels = (1 << bits) - 1; // 2^bits - 1
                let scale = (max_val - min_val) / levels as f32;

                // Quantize and dequantize
                let quantized_data: Vec<f32> = data
                    .iter()
                    .map(|&x| {
                        let quantized =
                            ((x - min_val) / scale).round().clamp(0.0, levels as f32) as u32;
                        min_val + (quantized as f32) * scale
                    })
                    .collect();

                Ok(Tensor::new(quantized_data)?)
            },
            _ => Ok(tensor.clone()),
        }
    }
}

impl Optimizer for EdgeOptimizer {
    fn update(&mut self, parameter: &mut Tensor, grad: &Tensor) -> Result<()> {
        self.base_optimizer.update(parameter, grad)
    }

    fn zero_grad(&mut self) {
        self.base_optimizer.zero_grad()
    }

    fn step(&mut self) {
        self.base_optimizer.step()
    }

    fn get_lr(&self) -> f32 {
        self.base_optimizer.get_lr()
    }

    fn set_lr(&mut self, lr: f32) {
        self.base_optimizer.set_lr(lr)
    }
}

impl EdgeOptimizer {
    #[allow(dead_code)]
    fn estimate_power_usage(&self, gradients: &[Tensor]) -> Result<f32> {
        // Estimate power consumption based on computation complexity
        let mut total_operations = 0;

        // Count operations needed for gradient updates
        for tensor in gradients {
            match tensor {
                Tensor::F32(data) => {
                    // Each parameter update involves: gradient computation, momentum update, parameter update
                    total_operations += data.len() * 3;
                },
                _ => {
                    // For unknown tensor types, estimate based on typical tensor size
                    // Conservative estimation: assume 1000 elements per tensor with 3 operations each
                    total_operations += 1000 * 3; // 3000 operations per unknown tensor
                },
            }
        }

        // Base power consumption per operation (estimated for edge devices)
        let power_per_operation_mw = 0.001; // 1 microWatt per operation
        let computational_power = total_operations as f32 * power_per_operation_mw;

        // Add base power consumption for memory access and control
        let base_power = self.power_budget_mw * 0.2; // 20% base power

        // Add power for quantization overhead
        let quantization_power = if self.quantization_bits < 8 {
            self.power_budget_mw * 0.1 // 10% overhead for quantization
        } else {
            0.0
        };

        let total_estimated_power = base_power + computational_power + quantization_power;

        // Ensure we don't exceed the power budget
        Ok(total_estimated_power.min(self.power_budget_mw))
    }
}

/// Helper structures
struct GPUMemoryPool {
    // GPU memory pool for efficient allocation
}

impl GPUMemoryPool {
    fn new() -> Result<Self> {
        Ok(Self {})
    }
}

struct ComputeKernel {
    // Cached compute kernels for GPU
}

/// Factory functions for creating hardware-aware optimizers
pub fn create_gpu_adam(memory_gb: f32, compute_capability: f32) -> Result<GPUAdam> {
    let config = HardwareAwareConfig {
        target: HardwareTarget::GPU {
            memory_gb,
            compute_capability,
            use_tensor_cores: compute_capability >= 7.0,
        },
        base_learning_rate: 1e-4,
        enable_fusion: true,
        memory_efficient: true,
        use_mixed_precision: true,
        gradient_compression: Some(CompressionRatio::Half),
        custom_kernels: true,
    };

    GPUAdam::new(config)
}

pub fn create_tpu_optimizer(version: TPUVersion, num_cores: usize) -> Result<TPUOptimizer> {
    let config = HardwareAwareConfig {
        target: HardwareTarget::TPU {
            version: version.clone(),
            num_cores,
            use_bfloat16: true,
        },
        base_learning_rate: 1e-4,
        enable_fusion: true,
        memory_efficient: true,
        use_mixed_precision: true,
        gradient_compression: None,
        custom_kernels: true,
    };

    let base_optimizer = Box::new(AdamW::new(1e-4, (0.9, 0.999), 1e-8, 0.01));
    TPUOptimizer::new(base_optimizer, config)
}

pub fn create_mobile_optimizer(
    memory_mb: usize,
    target_latency_ms: f32,
) -> Result<MobileOptimizer> {
    let config = HardwareAwareConfig {
        target: HardwareTarget::Mobile {
            memory_mb,
            cpu_cores: 4,
            target_latency_ms,
        },
        base_learning_rate: 1e-4,
        enable_fusion: false,
        memory_efficient: true,
        use_mixed_precision: true,
        gradient_compression: Some(CompressionRatio::Quarter),
        custom_kernels: false,
    };

    let base_optimizer = Box::new(SGD::new(1e-3, 0.9, 0.0, false));
    MobileOptimizer::new(base_optimizer, config)
}

pub fn create_edge_optimizer(memory_mb: usize, power_budget_mw: f32) -> Result<EdgeOptimizer> {
    let config = HardwareAwareConfig {
        target: HardwareTarget::Edge {
            memory_mb,
            power_budget_mw,
            quantization_bits: 8,
        },
        base_learning_rate: 1e-3,
        enable_fusion: false,
        memory_efficient: true,
        use_mixed_precision: false,
        gradient_compression: Some(CompressionRatio::Eighth),
        custom_kernels: false,
    };

    let base_optimizer = Box::new(SGD::new(1e-3, 0.5, 0.0, false));
    EdgeOptimizer::new(base_optimizer, config)
}

#[cfg(test)]
#[path = "hardware_aware_tests.rs"]
mod hardware_aware_tests;