gras 1.1.2

A Genetic Programming framework for Neural Architecture Search in Rust
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
//! Scoring — fitness function for ranking individuals.
//!
//! [`Fitness`] is a pure scoring function. Training loss is the user's
//! responsibility (lives inside the [`Trainer`](crate::trainer::Trainer)).

use flodl::Variable;
use flodl::tensor::Result;
use serde::{Deserialize, Serialize};

/// The engine-computed scoring signature: `(pred, target) → f32`.
type ScoreFn = dyn Fn(&Variable, &Variable) -> Result<f32> + Send + Sync;

// ── Direction — lower or higher is better ─────────────────────────────────

/// Whether lower or higher is better.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
pub enum Direction {
    /// Lower is better (losses).
    #[default]
    Minimize,
    /// Higher is better (metrics).
    Maximize,
}

impl Direction {
    /// Is `new` better than `current`?
    pub fn is_better(&self, new: f32, current: f32) -> bool {
        match self {
            Direction::Minimize => new < current,
            Direction::Maximize => new > current,
        }
    }

    /// Compact arrow for logs: `↓` or `↑`.
    pub fn arrow(&self) -> &'static str {
        match self {
            Direction::Minimize => "↓",
            Direction::Maximize => "↑",
        }
    }

    /// Total-order comparison under this direction (for `max_by`).
    /// NaN treated as equal.
    pub fn cmp(&self, a: f32, b: f32) -> std::cmp::Ordering {
        match self {
            Direction::Minimize => b.partial_cmp(&a).unwrap_or(std::cmp::Ordering::Equal),
            Direction::Maximize => a.partial_cmp(&b).unwrap_or(std::cmp::Ordering::Equal),
        }
    }
}

// ── Fitness — computed or reported ───────────────────────────────────────

/// Ranking signal for the race. Two flavors:
///
/// - **[`Fitness::Computed`]** — the engine scores `(pred, target)` itself on
///   the step's eval batch (supervised style: accuracy, mse, …). Built with
///   [`Fitness::new`].
/// - **[`Fitness::Reported`]** — the trainer computes the scalar however it
///   wants (e.g. an RL episode reward) and ships it back in
///   [`StepReport::fitness`](crate::trainer::StepReport); the engine only
///   ranks/culls on the reported values. Built with [`Fitness::reported`].
///
/// In both cases the engine's evolutionary machinery (ranking, culling,
/// gates, smoothing) operates on the scalar — the flavors differ only in
/// WHO computes it and whether a `(pred, target)` pair is needed.
pub enum Fitness {
    /// Engine-computed: a pure `(pred, target) → f32` scoring function,
    /// plus the direction and label that travel with it.
    Computed {
        /// Ranking metric: `(pred, target) → f32`.
        score_fn: Box<ScoreFn>,
        /// Score direction.
        direction: Direction,
        /// Label for logs.
        label: String,
    },
    /// Trainer-reported: the value arrives via `StepReport.fitness`; the
    /// engine never scores. Carries only the direction and label.
    Reported {
        /// Score direction.
        direction: Direction,
        /// Label for logs.
        label: String,
    },
}

impl Fitness {
    /// Create a new engine-computed fitness function (supervised style).
    pub fn new<F>(score_fn: F, direction: Direction, label: &str) -> Self
    where
        F: Fn(&Variable, &Variable) -> Result<f32> + Send + Sync + 'static,
    {
        Fitness::Computed {
            score_fn: Box::new(score_fn) as Box<ScoreFn>,
            direction,
            label: label.to_string(),
        }
    }

    /// Trainer-reported fitness (RL / episode style): the trainer supplies
    /// the scalar in `StepReport.fitness` each step; the engine ranks on it.
    /// The engine never calls a scorer in this mode.
    pub fn reported(direction: Direction, label: &str) -> Self {
        Fitness::Reported {
            direction,
            label: label.to_string(),
        }
    }

