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
//! GPU kernel fusion optimizations for high-performance optimization.
//!
//! This module provides fused kernels that combine multiple optimization operations
//! into single GPU kernels, reducing memory bandwidth requirements and improving
//! performance through reduced kernel launch overhead.
//!
//! # Key Features
//!
//! - **Fused Adam Kernels**: Combine momentum, variance, and parameter updates
//! - **Multi-Parameter Fusion**: Process multiple parameters in single kernel
//! - **Memory Coalescing**: Optimize memory access patterns for GPU
//! - **Warp-Level Optimizations**: Leverage GPU warp-level primitives
//! - **Mixed Precision Support**: Efficient FP16/FP32 mixed precision

use crate::common::{BiasCorrection, ParameterUpdate};
use std::collections::HashMap;
use trustformers_core::errors::{Result, TrustformersError};
use trustformers_core::tensor::Tensor;
use trustformers_core::traits::Optimizer;

/// Configuration for GPU kernel fusion optimization.
#[derive(Debug, Clone)]
pub struct KernelFusionConfig {
    /// Target GPU compute capability (e.g., 7.5 for V100, 8.0 for A100)
    pub compute_capability: (u32, u32),
    /// Warp size (typically 32 for NVIDIA GPUs)
    pub warp_size: usize,
    /// Maximum threads per block
    pub max_threads_per_block: usize,
    /// Shared memory size per block in bytes
    pub shared_memory_size: usize,
    /// Enable mixed precision (FP16/FP32) kernels
    pub mixed_precision: bool,
    /// Enable tensor core operations where possible
    pub use_tensor_cores: bool,
    /// Memory coalescing optimization level
    pub coalescing_level: CoalescingLevel,
}

/// Memory coalescing optimization levels.
#[derive(Debug, Clone, Copy)]
pub enum CoalescingLevel {
    /// No coalescing optimization
    None,
    /// Basic coalescing (align to 32-byte boundaries)
    Basic,
    /// Advanced coalescing (align to 128-byte boundaries)
    Advanced,
    /// Optimal coalescing (full cache line utilization)
    Optimal,
}

impl Default for KernelFusionConfig {
    fn default() -> Self {
        Self {
            compute_capability: (7, 5), // V100 baseline
            warp_size: 32,
            max_threads_per_block: 1024,
            shared_memory_size: 48 * 1024, // 48KB
            mixed_precision: false,
            use_tensor_cores: false,
            coalescing_level: CoalescingLevel::Advanced,
        }
    }
}

impl KernelFusionConfig {
    /// Creates configuration for A100 GPUs.
    pub fn a100() -> Self {
        Self {
            compute_capability: (8, 0),
            shared_memory_size: 164 * 1024, // 164KB
            use_tensor_cores: true,
            mixed_precision: true,
            coalescing_level: CoalescingLevel::Optimal,
            ..Default::default()
        }
    }

    /// Creates configuration for H100 GPUs.
    pub fn h100() -> Self {
        Self {
            compute_capability: (9, 0),
            shared_memory_size: 228 * 1024, // 228KB
            use_tensor_cores: true,
            mixed_precision: true,
            coalescing_level: CoalescingLevel::Optimal,
            ..Default::default()
        }
    }

    /// Creates configuration for RTX 4090.
    pub fn rtx4090() -> Self {
        Self {
            compute_capability: (8, 9),
            shared_memory_size: 100 * 1024, // 100KB
            use_tensor_cores: true,
            mixed_precision: true,
            coalescing_level: CoalescingLevel::Optimal,
            ..Default::default()
        }
    }

    /// Gets optimal block size for given parameter count.
    pub fn optimal_block_size(&self, param_count: usize) -> usize {
        let warp_aligned = param_count.div_ceil(self.warp_size) * self.warp_size;
        warp_aligned.min(self.max_threads_per_block)
    }

    /// Gets memory alignment requirement based on coalescing level.
    pub fn memory_alignment(&self) -> usize {
        match self.coalescing_level {
            CoalescingLevel::None => 4,       // 4 bytes (1 float)
            CoalescingLevel::Basic => 32,     // 32 bytes
            CoalescingLevel::Advanced => 128, // 128 bytes
            CoalescingLevel::Optimal => 256,  // 256 bytes (cache line)
        }
    }
}

/// GPU memory layout optimized for kernel fusion.
#[derive(Debug)]
pub struct FusedGPUState {
    /// Fused parameter data (parameters, momentum, variance interleaved)
    fused_buffers: HashMap<String, FusedParameterBuffer>,
    /// Kernel fusion configuration
    config: KernelFusionConfig,
    /// Current optimization step
    step: usize,
    /// GPU memory statistics
    gpu_memory_used: usize,
}

