gras 2.0.1

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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
//! Scoring — fitness function for ranking individuals.

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.
#[derive(Clone)]
pub enum Fitness {
    /// Engine-computed: a pure `(pred, target) → f32` scoring function,
    /// plus the direction and label that travel
    Computed {
        /// Ranking metric: `(pred, target) → f32`.
        score_fn: std::sync::Arc<ScoreFn>,
        /// Score direction.
        direction: Direction,
        /// Label for logs.
        label: String,
    },
    /// Trainer-reported: the value arrives via `StepReport.fitness`;
    /// 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: std::sync::Arc::new(score_fn) as std::sync::Arc<ScoreFn>,
            direction,
            label: label.to_string(),
        }
    }

    /// Trainer-reported fitness (RL style): the trainer supplies the scalar
    /// each step and the engine ranks
    pub fn reported(direction: Direction, label: &str) -> Self {
        Fitness::Reported {
            direction,
            label: label.to_string(),
        }
    }

    /// Lower-is-better scorer — shorthand
    /// `Fitness::new(score_fn, Direction::Minimize, label)`.
    pub fn minimize<F>(label: &str, score_fn: F) -> Self
    where
        F: Fn(&Variable, &Variable) -> Result<f32> + Send + Sync + 'static,
    {
        Fitness::new(score_fn, Direction::Minimize, label)
    }

    /// Higher-is-better scorer — shorthand
    /// `Fitness::new(score_fn, Direction::Maximize, label)`.
    pub fn maximize<F>(label: &str, score_fn: F) -> Self
    where
        F: Fn(&Variable, &Variable) -> Result<f32> + Send + Sync + 'static,
    {
        Fitness::new(score_fn, Direction::Maximize, label)
    }

    /// Score prediction against target — engine-computed ranking metric.
    /// Errors on a [`Fitness::Reported`] (nothing to score there).
    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);

/// One informative metric's contribution to the RANKING (`RaceConfig::selection_metrics`): the metric's smoothed window centre times `weight`, added to the fitness score.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SelectionMetric {
    /// The metric's label, as registered in `RaceConfig::metrics`.
    pub label: String,
    /// Multiplier on the metric's smoothed window centre (`0.0` is allowed, and pointless).
    pub weight: f32,
}

/// An informative (non-ranking) metric for a run — a label plus its closure;
/// values live in `NetMetrics::informative` in the run's `Vec<Metric>` order.
#[derive(Clone)]
pub struct Metric {
    /// Metric label, recorded in engine.json/history.csv.
    pub label: String,
    score_fn: std::sync::Arc<ScoreFn>,
}

impl Metric {
    /// Build a metric: a label + your own `(pred, target) -> f32` closure.
    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,
        )
    }

    /// `Fitness` is `Clone` so one scorer can be shared across runs: the clone must run the SAME
    /// closure (not a rebuilt one), and carry the same direction and label.
    #[test]
    fn fitness_clone_shares_the_scorer() {
        use std::sync::Arc;
        use std::sync::atomic::{AtomicUsize, Ordering};
        let calls = Arc::new(AtomicUsize::new(0));
        let counter = Arc::clone(&calls);
        let f = Fitness::maximize("counter", move |_p, _t| {
            counter.fetch_add(1, Ordering::SeqCst);
            Ok(1.0)
        });
        let g = f.clone();
        assert!(f.is_computed() && g.is_computed());
        assert_eq!(g.label(), "counter");
        assert_eq!(g.direction(), Direction::Maximize);
        let x = input(&[3.5]);
        assert_eq!(f.score(&x, &x).unwrap(), 1.0);
        assert_eq!(g.score(&x, &x).unwrap(), 1.0);
        // Both copies hit ONE counter: a re-built closure would have its own.
        assert_eq!(calls.load(Ordering::SeqCst), 2);
    }

    #[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_minimize_maximize_shorthand() {
        let lo = Fitness::minimize("mse", mse_loss_score);
        assert!(lo.is_computed());
        assert_eq!(lo.direction(), Direction::Minimize);
        assert_eq!(lo.label(), "mse");

        let hi = Fitness::maximize("f1", f1_score);
        assert!(hi.is_computed());
        assert_eq!(hi.direction(), Direction::Maximize);
        assert_eq!(hi.label(), "f1");

        // The shorthand must score identically to the long form.
        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 short = Fitness::minimize("mse", mse_loss_score)
            .score(&pred, &y)
            .unwrap();
        let long = Fitness::new(mse_loss_score, Direction::Minimize, "mse")
            .score(&pred, &y)
            .unwrap();
        assert!((short - long).abs() < 1e-9);
    }

    #[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");
    }

    #[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));
                }
            }
        }


    }
}