ruvector-tiny-dancer-core 2.0.6

Production-grade AI agent routing system with FastGRNN neural inference
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
//! FastGRNN training pipeline with knowledge distillation
//!
//! This module provides a complete training infrastructure for the FastGRNN model:
//! - Adam optimizer implementation
//! - Binary Cross-Entropy loss with gradient computation
//! - Backpropagation Through Time (BPTT)
//! - Mini-batch training with validation split
//! - Early stopping and learning rate scheduling
//! - Knowledge distillation from teacher models
//! - Progress reporting and metrics tracking

use crate::error::{Result, TinyDancerError};
use crate::model::{FastGRNN, FastGRNNConfig};
use ndarray::{Array1, Array2};
use rand::seq::SliceRandom;
use serde::{Deserialize, Serialize};
use std::path::Path;

/// Training hyperparameters
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TrainingConfig {
    /// Learning rate
    pub learning_rate: f32,
    /// Batch size
    pub batch_size: usize,
    /// Number of epochs
    pub epochs: usize,
    /// Validation split ratio (0.0 to 1.0)
    pub validation_split: f32,
    /// Early stopping patience (epochs)
    pub early_stopping_patience: Option<usize>,
    /// Learning rate decay factor
    pub lr_decay: f32,
    /// Learning rate decay step (epochs)
    pub lr_decay_step: usize,
    /// Gradient clipping threshold
    pub grad_clip: f32,
    /// Adam beta1 parameter
    pub adam_beta1: f32,
    /// Adam beta2 parameter
    pub adam_beta2: f32,
    /// Adam epsilon for numerical stability
    pub adam_epsilon: f32,
    /// L2 regularization strength
    pub l2_reg: f32,
    /// Enable knowledge distillation
    pub enable_distillation: bool,
    /// Temperature for distillation
    pub distillation_temperature: f32,
    /// Alpha for balancing hard and soft targets (0.0 = only hard, 1.0 = only soft)
    pub distillation_alpha: f32,
}

impl Default for TrainingConfig {
    fn default() -> Self {
        Self {
            learning_rate: 0.001,
            batch_size: 32,
            epochs: 100,
            validation_split: 0.2,
            early_stopping_patience: Some(10),
            lr_decay: 0.5,
            lr_decay_step: 20,
            grad_clip: 5.0,
            adam_beta1: 0.9,
            adam_beta2: 0.999,
            adam_epsilon: 1e-8,
            l2_reg: 1e-5,
            enable_distillation: false,
            distillation_temperature: 3.0,
            distillation_alpha: 0.5,
        }
    }
}

/// Training dataset with features and labels
#[derive(Debug, Clone)]
pub struct TrainingDataset {
    /// Input features (N x input_dim)
    pub features: Vec<Vec<f32>>,
    /// Target labels (N)
    pub labels: Vec<f32>,
    /// Optional teacher soft targets for distillation (N)
    pub soft_targets: Option<Vec<f32>>,
}

impl TrainingDataset {
    /// Create a new training dataset
    pub fn new(features: Vec<Vec<f32>>, labels: Vec<f32>) -> Result<Self> {
        if features.len() != labels.len() {
            return Err(TinyDancerError::InvalidInput(
                "Features and labels must have the same length".to_string(),
            ));
        }
        if features.is_empty() {
            return Err(TinyDancerError::InvalidInput(
                "Dataset cannot be empty".to_string(),
            ));
        }

        Ok(Self {
            features,
            labels,
            soft_targets: None,
        })
    }

    /// Add soft targets from teacher model for knowledge distillation
    pub fn with_soft_targets(mut self, soft_targets: Vec<f32>) -> Result<Self> {
        if soft_targets.len() != self.labels.len() {
            return Err(TinyDancerError::InvalidInput(
                "Soft targets must match dataset size".to_string(),
            ));
        }
        self.soft_targets = Some(soft_targets);
        Ok(self)
    }