/// Fused parameter buffer with optimized memory layout.
#[derive(Debug)]
struct FusedParameterBuffer {
    /// Parameter ID
    #[allow(dead_code)]
    id: String,
    /// Number of parameter elements
    size: usize,
    /// GPU memory pointer (simplified representation)
    #[allow(dead_code)]
    gpu_ptr: usize, // In real implementation, this would be a CUDA device pointer
    /// Memory layout stride for coalescing
    stride: usize,
    /// Whether buffer uses mixed precision
    #[allow(dead_code)]
    mixed_precision: bool,
}

impl FusedParameterBuffer {
    /// Creates a new fused parameter buffer.
    fn new(id: String, size: usize, config: &KernelFusionConfig) -> Self {
        let alignment = config.memory_alignment();
        let stride = (size * std::mem::size_of::<f32>()).div_ceil(alignment) * alignment;

        Self {
            id,
            size,
            gpu_ptr: 0, // Would be allocated via CUDA malloc
            stride,
            mixed_precision: config.mixed_precision,
        }
    }

    /// Gets the total memory required for this buffer.
    fn memory_requirement(&self) -> usize {
        // 3 arrays: parameters, momentum, variance
        self.stride * 3
    }
}

impl FusedGPUState {
    /// Creates a new fused GPU state.
    pub fn new(config: KernelFusionConfig) -> Self {
        Self {
            fused_buffers: HashMap::new(),
            config,
            step: 0,
            gpu_memory_used: 0,
        }
    }

    /// Allocates a fused parameter buffer on GPU.
    pub fn allocate_parameter(&mut self, id: String, size: usize) -> Result<()> {
        let buffer = FusedParameterBuffer::new(id.clone(), size, &self.config);
        let memory_required = buffer.memory_requirement();

        // In real implementation, this would call cudaMalloc
        self.simulate_gpu_allocation(memory_required)?;

        self.gpu_memory_used += memory_required;
        self.fused_buffers.insert(id, buffer);

        Ok(())
    }

    /// Simulates GPU memory allocation.
    fn simulate_gpu_allocation(&self, size: usize) -> Result<()> {
        // In real implementation, this would be:
        // cudaError_t err = cudaMalloc(&ptr, size);
        // if (err != cudaSuccess) return Err(...);

        if size > 16 * 1024 * 1024 * 1024 {
            // 16GB limit simulation
            return Err(TrustformersError::tensor_op_error(
                "GPU memory allocation failed",
                "simulate_gpu_allocation",
            ));
        }

        Ok(())
    }

    /// Launches fused Adam kernel for a parameter.
    pub fn launch_fused_adam_kernel(
        &mut self,
        param_id: &str,
        param: &mut [f32],
        grad: &[f32],
        lr: f32,
        betas: (f32, f32),
        eps: f32,
        weight_decay: f32,
    ) -> Result<()> {
        let buffer = self.fused_buffers.get(param_id).ok_or_else(|| {
            TrustformersError::tensor_op_error(
                "Parameter buffer not found",
                "launch_fused_adam_kernel",
            )
        })?;

        if param.len() != buffer.size || grad.len() != buffer.size {
            return Err(TrustformersError::tensor_op_error(
                "Size mismatch",
                "launch_fused_adam_kernel",
            ));
        }

        self.step += 1;

        // Calculate kernel launch parameters
        let block_size = self.config.optimal_block_size(buffer.size);
        let grid_size = buffer.size.div_ceil(block_size);

        // In real implementation, this would launch a CUDA kernel:
        // fused_adam_kernel<<<grid_size, block_size>>>(...)
        self.simulate_fused_adam_kernel(
            param,
            grad,
            buffer,
            lr,
            betas,
            eps,
            weight_decay,
            block_size,
            grid_size,
        )?;

        Ok(())
    }

    /// Simulates the fused Adam kernel execution.
    fn simulate_fused_adam_kernel(
        &self,
        param: &mut [f32],
        grad: &[f32],
        buffer: &FusedParameterBuffer,
        lr: f32,
        betas: (f32, f32),
        eps: f32,
        weight_decay: f32,
        block_size: usize,
        grid_size: usize,
    ) -> Result<()> {
        // This simulates what would happen in the GPU kernel

        let (bias_correction1, bias_correction2) =
            BiasCorrection::compute_adam_corrections(betas.0, betas.1, self.step);

        // Process in blocks to simulate GPU execution
        for block_idx in 0..grid_size {
            let start = block_idx * block_size;
            let end = (start + block_size).min(buffer.size);

            self.process_fused_block(
                &mut param[start..end],
                &grad[start..end],
                lr,
                betas,
                bias_correction1,
                bias_correction2,
                eps,
                weight_decay,
            );
        }

        Ok(())
    }

