entrenar 0.7.8

Training & Optimization library with autograd, LoRA, quantization, and model merging
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
//! Weighted loss wrappers for sample reweighting

use crate::Tensor;
use ndarray::Array1;

use super::LossFn;

/// Weighted loss wrapper for sample reweighting
///
/// Applies a scalar weight to any loss function, useful for:
/// - Upweighting compiler-verified labels (e.g., --reweight 1.5)
/// - Class balancing in imbalanced datasets
/// - Curriculum learning with sample importance
///
/// # Example
///
/// ```
/// use entrenar::train::{WeightedLoss, MSELoss, LossFn};
/// use entrenar::Tensor;
///
/// // Upweight compiler-verified samples by 1.5x
/// let loss_fn = WeightedLoss::new(Box::new(MSELoss), 1.5);
///
/// let pred = Tensor::from_vec(vec![1.0, 2.0], true);
/// let target = Tensor::from_vec(vec![1.5, 2.5], false);
///
/// let loss = loss_fn.forward(&pred, &target);
/// // Loss is 1.5x the unweighted loss
/// ```
pub struct WeightedLoss {
    inner: Box<dyn LossFn>,
    weight: f32,
}

impl WeightedLoss {
    /// Create a weighted loss wrapper
    ///
    /// # Arguments
    ///
    /// * `inner` - The underlying loss function
    /// * `weight` - Scalar multiplier for the loss (1.0 = no change)
    pub fn new(inner: Box<dyn LossFn>, weight: f32) -> Self {
        Self { inner, weight }
    }

    /// Create with weight 1.0 (no change)
    pub fn unweighted(inner: Box<dyn LossFn>) -> Self {
        Self::new(inner, 1.0)
    }

    /// Get current weight
    pub fn weight(&self) -> f32 {
        self.weight
    }

    /// Set new weight
    pub fn set_weight(&mut self, weight: f32) {
        self.weight = weight;
    }
}

impl LossFn for WeightedLoss {
    fn forward(&self, predictions: &Tensor, targets: &Tensor) -> Tensor {
        let inner_loss = self.inner.forward(predictions, targets);

        if (self.weight - 1.0).abs() < 1e-7 {
            // No weighting needed
            return inner_loss;
        }

        // Apply weight to loss value
        let weighted_val = inner_loss.data()[0] * self.weight;
        let mut weighted_loss = Tensor::from_vec(vec![weighted_val], true);

        // Scale gradient by weight
        use crate::autograd::BackwardOp;
        use std::rc::Rc;

        struct WeightedBackward {
            inner_backward: Option<Rc<dyn BackwardOp>>,
            #[allow(dead_code)]
            weight: f32, // Stored for future gradient scaling
        }

        impl BackwardOp for WeightedBackward {
            fn backward(&self) {
                // The inner backward already computed gradient
                // We just need to ensure it's called (weight is applied in forward)
                if let Some(ref inner) = self.inner_backward {
                    inner.backward();
                }
            }
        }

        if predictions.requires_grad() {
            weighted_loss.set_backward_op(Rc::new(WeightedBackward {
                inner_backward: inner_loss.backward_op(),
                weight: self.weight,
            }));
        }

        weighted_loss
    }

    fn name(&self) -> &'static str {
        "Weighted"
    }
}

/// Per-sample weighted loss for fine-grained control
///
/// Applies different weights to each sample in a batch.
/// Useful for curriculum learning where each sample has
/// a difficulty-based weight.
///
/// # Example
///
/// ```
/// use entrenar::train::{SampleWeightedLoss, MSELoss, LossFn};
/// use entrenar::Tensor;
///
/// let loss_fn = SampleWeightedLoss::new(Box::new(MSELoss));
///
/// let pred = Tensor::from_vec(vec![1.0, 2.0, 3.0], true);
/// let target = Tensor::from_vec(vec![1.5, 2.5, 3.5], false);
/// let weights = vec![1.0, 2.0, 0.5];  // Per-sample weights
///
/// let loss = loss_fn.forward_weighted(&pred, &target, &weights);
/// ```
pub struct SampleWeightedLoss {
    #[allow(dead_code)]
    inner: Box<dyn LossFn>, // Stored for type checking; forward_weighted uses MSE directly
}

impl SampleWeightedLoss {
    /// Create a sample-weighted loss wrapper
    pub fn new(inner: Box<dyn LossFn>) -> Self {
        Self { inner }
    }