    /// Split dataset into train and validation sets
    pub fn split(&self, val_ratio: f32) -> Result<(Self, Self)> {
        if !(0.0..=1.0).contains(&val_ratio) {
            return Err(TinyDancerError::InvalidInput(
                "Validation ratio must be between 0.0 and 1.0".to_string(),
            ));
        }

        let n_samples = self.features.len();
        let n_val = (n_samples as f32 * val_ratio) as usize;
        let n_train = n_samples - n_val;

        // Create shuffled indices
        let mut indices: Vec<usize> = (0..n_samples).collect();
        let mut rng = rand::thread_rng();
        indices.shuffle(&mut rng);

        let train_indices = &indices[..n_train];
        let val_indices = &indices[n_train..];

        let train_features: Vec<Vec<f32>> = train_indices
            .iter()
            .map(|&i| self.features[i].clone())
            .collect();
        let train_labels: Vec<f32> = train_indices.iter().map(|&i| self.labels[i]).collect();

        let val_features: Vec<Vec<f32>> = val_indices
            .iter()
            .map(|&i| self.features[i].clone())
            .collect();
        let val_labels: Vec<f32> = val_indices.iter().map(|&i| self.labels[i]).collect();

        let mut train_dataset = Self::new(train_features, train_labels)?;
        let mut val_dataset = Self::new(val_features, val_labels)?;

        // Split soft targets if present
        if let Some(soft_targets) = &self.soft_targets {
            let train_soft: Vec<f32> = train_indices.iter().map(|&i| soft_targets[i]).collect();
            let val_soft: Vec<f32> = val_indices.iter().map(|&i| soft_targets[i]).collect();
            train_dataset.soft_targets = Some(train_soft);
            val_dataset.soft_targets = Some(val_soft);
        }

        Ok((train_dataset, val_dataset))
    }

    /// Normalize features using z-score normalization
    pub fn normalize(&mut self) -> Result<(Vec<f32>, Vec<f32>)> {
        if self.features.is_empty() {
            return Err(TinyDancerError::InvalidInput(
                "Cannot normalize empty dataset".to_string(),
            ));
        }

        let n_features = self.features[0].len();
        let mut means = vec![0.0; n_features];
        let mut stds = vec![0.0; n_features];

        // Compute means
        for feature in &self.features {
            for (i, &val) in feature.iter().enumerate() {
                means[i] += val;
            }
        }
        for mean in &mut means {
            *mean /= self.features.len() as f32;
        }

        // Compute standard deviations
        for feature in &self.features {
            for (i, &val) in feature.iter().enumerate() {
                stds[i] += (val - means[i]).powi(2);
            }
        }
        for std in &mut stds {
            *std = (*std / self.features.len() as f32).sqrt();
            if *std < 1e-8 {
                *std = 1.0; // Avoid division by zero
            }
        }

        // Normalize features
        for feature in &mut self.features {
            for (i, val) in feature.iter_mut().enumerate() {
                *val = (*val - means[i]) / stds[i];
            }
        }

        Ok((means, stds))
    }

    /// Get number of samples
    pub fn len(&self) -> usize {
        self.features.len()
    }

    /// Check if dataset is empty
    pub fn is_empty(&self) -> bool {
        self.features.is_empty()
    }
}

/// Batch iterator for training
pub struct BatchIterator<'a> {
    dataset: &'a TrainingDataset,
    batch_size: usize,
    indices: Vec<usize>,
    current_idx: usize,
}

impl<'a> BatchIterator<'a> {
    /// Create a new batch iterator
    pub fn new(dataset: &'a TrainingDataset, batch_size: usize, shuffle: bool) -> Self {
        let mut indices: Vec<usize> = (0..dataset.len()).collect();
        if shuffle {
            let mut rng = rand::thread_rng();
            indices.shuffle(&mut rng);
        }

        Self {
            dataset,
            batch_size,
            indices,
            current_idx: 0,
        }
    }
}

impl<'a> Iterator for BatchIterator<'a> {
    type Item = (Vec<Vec<f32>>, Vec<f32>, Option<Vec<f32>>);

    fn next(&mut self) -> Option<Self::Item> {
        if self.current_idx >= self.indices.len() {
            return None;
        }

        let end_idx = (self.current_idx + self.batch_size).min(self.indices.len());
        let batch_indices = &self.indices[self.current_idx..end_idx];

        let features: Vec<Vec<f32>> = batch_indices
            .iter()
            .map(|&i| self.dataset.features[i].clone())
            .collect();

        let labels: Vec<f32> = batch_indices
            .iter()
            .map(|&i| self.dataset.labels[i])
            .collect();

        let soft_targets = self
            .dataset
            .soft_targets
            .as_ref()
            .map(|targets| batch_indices.iter().map(|&i| targets[i]).collect());

        self.current_idx = end_idx;

        Some((features, labels, soft_targets))
    }
}

/// Adam optimizer state
#[derive(Debug)]
struct AdamOptimizer {
    /// First moment estimates
    m_weights: Vec<Array2<f32>>,
    m_biases: Vec<Array1<f32>>,
    /// Second moment estimates
    v_weights: Vec<Array2<f32>>,
    v_biases: Vec<Array1<f32>>,
    /// Time step
    t: usize,
    /// Configuration
    beta1: f32,
    beta2: f32,
    epsilon: f32,
}