    /// Processes a block in the fused kernel.
    #[inline]
    fn process_fused_block(
        &self,
        param_block: &mut [f32],
        grad_block: &[f32],
        lr: f32,
        betas: (f32, f32),
        bias_correction1: f32,
        bias_correction2: f32,
        eps: f32,
        weight_decay: f32,
    ) {
        // Simulate warp-level operations
        let warp_size = self.config.warp_size;
        let num_warps = param_block.len().div_ceil(warp_size);

        for warp_idx in 0..num_warps {
            let warp_start = warp_idx * warp_size;
            let warp_end = (warp_start + warp_size).min(param_block.len());

            self.process_warp(
                &mut param_block[warp_start..warp_end],
                &grad_block[warp_start..warp_end],
                lr,
                betas,
                bias_correction1,
                bias_correction2,
                eps,
                weight_decay,
            );
        }
    }

    /// Processes a warp's worth of elements.
    #[inline]
    fn process_warp(
        &self,
        param_warp: &mut [f32],
        grad_warp: &[f32],
        lr: f32,
        betas: (f32, f32),
        bias_correction1: f32,
        bias_correction2: f32,
        eps: f32,
        weight_decay: f32,
    ) {
        // In a real GPU kernel, this would use warp-level primitives
        // and shared memory for optimization

        for i in 0..param_warp.len() {
            let grad_val = grad_warp[i] + weight_decay * param_warp[i];

            // Simulate loading momentum and variance from global memory
            let mut momentum = 0.0f32; // Would load from GPU memory
            let mut variance = 0.0f32; // Would load from GPU memory

            // Fused momentum and variance update
            ParameterUpdate::update_ema(&mut momentum, grad_val, betas.0);
            ParameterUpdate::update_ema(&mut variance, grad_val * grad_val, betas.1);

            // Fused bias correction and parameter update
            let m_hat = momentum / bias_correction1;
            let v_hat = variance / bias_correction2;

            ParameterUpdate::adam_update(&mut param_warp[i], lr, m_hat, v_hat, eps);

            // Store momentum and variance back to GPU memory
        }
    }

    /// Launches multi-parameter fused kernel.
    pub fn launch_multi_param_kernel(
        &mut self,
        params: Vec<(&str, &mut [f32], &[f32])>,
        lr: f32,
        betas: (f32, f32),
        eps: f32,
        weight_decay: f32,
    ) -> Result<()> {
        if params.is_empty() {
            return Ok(());
        }

        // Calculate total workload
        let total_elements: usize = params.iter().map(|(_, p, _)| p.len()).sum();
        let block_size = self.config.optimal_block_size(total_elements);
        let _grid_size = total_elements.div_ceil(block_size);

        // In real implementation, this would launch a multi-parameter kernel
        for (param_id, param, grad) in params {
            self.launch_fused_adam_kernel(param_id, param, grad, lr, betas, eps, weight_decay)?;
        }

        Ok(())
    }

    /// Gets GPU memory usage statistics.
    pub fn gpu_memory_stats(&self) -> GPUMemoryStats {
        let total_buffers = self.fused_buffers.len();
        let total_elements: usize = self.fused_buffers.values().map(|b| b.size).sum();

        GPUMemoryStats {
            total_gpu_memory: self.gpu_memory_used,
            num_parameter_buffers: total_buffers,
            total_parameter_elements: total_elements,
            memory_efficiency: self.calculate_memory_efficiency(),
            kernel_fusion_config: self.config.clone(),
        }
    }

    /// Calculates memory efficiency (utilization vs allocation).
    fn calculate_memory_efficiency(&self) -> f32 {
        if self.gpu_memory_used == 0 {
            return 1.0;
        }

        let actual_data_size: usize = self.fused_buffers.values()
            .map(|b| b.size * std::mem::size_of::<f32>() * 3) // param + momentum + variance
            .sum();

        actual_data_size as f32 / self.gpu_memory_used as f32
    }
}