    /// Compute loss with per-sample weights
    ///
    /// # Arguments
    ///
    /// * `predictions` - Model predictions
    /// * `targets` - Ground truth targets
    /// * `weights` - Per-sample weights (same length as predictions)
    pub fn forward_weighted(
        &self,
        predictions: &Tensor,
        targets: &Tensor,
        weights: &[f32],
    ) -> Tensor {
        assert_eq!(predictions.len(), weights.len(), "Weights must match predictions length");

        // Compute weighted loss manually for MSE-like losses
        let diff = predictions.data() - targets.data();
        let n = predictions.len() as f32;

        // Weighted squared error
        let weighted_loss: f32 =
            diff.iter().zip(weights.iter()).map(|(&d, &w)| w * d * d).sum::<f32>() / n;

        let mut loss = Tensor::from_vec(vec![weighted_loss], true);

        // Weighted gradient: 2 * w * (pred - target) / n
        let grad: Array1<f32> =
            diff.iter().zip(weights.iter()).map(|(&d, &w)| 2.0 * w * d / n).collect();

        use crate::autograd::BackwardOp;
        use std::rc::Rc;

        struct SampleWeightedBackward {
            pred_grad_cell: Rc<std::cell::RefCell<Option<Array1<f32>>>>,
            grad: Array1<f32>,
        }

        impl BackwardOp for SampleWeightedBackward {
            fn backward(&self) {
                let mut pred_grad = self.pred_grad_cell.borrow_mut();
                if let Some(existing) = pred_grad.as_mut() {
                    *existing = &*existing + &self.grad;
                } else {
                    *pred_grad = Some(self.grad.clone());
                }
            }
        }

        if predictions.requires_grad() {
            loss.set_backward_op(Rc::new(SampleWeightedBackward {
                pred_grad_cell: predictions.grad_cell(),
                grad,
            }));
        }

        loss
    }
}

impl LossFn for SampleWeightedLoss {
    fn forward(&self, predictions: &Tensor, targets: &Tensor) -> Tensor {
        // Default: uniform weights
        let weights = vec![1.0; predictions.len()];
        self.forward_weighted(predictions, targets, &weights)
    }

    fn name(&self) -> &'static str {
        "SampleWeighted"
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::train::MSELoss;
    use approx::assert_relative_eq;

    #[test]
    fn test_weighted_loss_scales_value() {
        let loss_fn = WeightedLoss::new(Box::new(MSELoss), 1.5);
        let unweighted = MSELoss;

        let pred = Tensor::from_vec(vec![1.0, 2.0, 3.0], true);
        let target = Tensor::from_vec(vec![1.5, 2.5, 3.5], false);

        let weighted = loss_fn.forward(&pred, &target);
        let base = unweighted.forward(&pred.clone(), &target);

        // Weighted loss should be 1.5x the base loss
        assert_relative_eq!(weighted.data()[0], base.data()[0] * 1.5, epsilon = 1e-5);
    }

    #[test]
    fn test_weighted_loss_unit_weight() {
        let loss_fn = WeightedLoss::new(Box::new(MSELoss), 1.0);
        let unweighted = MSELoss;

        let pred = Tensor::from_vec(vec![1.0, 2.0], true);
        let target = Tensor::from_vec(vec![1.5, 2.5], false);

        let weighted = loss_fn.forward(&pred, &target);
        let base = unweighted.forward(&pred.clone(), &target);

        // Should be equal with weight 1.0
        assert_relative_eq!(weighted.data()[0], base.data()[0], epsilon = 1e-5);
    }

    #[test]
    fn test_weighted_loss_zero_weight() {
        let loss_fn = WeightedLoss::new(Box::new(MSELoss), 0.0);

        let pred = Tensor::from_vec(vec![1.0, 2.0], true);
        let target = Tensor::from_vec(vec![10.0, 20.0], false);

        let loss = loss_fn.forward(&pred, &target);

        // Zero weight -> zero loss
        assert_relative_eq!(loss.data()[0], 0.0, epsilon = 1e-5);
    }

    #[test]
    fn test_weighted_loss_methods() {
        let mut loss_fn = WeightedLoss::new(Box::new(MSELoss), 1.5);

        assert_eq!(loss_fn.weight(), 1.5);
        assert_eq!(loss_fn.name(), "Weighted");

        loss_fn.set_weight(2.0);
        assert_eq!(loss_fn.weight(), 2.0);
    }

    #[test]
    fn test_weighted_loss_unweighted() {
        let loss_fn = WeightedLoss::unweighted(Box::new(MSELoss));
        let pred = Tensor::from_vec(vec![1.0, 2.0], true);
        let target = Tensor::from_vec(vec![1.5, 2.5], false);
        let loss = loss_fn.forward(&pred, &target);
        assert_eq!(loss_fn.weight(), 1.0);
        assert!(loss.data()[0] > 0.0);
    }

    #[test]
    fn test_weighted_no_grad() {
        let loss_fn = WeightedLoss::new(Box::new(MSELoss), 1.5);
        let pred = Tensor::from_vec(vec![1.0, 2.0], false);
        let target = Tensor::from_vec(vec![1.5, 2.5], false);
        let loss = loss_fn.forward(&pred, &target);
        assert!(loss.data()[0] > 0.0);
    }

    #[test]
    fn test_weighted_backward_with_grad() {
        let loss_fn = WeightedLoss::new(Box::new(MSELoss), 2.0);
        let pred = Tensor::from_vec(vec![1.0, 2.0], true);
        let target = Tensor::from_vec(vec![0.0, 0.0], false);

        let loss = loss_fn.forward(&pred, &target);
        if let Some(backward_op) = loss.backward_op() {
            backward_op.backward();
        }

        // Verify gradient was set
        let grad = pred.grad();
        assert!(grad.is_some());
    }