    /// Score prediction against target — engine-computed ranking metric.
    ///
    /// Errors on a [`Fitness::Reported`] (the trainer owns the value there —
    /// there is nothing to score). Callers on engine paths that may run in
    /// reported mode branch on [`Fitness::is_reported`] first.
    pub fn score(&self, pred: &Variable, target: &Variable) -> Result<f32> {
        match self {
            Fitness::Computed { score_fn, .. } => score_fn(pred, target),
            Fitness::Reported { label, .. } => Err(flodl::tensor::TensorError::new(&format!(
                "fitness `{label}` is Reported — the trainer supplies the value in StepReport; there is no (pred, target) scorer to call"
            ))),
        }
    }

    /// Score direction.
    pub fn direction(&self) -> Direction {
        match self {
            Fitness::Computed { direction, .. } => *direction,
            Fitness::Reported { direction, .. } => *direction,
        }
    }

    /// Label for logs.
    pub fn label(&self) -> &str {
        match self {
            Fitness::Computed { label, .. } => label,
            Fitness::Reported { label, .. } => label,
        }
    }

    /// Does the engine compute the score itself (`true` = Computed)?
    pub fn is_computed(&self) -> bool {
        matches!(self, Fitness::Computed { .. })
    }

    /// Does the trainer report the score (`true` = Reported)?
    pub fn is_reported(&self) -> bool {
        matches!(self, Fitness::Reported { .. })
    }
}

// ── Re-exports for backward compat ────────────────────────────────────────

// Historical note: old code used FitnessKind in the pre-split engine config;
// we keep a serializable label string instead.

/// Serialized fitness label for engine.json (e.g. "mse", "accuracy").
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct FitnessLabel(pub String);

/// An informative (non-ranking) metric configured for a run — e.g. "accuracy",
/// "f1". Carries only its label; the actual per-step values live in
/// `NetMetrics::informative` (same order as the run's `Vec<Metric>`).
///
/// There are no built-in labels: a metric IS a closure
/// (`Metric::custom("my_metric", |pred, y| ...)`), so what gets measured is
/// always explicit and never a name lookup that can silently drift. The label
/// is for history.csv/logs only — the closure is code, not data, so engine.json
/// records just the label.
#[derive(Clone)]
pub struct Metric {
    pub label: String,
    score_fn: std::sync::Arc<ScoreFn>,
}

impl Metric {
    /// The only way to build a metric: a label + your own scoring closure
    /// `(pred, target) -> f32`. Recorded by label in engine.json/history.csv,
    /// scored by the closure at eval time.
    pub fn custom<F>(label: impl Into<String>, score_fn: F) -> Self
    where
        F: Fn(&Variable, &Variable) -> Result<f32> + Send + Sync + 'static,
    {
        Metric {
            label: label.into(),
            score_fn: std::sync::Arc::new(score_fn),
        }
    }

    /// Label for logs / engine.json / history.csv header.
    pub fn label(&self) -> &str {
        &self.label
    }

    /// Score this metric with its own closure.
    pub fn score(&self, pred: &Variable, y: &Variable) -> Result<f32> {
        (self.score_fn)(pred, y)
    }
}

impl PartialEq for Metric {
    fn eq(&self, other: &Self) -> bool {
        self.label == other.label // closures don't compare; identity is the label
    }
}

impl std::fmt::Debug for Metric {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Metric")
            .field("label", &self.label)
            .finish()
    }
}

impl Default for FitnessLabel {
    fn default() -> Self {
        FitnessLabel("loss".to_string())
    }
}