/// GPU memory usage statistics for kernel fusion.
#[derive(Debug, Clone)]
pub struct GPUMemoryStats {
    /// Total GPU memory used in bytes
    pub total_gpu_memory: usize,
    /// Number of parameter buffers
    pub num_parameter_buffers: usize,
    /// Total parameter elements across all buffers
    pub total_parameter_elements: usize,
    /// Memory efficiency (0.0 to 1.0)
    pub memory_efficiency: f32,
    /// Kernel fusion configuration
    pub kernel_fusion_config: KernelFusionConfig,
}

impl GPUMemoryStats {
    /// Calculates theoretical memory bandwidth utilization.
    pub fn memory_bandwidth_utilization(&self, peak_bandwidth_gb_s: f32) -> f32 {
        // Simplified calculation based on parameter count and update frequency
        let bytes_per_update = self.total_parameter_elements * std::mem::size_of::<f32>() * 6; // Read: param, momentum, variance; Write: param, momentum, variance
        let theoretical_bandwidth = bytes_per_update as f32 / 1e9; // Convert to GB

        (theoretical_bandwidth / peak_bandwidth_gb_s).min(1.0)
    }

    /// Suggests optimization strategies.
    pub fn optimization_suggestions(&self) -> Vec<String> {
        let mut suggestions = Vec::new();

        if self.memory_efficiency < 0.8 {
            suggestions.push("Poor memory efficiency; review alignment and coalescing".to_string());
        }

        if self.num_parameter_buffers > 1000 {
            suggestions.push("Many small buffers; consider parameter grouping".to_string());
        }

        let compute_capability = self.kernel_fusion_config.compute_capability;
        if compute_capability.0 < 8 && self.kernel_fusion_config.use_tensor_cores {
            suggestions.push("Tensor cores require compute capability 7.0+".to_string());
        }

        if !self.kernel_fusion_config.mixed_precision && compute_capability.0 >= 7 {
            suggestions.push("Consider enabling mixed precision for newer GPUs".to_string());
        }

        if suggestions.is_empty() {
            suggestions.push("GPU kernel fusion appears well optimized".to_string());
        }

        suggestions
    }
}

/// Kernel fusion optimized Adam optimizer.
#[derive(Debug)]
pub struct KernelFusedAdam {
    /// Learning rate
    lr: f32,
    /// Beta coefficients
    betas: (f32, f32),
    /// Epsilon for numerical stability
    eps: f32,
    /// Weight decay coefficient
    weight_decay: f32,
    /// Fused GPU state
    gpu_state: FusedGPUState,
}

impl KernelFusedAdam {
    /// Creates a new kernel fused Adam optimizer.
    pub fn new(lr: f32, betas: (f32, f32), eps: f32, weight_decay: f32) -> Self {
        Self::with_config(lr, betas, eps, weight_decay, KernelFusionConfig::default())
    }

    /// Creates optimizer with specific GPU configuration.
    pub fn with_config(
        lr: f32,
        betas: (f32, f32),
        eps: f32,
        weight_decay: f32,
        config: KernelFusionConfig,
    ) -> Self {
        Self {
            lr,
            betas,
            eps,
            weight_decay,
            gpu_state: FusedGPUState::new(config),
        }
    }

    /// Creates A100-optimized variant.
    pub fn for_a100(lr: f32, betas: (f32, f32), eps: f32, weight_decay: f32) -> Self {
        Self::with_config(lr, betas, eps, weight_decay, KernelFusionConfig::a100())
    }

    /// Creates H100-optimized variant.
    pub fn for_h100(lr: f32, betas: (f32, f32), eps: f32, weight_decay: f32) -> Self {
        Self::with_config(lr, betas, eps, weight_decay, KernelFusionConfig::h100())
    }

    /// Updates multiple parameters using fused kernels.
    pub fn update_fused(&mut self, params: Vec<(&str, &mut [f32], &[f32])>) -> Result<()> {
        self.gpu_state.launch_multi_param_kernel(
            params,
            self.lr,
            self.betas,
            self.eps,
            self.weight_decay,
        )
    }

    /// Gets GPU performance statistics.
    pub fn gpu_stats(&self) -> GPUMemoryStats {
        self.gpu_state.gpu_memory_stats()
    }
}

impl Optimizer for KernelFusedAdam {
    fn update(&mut self, parameter: &mut Tensor, grad: &Tensor) -> Result<()> {
        match (parameter, grad) {
            (Tensor::F32(param), Tensor::F32(grad_arr)) => {
                let param_id = format!("{:p}", param.as_ptr());

                // Ensure parameter buffer is allocated
                if !self.gpu_state.fused_buffers.contains_key(&param_id) {
                    self.gpu_state.allocate_parameter(param_id.clone(), param.len())?;
                }

                self.gpu_state.launch_fused_adam_kernel(
                    &param_id,
                    param.as_slice_mut().expect("param tensor should have contiguous layout"),
                    grad_arr.as_slice().expect("gradient tensor should have contiguous layout"),
                    self.lr,
                    self.betas,
                    self.eps,
                    self.weight_decay,
                )
            },
            _ => Err(TrustformersError::tensor_op_error(
                "Unsupported tensor types for KernelFusedAdam",
                "update",
            )),
        }
    }