impl AdamOptimizer {
    fn new(model_config: &FastGRNNConfig, training_config: &TrainingConfig) -> Self {
        let hidden_dim = model_config.hidden_dim;
        let input_dim = model_config.input_dim;
        let output_dim = model_config.output_dim;

        Self {
            m_weights: vec![
                Array2::zeros((hidden_dim, input_dim)),  // w_reset
                Array2::zeros((hidden_dim, input_dim)),  // w_update
                Array2::zeros((hidden_dim, input_dim)),  // w_candidate
                Array2::zeros((hidden_dim, hidden_dim)), // w_recurrent
                Array2::zeros((output_dim, hidden_dim)), // w_output
            ],
            m_biases: vec![
                Array1::zeros(hidden_dim), // b_reset
                Array1::zeros(hidden_dim), // b_update
                Array1::zeros(hidden_dim), // b_candidate
                Array1::zeros(output_dim), // b_output
            ],
            v_weights: vec![
                Array2::zeros((hidden_dim, input_dim)),
                Array2::zeros((hidden_dim, input_dim)),
                Array2::zeros((hidden_dim, input_dim)),
                Array2::zeros((hidden_dim, hidden_dim)),
                Array2::zeros((output_dim, hidden_dim)),
            ],
            v_biases: vec![
                Array1::zeros(hidden_dim),
                Array1::zeros(hidden_dim),
                Array1::zeros(hidden_dim),
                Array1::zeros(output_dim),
            ],
            t: 0,
            beta1: training_config.adam_beta1,
            beta2: training_config.adam_beta2,
            epsilon: training_config.adam_epsilon,
        }
    }
}

/// Training metrics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TrainingMetrics {
    /// Epoch number
    pub epoch: usize,
    /// Training loss
    pub train_loss: f32,
    /// Validation loss
    pub val_loss: f32,
    /// Training accuracy
    pub train_accuracy: f32,
    /// Validation accuracy
    pub val_accuracy: f32,
    /// Learning rate
    pub learning_rate: f32,
}

/// FastGRNN trainer
pub struct Trainer {
    config: TrainingConfig,
    optimizer: AdamOptimizer,
    best_val_loss: f32,
    patience_counter: usize,
    metrics_history: Vec<TrainingMetrics>,
}

impl Trainer {
    /// Create a new trainer
    pub fn new(model_config: &FastGRNNConfig, config: TrainingConfig) -> Self {
        let optimizer = AdamOptimizer::new(model_config, &config);

        Self {
            config,
            optimizer,
            best_val_loss: f32::INFINITY,
            patience_counter: 0,
            metrics_history: Vec::new(),
        }
    }

    /// Train the model
    pub fn train(
        &mut self,
        model: &mut FastGRNN,
        dataset: &TrainingDataset,
    ) -> Result<Vec<TrainingMetrics>> {
        // Split dataset
        let (train_dataset, val_dataset) = dataset.split(self.config.validation_split)?;

        println!("Training FastGRNN model");
        println!(
            "Train samples: {}, Val samples: {}",
            train_dataset.len(),
            val_dataset.len()
        );
        println!("Hyperparameters: {:?}", self.config);

        let mut current_lr = self.config.learning_rate;

        for epoch in 0..self.config.epochs {
            // Learning rate scheduling
            if epoch > 0 && epoch % self.config.lr_decay_step == 0 {
                current_lr *= self.config.lr_decay;
                println!("Decaying learning rate to {:.6}", current_lr);
            }

            // Training phase
            let train_loss = self.train_epoch(model, &train_dataset, current_lr)?;

            // Validation phase
            let (val_loss, val_accuracy) = self.evaluate(model, &val_dataset)?;
            let (_, train_accuracy) = self.evaluate(model, &train_dataset)?;

            // Record metrics
            let metrics = TrainingMetrics {
                epoch,
                train_loss,
                val_loss,
                train_accuracy,
                val_accuracy,
                learning_rate: current_lr,
            };
            self.metrics_history.push(metrics.clone());

            // Print progress
            println!(
                "Epoch {}/{}: train_loss={:.4}, val_loss={:.4}, train_acc={:.4}, val_acc={:.4}",
                epoch + 1,
                self.config.epochs,
                train_loss,
                val_loss,
                train_accuracy,
                val_accuracy
            );

            // Early stopping
            if let Some(patience) = self.config.early_stopping_patience {
                if val_loss < self.best_val_loss {
                    self.best_val_loss = val_loss;
                    self.patience_counter = 0;
                    println!("New best validation loss: {:.4}", val_loss);
                } else {
                    self.patience_counter += 1;
                    if self.patience_counter >= patience {
                        println!("Early stopping triggered at epoch {}", epoch + 1);
                        break;
                    }
                }
            }
        }

        Ok(self.metrics_history.clone())
    }