// ── Tests ────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::graph::network::Network;
    use crate::graph::node::Node;
    use crate::graph::topology::Topology;
    use crate::utils::score::*;
    use flodl::nn::Module;
    use proptest::prelude::*;

    fn tiny_net() -> Network {
        let mut graph = Topology::new(0, None);
        graph.nodes.push(Node::new_input(0, 1));
        graph.nodes.push(Node::new_output(1, 1, 1));
        graph.finalize();
        Network::build(&graph, flodl::Device::CPU).unwrap()
    }

    fn input(xs: &[f32]) -> Variable {
        Variable::new(
            flodl::Tensor::from_f32(xs, &[xs.len() as i64, 1], flodl::Device::CPU).unwrap(),
            false,
        )
    }

    #[test]
    fn test_direction_semantics() {
        assert!(Direction::Minimize.is_better(0.5, 1.0));
        assert!(!Direction::Minimize.is_better(1.0, 0.5));
        assert!(Direction::Maximize.is_better(1.0, 0.5));
        assert!(!Direction::Maximize.is_better(0.5, 1.0));
    }

    #[test]
    fn test_reported_fitness_contract() {
        let f = Fitness::reported(Direction::Maximize, "episode_reward");
        assert!(f.is_reported());
        assert!(!f.is_computed());
        assert_eq!(f.direction(), Direction::Maximize);
        assert_eq!(f.label(), "episode_reward");
        // No scorer exists — scoring must error loudly, not return a value.
        let net = tiny_net();
        let x = input(&[1.0, 2.0, 3.0]);
        let pred = net.forward(&x).unwrap();
        assert!(f.score(&pred, &pred).is_err());
    }

    #[test]
    fn test_computed_fitness_flags() {
        let f = Fitness::new(mse_loss_score, Direction::Minimize, "mse");
        assert!(f.is_computed());
        assert!(!f.is_reported());
    }

    #[test]
    fn test_fitness_new() {
        let f = Fitness::new(
            |pred, y| {
                let diff = pred.data().sub(&y.data())?;
                let sq = diff.mul(&diff)?;
                Ok(sq.mean()?.item()? as f32)
            },
            Direction::Minimize,
            "mse",
        );
        let net = tiny_net();
        let x = input(&[1.0, 2.0, 3.0]);
        let y = input(&[1.0, 2.0, 3.0]);
        let pred = net.forward(&x).unwrap();
        let score = f.score(&pred, &y).unwrap();
        assert!(score.is_finite());
        assert!(score >= 0.0);
        assert_eq!(f.direction(), Direction::Minimize);
        assert_eq!(f.label(), "mse");
    }

    // TODO: uncomment when from_loss_with_other is re-enabled.
    // #[test]
    // fn test_fitness_from_loss_with_other() {
    //     let f = Fitness::from_loss_with_other(
    //         accuracy_score,
    //         |pred, y| flodl::nn::loss::mse_loss(pred, y),
    //         Direction::Maximize,
    //         Direction::Minimize,
    //         "accuracy",
    //         "mse",
    //     );
    //     ...
    // }

    #[test]
    fn test_scoring_helpers() {
        let net = tiny_net();
        let x = input(&[1.0, 2.0, 3.0]);
        let pred = net.forward(&x).unwrap();
        // Use pred as both pred and y for perfect fit.
        let y = Variable::new(pred.data().clone(), false);
        let r2 = r2_score(&pred, &y).unwrap();
        assert!((r2 - 1.0).abs() < 1e-3, "perfect fit → R2 ≈ 1, got {r2}");
        let mse = flodl::nn::loss::mse_loss(&pred, &y)
            .unwrap()
            .item()
            .unwrap() as f32;
        assert!(mse < 1e-6);
    }

    #[test]
    fn test_categorical_helpers() {
        let mut graph = Topology::new(0, None);
        graph.options.input_dim = Some(2);
        graph.nodes.push(Node::new_input(0, 2));
        graph.nodes.push(Node::new_hidden(1, 2, 2));
        graph.nodes.push(Node::new_output(2, 2, 2));
        graph.nodes[2].hidden_dim = Some(2);
        graph.finalize();
        let net = Network::build(&graph, flodl::Device::CPU).unwrap();
        let x = Variable::new(
            flodl::Tensor::from_f32(&[2.0, 0.5, 0.1, 0.9, 1.2, 0.3], &[3, 2], flodl::Device::CPU)
                .unwrap(),
            false,
        );
        let pred = net.forward(&x).unwrap();
        let pa = pred.data().argmax(1, false).unwrap().to_i64_vec().unwrap();
        let y = Variable::new(
            crate::utils::tabular_data::one_hot(
                &pa.iter().map(|&v| v as usize).collect::<Vec<_>>(),
                2,
                flodl::Device::CPU,
            )
            .unwrap(),
            false,
        );
        let acc = accuracy_score(&pred, &y).unwrap();
        let ce = cross_entropy_onehot(&pred, &y).unwrap();
        assert!((acc - 1.0).abs() < 1e-6, "acc = {acc}");
        assert!(ce > 0.0 && ce.is_finite(), "ce = {ce}");
    }

    #[test]
    fn test_f1_and_precision_from_vecs() {
        assert_eq!(f1_from_vecs(&[0, 1, 0, 1], &[0, 1, 0, 1], 2), 1.0);
        assert_eq!(precision_from_vecs(&[0, 1, 0, 1], &[0, 1, 0, 1], 2), 1.0);
        let pa = [0i64, 0, 0, 0];
        let ta = [0i64, 1, 0, 1];
        assert!((precision_from_vecs(&pa, &ta, 2) - 0.25).abs() < 1e-9);
        assert!((f1_from_vecs(&pa, &ta, 2) - 1.0 / 3.0).abs() < 1e-9);
        assert_eq!(f1_from_vecs(&[], &[], 2), 0.0);
        assert_eq!(precision_from_vecs(&[0], &[0], 0), 0.0);
    }

    #[test]
    fn test_all_scoring_helpers() {
        let net = tiny_net();
        let x = input(&[1.0, 2.0, 3.0]);
        let pred = net.forward(&x).unwrap();
        // Use pred as both pred and y for perfect-fit case.
        let y = Variable::new(pred.data().clone(), false);

        let mse = mse_loss_score(&pred, &y).unwrap();
        assert!(mse < 1e-6, "mse_score = {mse}");
        let l1 = l1_loss_score(&pred, &y).unwrap();
        assert!(l1 < 1e-6, "l1_score = {l1}");
        let rmse = rmse_score(&pred, &y).unwrap();
        assert!(rmse < 1e-3, "rmse_score = {rmse}");
        let r2 = r2_score(&pred, &y).unwrap();
        assert!((r2 - 1.0).abs() < 1e-3, "r2_score = {r2}");

        // Cross-entropy: > 0 for valid predictions
        let mut graph2 = Topology::new(0, None);
        graph2.options.input_dim = Some(2);
        graph2.nodes.push(Node::new_input(0, 2));
        graph2.nodes.push(Node::new_hidden(1, 2, 2));
        graph2.nodes.push(Node::new_output(2, 2, 3));
        graph2.nodes[2].hidden_dim = Some(3);
        graph2.finalize();
        let cat_net = Network::build(&graph2, flodl::Device::CPU).unwrap();
        let cx = Variable::new(
            flodl::Tensor::from_f32(&[1.0, 0.5, 0.1, 0.9], &[2, 2], flodl::Device::CPU).unwrap(),
            false,
        );
        let cpred = cat_net.forward(&cx).unwrap();
        // One-hot targets
        let ct = Variable::new(
            flodl::Tensor::from_f32(&[1.0, 0.0, 0.0, 0.0, 1.0, 0.0], &[2, 3], flodl::Device::CPU)
                .unwrap(),
            false,
        );
        let ce = cross_entropy_onehot(&cpred, &ct).unwrap();
        assert!(ce > 0.0 && ce.is_finite(), "cross_entropy = {ce}");
        let acc = accuracy_score(&cpred, &ct).unwrap();
        assert!((0.0..=1.0).contains(&acc), "accuracy = {acc}");
        let f1 = f1_score(&cpred, &ct).unwrap();
        assert!((0.0..=1.0).contains(&f1), "f1 = {f1}");
        let prec = precision_score(&cpred, &ct).unwrap();
        assert!((0.0..=1.0).contains(&prec), "precision = {prec}");
        let (pa, ta) = argmax_classes(&cpred, &ct).unwrap();
        assert_eq!(pa.len(), 2);
        assert_eq!(ta.len(), 2);
    }

    proptest! {
        #[test]
        fn prop_direction_is_better_is_antisymmetric(a in -100.0f32..100.0, b in -100.0f32..100.0) {
            if a != b {
                if Direction::Minimize.is_better(a, b) {
                    prop_assert!(!Direction::Minimize.is_better(b, a));
                }
                if Direction::Maximize.is_better(a, b) {
                    prop_assert!(!Direction::Maximize.is_better(b, a));
                }
            }
        }


    }
}