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
# Training API Reference

## Module: `ruvector_tiny_dancer_core::training`

Complete API reference for the FastGRNN training pipeline.

## Core Types

### TrainingConfig

Configuration for training hyperparameters.

```rust
pub struct TrainingConfig {
    pub learning_rate: f32,
    pub batch_size: usize,
    pub epochs: usize,
    pub validation_split: f32,
    pub early_stopping_patience: Option<usize>,
    pub lr_decay: f32,
    pub lr_decay_step: usize,
    pub grad_clip: f32,
    pub adam_beta1: f32,
    pub adam_beta2: f32,
    pub adam_epsilon: f32,
    pub l2_reg: f32,
    pub enable_distillation: bool,
    pub distillation_temperature: f32,
    pub distillation_alpha: f32,
}
```

**Default values:**
- `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

### TrainingDataset

Training dataset with features and labels.

```rust
pub struct TrainingDataset {
    pub features: Vec<Vec<f32>>,
    pub labels: Vec<f32>,
    pub soft_targets: Option<Vec<f32>>,
}
```

**Methods:**

#### `new`
```rust
pub fn new(features: Vec<Vec<f32>>, labels: Vec<f32>) -> Result<Self>
```
Create a new training dataset.

**Parameters:**
- `features`: Input features (N × input_dim)
- `labels`: Target labels (N)

**Returns:** Result<TrainingDataset>

**Errors:**
- Returns error if features and labels have different lengths
- Returns error if dataset is empty

**Example:**
```rust
let features = vec![
    vec![0.8, 0.9, 0.7, 0.85, 0.2],
    vec![0.3, 0.2, 0.4, 0.35, 0.9],
];
let labels = vec![1.0, 0.0];
let dataset = TrainingDataset::new(features, labels)?;
```

#### `with_soft_targets`
```rust
pub fn with_soft_targets(self, soft_targets: Vec<f32>) -> Result<Self>
```
Add soft targets from teacher model for knowledge distillation.

**Parameters:**
- `soft_targets`: Soft predictions from teacher model (N)

**Returns:** Result<TrainingDataset>

**Example:**
```rust
let soft_targets = generate_teacher_predictions(&teacher, &features, 3.0)?;
let dataset = dataset.with_soft_targets(soft_targets)?;
```

#### `split`
```rust
pub fn split(&self, val_ratio: f32) -> Result<(Self, Self)>
```
Split dataset into train and validation sets.

**Parameters:**
- `val_ratio`: Validation set ratio (0.0 to 1.0)

**Returns:** Result<(train_dataset, val_dataset)>

**Example:**
```rust
let (train, val) = dataset.split(0.2)?; // 80% train, 20% val
```

#### `normalize`
```rust
pub fn normalize(&mut self) -> Result<(Vec<f32>, Vec<f32>)>
```
Normalize features using z-score normalization.

**Returns:** Result<(means, stds)>

**Example:**
```rust
let (means, stds) = dataset.normalize()?;
// Save for inference
save_normalization_params("norm.json", &means, &stds)?;
```

#### `len`
```rust
pub fn len(&self) -> usize
```
Get number of samples in dataset.

#### `is_empty`
```rust
pub fn is_empty(&self) -> bool
```
Check if dataset is empty.

### BatchIterator

Iterator for mini-batch training.

```rust
pub struct BatchIterator<'a> {
    // Private fields
}
```

**Methods:**

#### `new`
```rust
pub fn new(dataset: &'a TrainingDataset, batch_size: usize, shuffle: bool) -> Self
```
Create a new batch iterator.

**Parameters:**
- `dataset`: Reference to training dataset
- `batch_size`: Size of each batch
- `shuffle`: Whether to shuffle data

**Example:**
```rust
let batch_iter = BatchIterator::new(&dataset, 32, true);
for (features, labels, soft_targets) in batch_iter {
    // Train on batch
}
```

### TrainingMetrics

Metrics recorded during training.

```rust
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TrainingMetrics {
    pub epoch: usize,
    pub train_loss: f32,
    pub val_loss: f32,
    pub train_accuracy: f32,
    pub val_accuracy: f32,
    pub learning_rate: f32,
}
```

### Trainer

Main trainer for FastGRNN models.

```rust
pub struct Trainer {
    // Private fields
}
```

**Methods:**

#### `new`
```rust
pub fn new(model_config: &FastGRNNConfig, config: TrainingConfig) -> Self
```
Create a new trainer.

**Parameters:**
- `model_config`: Model configuration
- `config`: Training configuration

**Example:**
```rust
let trainer = Trainer::new(&model_config, training_config);
```

#### `train`
```rust
pub fn train(
    &mut self,
    model: &mut FastGRNN,
    dataset: &TrainingDataset,
) -> Result<Vec<TrainingMetrics>>
```
Train the model on the dataset.

**Parameters:**
- `model`: Mutable reference to the model
- `dataset`: Training dataset

**Returns:** Result<Vec<TrainingMetrics>> - Metrics for each epoch

**Example:**
```rust
let metrics = trainer.train(&mut model, &dataset)?;

// Print results
for m in &metrics {
    println!("Epoch {}: val_loss={:.4}, val_acc={:.2}%",
             m.epoch, m.val_loss, m.val_accuracy * 100.0);
}
```

#### `metrics_history`
```rust
pub fn metrics_history(&self) -> &[TrainingMetrics]
```
Get training metrics history.

**Returns:** Slice of training metrics

#### `save_metrics`
```rust
pub fn save_metrics<P: AsRef<Path>>(&self, path: P) -> Result<()>
```
Save training metrics to JSON file.

**Parameters:**
- `path`: Output file path

**Example:**
```rust
trainer.save_metrics("models/metrics.json")?;
```

## Functions

### binary_cross_entropy
```rust
fn binary_cross_entropy(prediction: f32, target: f32) -> f32
```
Compute binary cross-entropy loss.

**Formula:**
```
BCE = -target * log(pred) - (1 - target) * log(1 - pred)
```

**Parameters:**
- `prediction`: Model prediction (0.0 to 1.0)
- `target`: True label (0.0 or 1.0)

**Returns:** Loss value

### temperature_softmax
```rust
pub fn temperature_softmax(logit: f32, temperature: f32) -> f32
```
Temperature-scaled sigmoid for knowledge distillation.

**Parameters:**
- `logit`: Model output logit
- `temperature`: Temperature scaling factor (> 1.0 = softer)

**Returns:** Temperature-scaled probability

**Example:**
```rust
let soft_pred = temperature_softmax(logit, 3.0);
```

### generate_teacher_predictions
```rust
pub fn generate_teacher_predictions(
    teacher: &FastGRNN,
    features: &[Vec<f32>],
    temperature: f32,
) -> Result<Vec<f32>>
```
Generate soft predictions from teacher model.

**Parameters:**
- `teacher`: Teacher model
- `features`: Input features
- `temperature`: Temperature for softening

**Returns:** Result<Vec<f32>> - Soft predictions

**Example:**
```rust
let teacher = FastGRNN::load("teacher.safetensors")?;
let soft_targets = generate_teacher_predictions(&teacher, &features, 3.0)?;
```

## Usage Examples

### Basic Training

```rust
use ruvector_tiny_dancer_core::{
    model::{FastGRNN, FastGRNNConfig},
    training::{TrainingConfig, TrainingDataset, Trainer},
};

// Prepare data
let features = vec![/* ... */];
let labels = vec![/* ... */];
let mut dataset = TrainingDataset::new(features, labels)?;
dataset.normalize()?;

// Configure
let model_config = FastGRNNConfig::default();
let training_config = TrainingConfig::default();

// Train
let mut model = FastGRNN::new(model_config.clone())?;
let mut trainer = Trainer::new(&model_config, training_config);
let metrics = trainer.train(&mut model, &dataset)?;

// Save
model.save("model.safetensors")?;
```

### Knowledge Distillation

```rust
use ruvector_tiny_dancer_core::training::generate_teacher_predictions;

// Load teacher
let teacher = FastGRNN::load("teacher.safetensors")?;

// Generate soft targets
let temperature = 3.0;
let soft_targets = generate_teacher_predictions(&teacher, &features, temperature)?;

// Add to dataset
let dataset = dataset.with_soft_targets(soft_targets)?;

// Configure distillation
let training_config = TrainingConfig {
    enable_distillation: true,
    distillation_temperature: temperature,
    distillation_alpha: 0.7,
    ..Default::default()
};

// Train with distillation
let mut trainer = Trainer::new(&model_config, training_config);
trainer.train(&mut model, &dataset)?;
```

### Custom Training Loop

```rust
use ruvector_tiny_dancer_core::training::BatchIterator;

for epoch in 0..50 {
    let mut epoch_loss = 0.0;
    let mut n_batches = 0;

    let batch_iter = BatchIterator::new(&train_dataset, 32, true);
    for (features, labels, soft_targets) in batch_iter {
        // Your training logic here
        epoch_loss += train_batch(&mut model, &features, &labels);
        n_batches += 1;
    }

    let avg_loss = epoch_loss / n_batches as f32;
    println!("Epoch {}: loss={:.4}", epoch, avg_loss);
}
```

### Progressive Training

```rust
// Start with high LR
let mut config = TrainingConfig {
    learning_rate: 0.1,
    epochs: 20,
    ..Default::default()
};

let mut trainer = Trainer::new(&model_config, config.clone());
trainer.train(&mut model, &dataset)?;

// Continue with lower LR
config.learning_rate = 0.01;
config.epochs = 30;

let mut trainer2 = Trainer::new(&model_config, config);
trainer2.train(&mut model, &dataset)?;
```

## Error Handling

All training functions return `Result<T>` with `TinyDancerError`:

```rust
match trainer.train(&mut model, &dataset) {
    Ok(metrics) => {
        println!("Training successful!");
        println!("Final accuracy: {:.2}%",
                 metrics.last().unwrap().val_accuracy * 100.0);
    }
    Err(e) => {
        eprintln!("Training failed: {}", e);
        // Handle error appropriately
    }
}
```

Common errors:
- `InvalidInput`: Invalid dataset, configuration, or parameters
- `SerializationError`: Failed to save/load files
- `IoError`: File I/O errors

## Performance Considerations

### Memory Usage

- **Dataset**: O(N × input_dim) floats
- **Model**: ~850 parameters for default config (16 hidden units)
- **Optimizer**: 2× model size (Adam momentum)

For large datasets (>100K samples), consider:
- Batch processing
- Data streaming
- Memory-mapped files

### Training Speed

Typical training times (CPU):
- Small dataset (1K samples): ~10 seconds
- Medium dataset (10K samples): ~1-2 minutes
- Large dataset (100K samples): ~10-20 minutes

Optimization tips:
- Use larger batch sizes (32-128)
- Enable early stopping
- Use knowledge distillation for faster convergence

### Reproducibility

For reproducible results:
1. Set random seed before training
2. Use deterministic operations
3. Save normalization parameters
4. Version control all hyperparameters

```rust
// Set seed (note: full reproducibility requires more work)
use rand::SeedableRng;
let mut rng = rand::rngs::StdRng::seed_from_u64(42);
```

## See Also

- [Training Guide]./training-guide.md - Complete training walkthrough
- [Model API]../src/model.rs - FastGRNN model implementation
- [Examples]../examples/train-model.rs - Working code examples