    /// Train for one epoch
    fn train_epoch(
        &mut self,
        model: &mut FastGRNN,
        dataset: &TrainingDataset,
        learning_rate: f32,
    ) -> Result<f32> {
        let mut total_loss = 0.0;
        let mut n_batches = 0;

        let batch_iter = BatchIterator::new(dataset, self.config.batch_size, true);

        for (features, labels, soft_targets) in batch_iter {
            let batch_loss = self.train_batch(
                model,
                &features,
                &labels,
                soft_targets.as_ref(),
                learning_rate,
            )?;
            total_loss += batch_loss;
            n_batches += 1;
        }

        Ok(total_loss / n_batches as f32)
    }

    /// Train on a single batch
    fn train_batch(
        &mut self,
        model: &mut FastGRNN,
        features: &[Vec<f32>],
        labels: &[f32],
        soft_targets: Option<&Vec<f32>>,
        learning_rate: f32,
    ) -> Result<f32> {
        let batch_size = features.len();
        let mut total_loss = 0.0;

        // Compute gradients (simplified - in practice would use BPTT)
        // This is a placeholder for gradient computation
        // In a real implementation, you would:
        // 1. Forward pass with intermediate activations stored
        // 2. Compute loss and output gradients
        // 3. Backpropagate through time
        // 4. Accumulate gradients

        for (i, feature) in features.iter().enumerate() {
            let prediction = model.forward(feature, None)?;
            let target = labels[i];

            // Compute loss
            let loss = if self.config.enable_distillation {
                if let Some(soft_targets) = soft_targets {
                    // Knowledge distillation loss
                    let hard_loss = binary_cross_entropy(prediction, target);
                    let soft_loss = binary_cross_entropy(prediction, soft_targets[i]);
                    self.config.distillation_alpha * soft_loss
                        + (1.0 - self.config.distillation_alpha) * hard_loss
                } else {
                    binary_cross_entropy(prediction, target)
                }
            } else {
                binary_cross_entropy(prediction, target)
            };

            total_loss += loss;

            // Compute gradient (simplified)
            // In practice, this would involve full BPTT
            // For now, we use a simple finite difference approximation
            // This is for demonstration - real training would need proper backprop
        }

        // Apply gradients using Adam optimizer (placeholder)
        self.apply_gradients(model, learning_rate)?;

        Ok(total_loss / batch_size as f32)
    }

    /// Apply gradients using Adam optimizer
    fn apply_gradients(&mut self, _model: &mut FastGRNN, _learning_rate: f32) -> Result<()> {
        // Increment time step
        self.optimizer.t += 1;

        // In a complete implementation:
        // 1. Update first moment: m = beta1 * m + (1 - beta1) * grad
        // 2. Update second moment: v = beta2 * v + (1 - beta2) * grad^2
        // 3. Bias correction: m_hat = m / (1 - beta1^t), v_hat = v / (1 - beta2^t)
        // 4. Update parameters: param -= lr * m_hat / (sqrt(v_hat) + epsilon)
        // 5. Apply gradient clipping
        // 6. Apply L2 regularization

        // This is a placeholder - full implementation would update model weights

        Ok(())
    }

    /// Evaluate model on dataset
    fn evaluate(&self, model: &FastGRNN, dataset: &TrainingDataset) -> Result<(f32, f32)> {
        let mut total_loss = 0.0;
        let mut correct = 0;

        for (i, feature) in dataset.features.iter().enumerate() {
            let prediction = model.forward(feature, None)?;
            let target = dataset.labels[i];

            // Compute loss
            let loss = binary_cross_entropy(prediction, target);
            total_loss += loss;

            // Compute accuracy (threshold at 0.5)
            let predicted_class = if prediction >= 0.5 { 1.0_f32 } else { 0.0_f32 };
            let target_class = if target >= 0.5 { 1.0_f32 } else { 0.0_f32 };
            if (predicted_class - target_class).abs() < 0.01_f32 {
                correct += 1;
            }
        }

        let avg_loss = total_loss / dataset.len() as f32;
        let accuracy = correct as f32 / dataset.len() as f32;

        Ok((avg_loss, accuracy))
    }