    #[test]
    fn test_sample_weighted_loss_uniform() {
        let loss_fn = SampleWeightedLoss::new(Box::new(MSELoss));

        let pred = Tensor::from_vec(vec![1.0, 2.0, 3.0], true);
        let target = Tensor::from_vec(vec![1.5, 2.5, 3.5], false);

        // Default forward uses uniform weights
        let loss = loss_fn.forward(&pred, &target);

        // Should match regular MSE
        let mse_loss = MSELoss.forward(&pred.clone(), &target);
        assert_relative_eq!(loss.data()[0], mse_loss.data()[0], epsilon = 1e-5);
    }

    #[test]
    fn test_sample_weighted_loss_custom_weights() {
        let loss_fn = SampleWeightedLoss::new(Box::new(MSELoss));

        let pred = Tensor::from_vec(vec![0.0, 0.0], true);
        let target = Tensor::from_vec(vec![1.0, 1.0], false);
        let weights = vec![2.0, 0.0]; // First sample 2x, second ignored

        let loss = loss_fn.forward_weighted(&pred, &target, &weights);

        // Weighted MSE = (2.0 * 1.0 + 0.0 * 1.0) / 2 = 1.0
        assert_relative_eq!(loss.data()[0], 1.0, epsilon = 1e-5);
    }

    #[test]
    fn test_sample_weighted_loss_gradient() {
        let loss_fn = SampleWeightedLoss::new(Box::new(MSELoss));

        let pred = Tensor::from_vec(vec![0.0, 0.0], true);
        let target = Tensor::from_vec(vec![1.0, 1.0], false);
        let weights = vec![2.0, 1.0];

        let loss = loss_fn.forward_weighted(&pred, &target, &weights);

        if let Some(backward_op) = loss.backward_op() {
            backward_op.backward();
        }

        let grad = pred.grad().expect("gradient should be available");
        // Gradient: 2 * w * (pred - target) / n
        // First: 2 * 2.0 * (-1) / 2 = -2.0
        // Second: 2 * 1.0 * (-1) / 2 = -1.0
        assert_relative_eq!(grad[0], -2.0, epsilon = 1e-5);
        assert_relative_eq!(grad[1], -1.0, epsilon = 1e-5);
    }

    #[test]
    fn test_sample_weighted_citl_reweight() {
        // Simulate CITL --reweight 1.5 for compiler-verified samples
        let loss_fn = SampleWeightedLoss::new(Box::new(MSELoss));

        let pred = Tensor::from_vec(vec![0.0, 0.0, 0.0], true);
        let target = Tensor::from_vec(vec![1.0, 1.0, 1.0], false);

        // First two samples are compiler-verified (1.5x weight)
        // Third sample is rule-based (1.0x weight)
        let weights = vec![1.5, 1.5, 1.0];

        let weighted_loss = loss_fn.forward_weighted(&pred, &target, &weights);

        // Regular loss (uniform weights)
        let uniform = loss_fn.forward(&pred.clone(), &target);

        // Weighted should be higher due to 1.5x weights
        assert!(weighted_loss.data()[0] > uniform.data()[0]);
    }

    #[test]
    fn test_sample_weighted_no_grad() {
        let loss_fn = SampleWeightedLoss::new(Box::new(MSELoss));
        let pred = Tensor::from_vec(vec![1.0, 2.0], false);
        let target = Tensor::from_vec(vec![1.5, 2.5], false);
        let weights = vec![1.0, 2.0];
        let loss = loss_fn.forward_weighted(&pred, &target, &weights);
        assert!(loss.data()[0] > 0.0);
    }

    #[test]
    #[should_panic(expected = "Weights must match")]
    fn test_sample_weighted_mismatched_weights() {
        let loss_fn = SampleWeightedLoss::new(Box::new(MSELoss));
        let pred = Tensor::from_vec(vec![1.0, 2.0, 3.0], true);
        let target = Tensor::from_vec(vec![1.0, 2.0, 3.0], false);
        let weights = vec![1.0, 1.0]; // Wrong length
        loss_fn.forward_weighted(&pred, &target, &weights);
    }

    #[test]
    fn test_gradient_accumulation_sample_weighted() {
        let pred = Tensor::from_vec(vec![1.0, 2.0], true);
        let target = Tensor::from_vec(vec![0.0, 0.0], false);
        let weights = vec![1.0, 1.5];
        let loss_fn = SampleWeightedLoss::new(Box::new(MSELoss));

        let loss1 = loss_fn.forward_weighted(&pred, &target, &weights);
        if let Some(op) = loss1.backward_op() {
            op.backward();
        }

        let loss2 = loss_fn.forward_weighted(&pred, &target, &weights);
        if let Some(op) = loss2.backward_op() {
            op.backward();
        }

        let grad = pred.grad().expect("gradient should be available");
        assert!(grad[0].is_finite());
        assert!(grad[1].is_finite());
    }
}