    fn zero_grad(&mut self) {
        // No explicit gradient storage
    }

    fn step(&mut self) {
        // Step counter is handled in kernel launches
    }

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

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

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

    #[test]
    fn test_kernel_fusion_config() {
        let config = KernelFusionConfig::default();
        assert_eq!(config.warp_size, 32);
        assert_eq!(config.compute_capability, (7, 5));

        let a100_config = KernelFusionConfig::a100();
        assert_eq!(a100_config.compute_capability, (8, 0));
        assert!(a100_config.use_tensor_cores);

        let block_size = config.optimal_block_size(1000);
        assert!(block_size > 0);
        assert!(block_size % config.warp_size == 0);
    }

    #[test]
    fn test_fused_gpu_state() {
        let config = KernelFusionConfig::default();
        let mut state = FusedGPUState::new(config);

        assert_eq!(state.gpu_memory_used, 0);

        state
            .allocate_parameter("param1".to_string(), 1000)
            .expect("Operation failed in test");
        assert!(state.gpu_memory_used > 0);
        assert!(state.fused_buffers.contains_key("param1"));
    }

    #[test]
    fn test_kernel_fused_adam() {
        let optimizer = KernelFusedAdam::new(1e-3, (0.9, 0.999), 1e-8, 0.01);
        assert_eq!(optimizer.get_lr(), 1e-3);
        assert_eq!(optimizer.betas, (0.9, 0.999));

        let stats = optimizer.gpu_stats();
        assert_eq!(stats.num_parameter_buffers, 0);
        assert_eq!(stats.total_parameter_elements, 0);
    }

    #[test]
    fn test_gpu_memory_stats() {
        let config = KernelFusionConfig::a100();
        let mut state = FusedGPUState::new(config);

        state
            .allocate_parameter("param1".to_string(), 1000)
            .expect("Operation failed in test");
        state
            .allocate_parameter("param2".to_string(), 2000)
            .expect("Operation failed in test");

        let stats = state.gpu_memory_stats();
        assert_eq!(stats.num_parameter_buffers, 2);
        assert_eq!(stats.total_parameter_elements, 3000);
        assert!(stats.memory_efficiency > 0.0);
        assert!(stats.memory_efficiency <= 1.0);

        let suggestions = stats.optimization_suggestions();
        assert!(!suggestions.is_empty());
    }

    #[test]
    fn test_memory_alignment() {
        let config = KernelFusionConfig::default();
        let alignment = config.memory_alignment();
        assert!(alignment > 0);
        assert!(alignment.is_power_of_two());

        let optimal_config = KernelFusionConfig {
            coalescing_level: CoalescingLevel::Optimal,
            ..Default::default()
        };
        assert!(optimal_config.memory_alignment() >= config.memory_alignment());
    }

    #[test]
    fn test_bandwidth_utilization() {
        let stats = GPUMemoryStats {
            total_gpu_memory: 1024 * 1024,
            num_parameter_buffers: 10,
            total_parameter_elements: 10000,
            memory_efficiency: 0.9,
            kernel_fusion_config: KernelFusionConfig::a100(),
        };

        let utilization = stats.memory_bandwidth_utilization(1555.0); // A100 peak bandwidth
        assert!(utilization >= 0.0);
        assert!(utilization <= 1.0);
    }

    #[test]
    fn test_specialized_configs() {
        let a100_opt = KernelFusedAdam::for_a100(1e-3, (0.9, 0.999), 1e-8, 0.01);
        let h100_opt = KernelFusedAdam::for_h100(1e-3, (0.9, 0.999), 1e-8, 0.01);

        let a100_stats = a100_opt.gpu_stats();
        let h100_stats = h100_opt.gpu_stats();

        assert_eq!(a100_stats.kernel_fusion_config.compute_capability, (8, 0));
        assert_eq!(h100_stats.kernel_fusion_config.compute_capability, (9, 0));
        assert!(
            h100_stats.kernel_fusion_config.shared_memory_size
                > a100_stats.kernel_fusion_config.shared_memory_size
        );
    }
}