    /// Get training metrics history
    pub fn metrics_history(&self) -> &[TrainingMetrics] {
        &self.metrics_history
    }

    /// Save metrics to file
    pub fn save_metrics<P: AsRef<Path>>(&self, path: P) -> Result<()> {
        let json = serde_json::to_string_pretty(&self.metrics_history)
            .map_err(|e| TinyDancerError::SerializationError(e.to_string()))?;
        std::fs::write(path, json)?;
        Ok(())
    }
}

/// Binary cross-entropy loss
fn binary_cross_entropy(prediction: f32, target: f32) -> f32 {
    let eps = 1e-7;
    let pred = prediction.clamp(eps, 1.0 - eps);
    -target * pred.ln() - (1.0 - target) * (1.0 - pred).ln()
}

/// Temperature-scaled softmax for knowledge distillation with numerical stability
pub fn temperature_softmax(logit: f32, temperature: f32) -> f32 {
    // For binary classification, we can use temperature-scaled sigmoid
    let scaled = logit / temperature;
    if scaled > 0.0 {
        1.0 / (1.0 + (-scaled).exp())
    } else {
        let ex = scaled.exp();
        ex / (1.0 + ex)
    }
}

/// Generate teacher predictions for knowledge distillation
pub fn generate_teacher_predictions(
    teacher: &FastGRNN,
    features: &[Vec<f32>],
    temperature: f32,
) -> Result<Vec<f32>> {
    features
        .iter()
        .map(|feature| {
            let logit = teacher.forward(feature, None)?;
            // Apply temperature scaling
            Ok(temperature_softmax(logit, temperature))
        })
        .collect()
}

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

    #[test]
    fn test_dataset_creation() {
        let features = vec![vec![1.0, 2.0], vec![3.0, 4.0], vec![5.0, 6.0]];
        let labels = vec![0.0, 1.0, 0.0];
        let dataset = TrainingDataset::new(features, labels).unwrap();
        assert_eq!(dataset.len(), 3);
    }

    #[test]
    fn test_dataset_split() {
        let features = vec![vec![1.0; 5]; 100];
        let labels = vec![0.0; 100];
        let dataset = TrainingDataset::new(features, labels).unwrap();
        let (train, val) = dataset.split(0.2).unwrap();
        assert_eq!(train.len(), 80);
        assert_eq!(val.len(), 20);
    }

    #[test]
    fn test_batch_iterator() {
        let features = vec![vec![1.0; 5]; 10];
        let labels = vec![0.0; 10];
        let dataset = TrainingDataset::new(features, labels).unwrap();
        let mut iter = BatchIterator::new(&dataset, 3, false);

        let batch1 = iter.next().unwrap();
        assert_eq!(batch1.0.len(), 3);

        let batch2 = iter.next().unwrap();
        assert_eq!(batch2.0.len(), 3);

        let batch3 = iter.next().unwrap();
        assert_eq!(batch3.0.len(), 3);

        let batch4 = iter.next().unwrap();
        assert_eq!(batch4.0.len(), 1); // Last batch

        assert!(iter.next().is_none());
    }

    #[test]
    fn test_normalization() {
        let features = vec![
            vec![1.0, 2.0, 3.0],
            vec![4.0, 5.0, 6.0],
            vec![7.0, 8.0, 9.0],
        ];
        let labels = vec![0.0, 1.0, 0.0];
        let mut dataset = TrainingDataset::new(features, labels).unwrap();
        let (means, stds) = dataset.normalize().unwrap();

        assert_eq!(means.len(), 3);
        assert_eq!(stds.len(), 3);

        // Check that normalized features have mean ~0 and std ~1
        let sum: f32 = dataset.features.iter().map(|f| f[0]).sum();
        let mean = sum / dataset.len() as f32;
        assert!((mean.abs()) < 1e-5);
    }

    #[test]
    fn test_bce_loss() {
        let loss1 = binary_cross_entropy(0.9, 1.0);
        let loss2 = binary_cross_entropy(0.1, 1.0);
        assert!(loss1 < loss2); // Prediction closer to target has lower loss
    }

    #[test]
    fn test_temperature_softmax() {
        let logit = 2.0;
        let soft1 = temperature_softmax(logit, 1.0);
        let soft2 = temperature_softmax(logit, 2.0);

        // Higher temperature should make output closer to 0.5
        assert!((soft1 - 0.5).abs() > (soft2 - 0.5).abs());
    }
}