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
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
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
//! The reference [`RlStep`]: REINFORCE over any [`Env`].

use crate::graph::network::Network;
use crate::trainer::challenge::{
    ChallengeDecay, ChallengePolicy, ForcedAction, challenge_fires, forced_action,
};
use crate::trainer::core::{RlContext, RlStep, RlStepMeta, RlStepReport};
use crate::trainer::env::Env;
use crate::utils::fitness::Metric;
use crate::utils::race_steps::train_one_step_pred_only;
use flodl::nn::Module;
use flodl::nn::optim::Optimizer;
use flodl::tensor::Result;
use flodl::{Device, Tensor, Variable};
use std::cmp::Ordering;

/// Gradient-norm clip per optimizer step (default: the cartpole recipe's 2.0;
/// 0 disables clipping).
const DEFAULT_GRAD_CLIP: f32 = 2.0;

/// TRAIN episodes per net per step — the learning signal (default: 1,
/// cartpole recipe).
const DEFAULT_MATCHES_PER_STEP: usize = 1;

/// EVAL episodes per net per step — the ranking signal (default: 5, the cartpole recipe).
const DEFAULT_EVAL_MATCHES_PER_STEP: usize = 5;

/// Peak probability that a step fires a challenge (default: the cartpole
/// recipe's 0.1 — see the module docs on why the default is not 0).
const DEFAULT_CHALLENGE_PROB: f32 = 0.1;

/// Challenge decay shape (default: the cartpole recipe's `custom:0.5`, i.e.
/// `eff = p × (1 − √progress)`).
const DEFAULT_CHALLENGE_DECAY: ChallengeDecay = ChallengeDecay::Custom { exponent: 0.5 };

/// The seed offset that separates a step's EVAL exam from its TRAIN episodes — a plain add on the run seed, so the two bases sit that constant apart for any run seed.
const EVAL_SEED_OFFSET: u64 = 1000;

/// The guardrail's games stay on a fixed seed forever: a verdict has to be
/// comparable across runs, and each run draws its own race seed.

/// What a REINFORCE step optimizes and ranks on — the two axes are one decision,
/// so they are one knob.
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Signal {
    /// Survival: a turn's return is the turns remaining in its episode, and the fitness is the mean
    /// episode length.
    Turns,
    /// Episode return: a turn's return is `G_t = Σ_k γ^k · r_{t+k}` — the discount shapes
    /// turns get credit — and the fitness is the mean episode return (undiscounted: the number
    Return {
        /// Per-turn discount `γ`, e.g. 0.99.
        discount: f32,
    },
}

impl Signal {
    /// The name this signal goes by in `describe()` and in a log.
    pub fn name(self) -> &'static str {
        match self {
            Signal::Turns => "turns",
            Signal::Return { .. } => "return",
        }
    }
}

/// What the net is told about the PAST at each turn — the trainer's answer to an RL policy being
/// memoryless by construction.
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum ObsMemory {
    /// No memory: the net sees the current observation alone (the engine
    None,
    /// `[obs, obs − prev_obs]` — the discrete derivative. First turn's half is zero.
    Delta,
    /// `[obs, ema]` with `ema_t = β·ema_{t−1} + (1−β)·obs_t`, seeded at the episode's first
    /// observation — the SMOOTH version of "the previous observation", so one noisy turn cannot
    Ema { beta: f32 },
}

impl ObsMemory {
    /// How many observation-widths the net is fed (`1` = no memory, `2` = a channel).
    pub fn width_factor(self) -> usize {
        match self {
            ObsMemory::None => 1,
            ObsMemory::Delta | ObsMemory::Ema { .. } => 2,
        }
    }
}

/// One episode's [`ObsMemory`], seeded at its first observation.
struct MemoryState {
    memory: ObsMemory,
    prev: Vec<f32>,
    ema: Vec<f32>,
}

impl MemoryState {
    fn new(memory: ObsMemory, first: &[f32]) -> Self {
        Self {
            memory,
            prev: first.to_vec(),
            ema: first.to_vec(),
        }
    }

    /// The row the net is fed for `obs`, advancing the memory.
    fn row(&mut self, obs: &[f32]) -> Vec<f32> {
        let mut fed = obs.to_vec();
        match self.memory {
            ObsMemory::None => {}
            ObsMemory::Delta => {
                fed.extend(obs.iter().zip(&self.prev).map(|(o, p)| o - p));
                self.prev = obs.to_vec();
            }
            ObsMemory::Ema { beta } => {
                // Includes the current observation, so the feature is never stale.
                for (e, o) in self.ema.iter_mut().zip(obs) {
                    *e = beta * *e + (1.0 - beta) * o;
                }
                fed.extend(&self.ema);
            }
        }
        fed
    }
}

/// The crate's reference [`RlStep`]: REINFORCE over an [`Env`]. See the module
/// docs for the algorithm, the replay contract, and the knob defaults.
pub struct Reinforce<E: Env> {
    /// The world being trained, owned by the trainer (it holds the episode state
    /// between `reset` and the episode's end).
    env: E,
    /// Device every tensor in a step lives
    device: Device,
    /// Adam step size for the update.
    learning_rate: f32,
    /// Gradient-norm clip per optimizer step (0 = off).
    grad_clip: f32,
    /// TRAIN episodes per net per step.
    matches_per_step: usize,
    /// EVAL episodes per net per step (the exam).
    eval_matches_per_step: usize,
    /// Whether the exam is drawn per CLOCK (default) rather than per era — see
    /// [`Self::with_per_clock_exam`].
    per_clock_exam: bool,
    /// What the returns and the fitness are derived
    signal: Signal,
    /// The PAST handed to the net alongside the instant (`None` = the observation alone).
    obs_memory: ObsMemory,
    /// The trainer's own anti-plateau knob — the engine never sees
    challenge_prob: f32,
    /// Which action a fired challenge forces.
    challenge_policy: ChallengePolicy,
    /// How the challenge knob decays over the step budget.
    challenge_decay: ChallengeDecay,
    /// A NAMED LR schedule scaling [`Self::learning_rate`] over the run (`None` =
    /// the rate stays put). Recorded in `describe()`, so a resume cannot swap
    lr_schedule: Option<crate::trainer::LrSchedule>,
    /// Which update the optimizer makes (`adam`, the reference recipe).
    optimizer: crate::trainer::OptimizerKind,
    /// How the acting forward pass turns action values into a move, and the temperature
    /// [`ActionRule::Softmax`] draws at — the build consts unless a caller sets them.
    action_rule: ActionRule,
    /// The EXAM's rule ([`EVAL_ACTION_RULE`], the greedy head unless a caller sets it): training may explore while the reading stays the policy the net actually plays.
    eval_action_rule: ActionRule,
    softmax_temperature: f32,
}

impl<E: Env> Reinforce<E> {
    /// Train `env` with REINFORCE on `device`.
    pub fn new(env: E, device: Device) -> Self {
        Self {
            env,
            device,
            learning_rate: crate::utils::training::DEFAULT_LR,
            grad_clip: DEFAULT_GRAD_CLIP,
            matches_per_step: DEFAULT_MATCHES_PER_STEP,
            eval_matches_per_step: DEFAULT_EVAL_MATCHES_PER_STEP,
            per_clock_exam: true,
            signal: Signal::Turns,
            obs_memory: ObsMemory::None,
            challenge_prob: DEFAULT_CHALLENGE_PROB,
            challenge_policy: ChallengePolicy::LeastAction,
            challenge_decay: DEFAULT_CHALLENGE_DECAY,
            lr_schedule: None,
            optimizer: crate::trainer::OptimizerKind::default(),
            action_rule: ACTION_RULE,
            eval_action_rule: EVAL_ACTION_RULE,
            softmax_temperature: SOFTMAX_TEMPERATURE,
        }
    }

    /// Choose the update by name (`adam` is the reference recipe).
    pub fn with_optimizer(mut self, optimizer: crate::trainer::OptimizerKind) -> Self {
        self.optimizer = optimizer;
        self
    }

    /// Set a NAMED LR schedule (`cosine`, `onecycle`, …), scaling the base rate over the run's
    /// budget.
    pub fn with_named_lr_schedule(mut self, schedule: crate::trainer::LrSchedule) -> Self {
        self.lr_schedule = Some(schedule);
        self
    }

    /// Set the TRAIN episodes per step (default 1). The learning signal: more
    /// episodes per update, at N× the environment turns.
    pub fn with_matches_per_step(mut self, n: usize) -> Self {
        self.matches_per_step = n;
        self
    }

    /// Set the EVAL episodes per step (default 5) — the exam the fitness is measured
    pub fn with_eval_matches_per_step(mut self, n: usize) -> Self {
        self.eval_matches_per_step = n;
        self
    }

    /// Draw the EVAL exam per CLOCK (default `true`) instead of per era — see the module docs' replay contract.
    pub fn with_per_clock_exam(mut self, on: bool) -> Self {
        self.per_clock_exam = on;
        self
    }

    /// Set what the returns and the fitness are derived from (default
    /// [`Signal::Turns`]) — see [`Signal`].
    pub fn with_signal(mut self, signal: Signal) -> Self {
        self.signal = signal;
        self
    }

    /// Set the ACTING rule and its temperature (defaults [`ACTION_RULE`] / [`SOFTMAX_TEMPERATURE`]): what both the TRAIN episodes and the EVAL exam act under.
    pub fn with_action_rule(mut self, rule: ActionRule, temperature: f32) -> Self {
        self.action_rule = rule;
        self.softmax_temperature = if temperature.is_finite() && temperature > 0.0 {
            temperature
        } else {
            1.0
        };
        self
    }

    /// How the acting forward pass picks a move, and the temperature its softmax arm draws at.
    pub fn action_rule(&self) -> (ActionRule, f32) {
        (self.action_rule, self.softmax_temperature)
    }

    /// Set the EXAM's acting rule (default [`EVAL_ACTION_RULE`], the greedy head) — the phase split [`Self::with_action_rule`] cannot express: `Softmax` training explores…
    pub fn with_eval_action_rule(mut self, rule: ActionRule) -> Self {
        self.eval_action_rule = rule;
        self
    }

    /// The EXAM's acting rule (the training one is [`Self::action_rule`]).
    pub fn eval_action_rule(&self) -> ActionRule {
        self.eval_action_rule
    }
    /// Feed the net a MEMORY of the trajectory as well as the instant ([`ObsMemory`]): `[obs, obs −
    /// prev]` for a velocity-like derivative, or `[obs, ema]` for a smooth past.
    pub fn with_obs_memory(mut self, memory: ObsMemory) -> Self {
        self.obs_memory = match memory {
            ObsMemory::Ema { beta } if beta.is_finite() => ObsMemory::Ema {
                beta: beta.clamp(0.0, 1.0),
            },
            ObsMemory::Ema { .. } => ObsMemory::Ema { beta: 0.9 },
            other => other,
        };
        self
    }

    /// Set the Adam learning rate (default: the crate's `DEFAULT_LR`).
    pub fn with_learning_rate(mut self, lr: f32) -> Self {
        self.learning_rate = lr;
        self
    }

    /// Set the gradient-norm clip (default 2.0; 0 disables clipping).
    pub fn with_grad_clip(mut self, clip: f32) -> Self {
        self.grad_clip = clip;
        self
    }

    /// Set the anti-plateau challenge: the peak probability a step fires one, which action
    /// forces, and how the knob decays to 0 over the budget.
    pub fn with_challenge(
        mut self,
        prob: f32,
        policy: ChallengePolicy,
        decay: ChallengeDecay,
    ) -> Self {
        self.challenge_prob = prob;
        self.challenge_policy = policy;
        self.challenge_decay = decay;
        self
    }

    /// The world being trained — read it for its own state and diagnostics.
    pub fn env(&self) -> &E {
        &self.env
    }

    /// The world being trained, mutably (a test or a scripted env drives it here).
    pub fn env_mut(&mut self) -> &mut E {
        &mut self.env
    }

    /// What the returns and the fitness are derived
    pub fn signal(&self) -> Signal {
        self.signal
    }

    /// Play ONE episode under the TRAIN acting rule ([`Self::action_rule`]); `forced` is the
    /// challenge override.
    fn play_episode(
        &mut self,
        net: &mut Network,
        start_seed: u64,
        forced: Option<ForcedAction>,
    ) -> Result<Episode> {
        self.play_episode_with_rule(net, start_seed, forced, self.action_rule)
    }

    /// [`Self::play_episode`] under an EXPLICIT rule — the eval exam passes [`Self::eval_action_rule`], so exploration on the training side can never leak into the fitness the…
    fn play_episode_with_rule(
        &mut self,
        net: &mut Network,
        start_seed: u64,
        forced: Option<ForcedAction>,
        rule: ActionRule,
    ) -> Result<Episode> {
        // A policy rollout, not a training forward: dropout stays off,
        // set here so the mode never depends on what the last caller left behind.
        net.eval();
        // The acting sampler's generator, seeded from the episode's OWN seed so a
        // `Softmax` run replays exactly what it played. `Argmax` never reads it.
        let mut rng = fastrand::Rng::with_seed(start_seed ^ ACTION_RULE_SEED_SALT);
        let max_turns = self.env.max_turns();
        let mut episode = Episode::default();
        let mut obs = self.env.reset(start_seed)?;
        // Seeded AT the first observation, so turn 0 has no cold-start spike:
        // delta half is 0 and its EMA half is the observation itself.
        let mut memory = MemoryState::new(self.obs_memory, &obs);
        for _ in 0..max_turns {
            // The row the net SEES and the row the update re-forwards are the same
            // one, so a channel cannot drift between play and update.
            let fed = memory.row(&obs);
            let row = Tensor::from_f32(&fed, &[1, fed.len() as i64], self.device)?;
            let values = net
                .forward(&Variable::new(row, false))?
                .data()
                .to_f32_vec()?;
            let action = match forced {
                Some(forced) => forced.resolve(&values),
                None => choose_action(rule, self.softmax_temperature, &values, &mut rng),
            };
            let (next, reward, done) = self.env.step(action)?;
            episode.turns.push((fed, action));
            episode.rewards.push(reward);
            obs = next;
            if done {
                break;
            }
        }
        Ok(episode)
    }

    /// REINFORCE update over the step's played episodes: `−Σ_t Â_t · log π(a_t|s_t)` with a batch-mean baseline and unit-variance advantages, summed over the batch's turns and…
    fn reinforce_update(
        &self,
        net: &mut Network,
        optimizer: &mut dyn Optimizer,
        episodes: &[Episode],
        input_dim: usize,
    ) -> Result<f32> {
        let actions = self.env.action_count();
        let total: usize = episodes.iter().map(Episode::len).sum();
        let mut flat = Vec::with_capacity(total * input_dim);
        // One row per played turn, one column per action: 1 where the turn's
        // action was taken, 0 elsewhere.
        let mut mask = vec![0.0f32; total * actions];
        let mut returns = Vec::with_capacity(total);
        let mut row = 0usize;
        for episode in episodes {
            // eli5: every turn of the episode gets the return that follows
            let g = episode.returns(self.signal);
            for (t, (obs, action)) in episode.turns.iter().enumerate() {
                flat.extend_from_slice(obs);
                // The head can be wider than the world only by misconfiguration, and a silent wrap
                // here would train on an action the env cannot take — so name the mismatch instead.
                if *action >= actions {
                    return Err(flodl::tensor::TensorError::new(&format!(
                        "reinforce: the policy chose action {action}, but the environment has \
                         {actions} — the topology's output_dim must equal Env::action_count"
                    )));
                }
                mask[row * actions + action] = 1.0;
                returns.push(g[t]);
                row += 1;
            }
        }
        // eli5: the baseline is the batch's mean return; the advantages
        // returns minus it, scaled so one lucky episode cannot dominate a step.
        let baseline = returns.iter().sum::<f32>() / returns.len() as f32;
        let advantages: Vec<f32> = returns.iter().map(|g| g - baseline).collect();
        let adv_std =
            (advantages.iter().map(|a| a * a).sum::<f32>() / advantages.len() as f32).sqrt();
        let scale = 1.0 / adv_std.max(1e-6);

        // The graph must carry dropout (the update's forward is a training
        // forward), and the policy that played the episodes above did
        net.train();
        let x = Variable::new(
            Tensor::from_f32(&flat, &[total as i64, input_dim as i64], self.device)?,
            true,
        );
        // pred: [total, actions]
        let pred = net.forward(&x)?;
        // The score function ∇log π(a|s) REQUIRES a normalized log-prob: raw logits (or an argmax
        // indicator) are not a gradient — keep the log_softmax.
        let logp = pred.data().log_softmax(1)?;
        let m = Tensor::from_f32(&mask, &[total as i64, actions as i64], self.device)?;
        // Zero out the actions not taken: [total, actions] → one finite term per row.
        let chosen = logp.mul(&m)?;
        let adv = Tensor::from_f32(&advantages, &[total as i64, 1], self.device)?;
        // Per turn: Σ_a mask·logp = log π(a_t|s_t), times that turn's advantage.
        let weighted = chosen
            .sum_dims(&[1], false)?
            .reshape(&[total as i64, 1])?
            .mul(&adv)?;
        let s = Tensor::from_f32(
            &[loss_scale(scale, total, LOSS_MEAN_OVER_TURNS)],
            &[1],
            self.device,
        )?;
        let loss = Variable::new(weighted.sum()?.mul(&s)?, false);
        // Back to the resting mode BEFORE the optimizer step re-forwards: the loss above already
        // carries the training-mode graph, and a dropout draw during the re-forward would be
        net.eval();

        // The closure ignores `pred`: the graph above is the one being
        // differentiated, and the step only needs SOME input to re-forward.
        let dummy = Tensor::from_f32(&vec![0.0; input_dim], &[1, input_dim as i64], self.device)?;
        train_one_step_pred_only(
            net,
            optimizer,
            &|_: &Variable| Ok(loss.clone()),
            &dummy,
            self.grad_clip,
        )
    }

    /// The exam's step axis for `step`: the clock (default), or the era when
    /// era-scoping was asked for. One place, so the two axes cannot drift apart.
    fn exam_axis(&self, step: usize, era_len: usize) -> usize {
        if self.per_clock_exam {
            step
        } else {
            eval_era_of(step, era_len)
        }
    }

    /// Score the run's informative metrics on the step's EVAL outcomes.
    fn score_metrics(&self, metrics: &[Metric], outcomes: &[f32]) -> Result<Vec<f32>> {
        if metrics.is_empty() {
            return Ok(Vec::new());
        }
        let t = Tensor::from_f32(outcomes, &[outcomes.len() as i64], self.device)?;
        let (pred, target) = (Variable::new(t.clone(), false), Variable::new(t, false));
        metrics.iter().map(|m| m.score(&pred, &target)).collect()
    }
}

impl<E: Env> RlStep for Reinforce<E> {
    /// Adam over the net's parameters — one optimizer per net, kept across steps.
    fn restore_optimizer(
        &self,
        net: &Network,
        path: &std::path::Path,
    ) -> Option<Box<dyn Optimizer>> {
        self.optimizer.load(net, self.learning_rate, path)
    }

    fn make_optimizer(&self, net: &Network) -> Box<dyn Optimizer> {
        self.optimizer.make(net, self.learning_rate)
    }

    /// The recorded trainer blob — `engine.json`'s record of WHAT trained, so a resume diffs
    /// changed knob by name instead of silently training something else.
    fn describe(&self) -> Option<serde_json::Value> {
        let mut blob = serde_json::json!({
            "trainer": "reinforce",
            "update": "REINFORCE (log_softmax autodiff; per-turn returns, batch-mean baseline, advantage normalization)",
            "env": self.env.describe(),
            "actions": self.env.action_count(),
            "max_turns": self.env.max_turns(),
            "signal": self.signal,
            "matches_per_step": self.matches_per_step,
            "eval_matches_per_step": self.eval_matches_per_step,
            // The exam's step axis, by name: a resume that flipped it would replay
            // different eval games from the very next clock.
            "exam": if self.per_clock_exam { "per_clock" } else { "era" },
            "learning_rate": self.learning_rate,
            "grad_clip": self.grad_clip,
            // The challenge trigger is TRAINER-owned, so this blob
            // place a reader of the run can see
            "challenge_prob": self.challenge_prob,
            "challenge_policy": self.challenge_policy.to_string(),
            "challenge_decay": self.challenge_decay.to_string(),
        });
        // Only when set: the memory doubles the fed row, so a run that never used
        // keeps the exact blob (and therefore the resume compatibility) it had before.
        if self.obs_memory != ObsMemory::None {
            blob["obs_memory"] =
                serde_json::to_value(self.obs_memory).unwrap_or(serde_json::Value::Null);
        }
        // Only when set: an RL run with no schedule keeps the exact blob
        // therefore the resume compatibility) it had before schedules existed.
        if let Some(named) = &self.lr_schedule {
            blob["lr_schedule"] = serde_json::Value::String(named.label());
        }
        // Same rule for the optimizer: only when it is not the reference recipe,
        // an RL run that never named one keeps the blob (and resume) it had before.
        if self.optimizer != crate::trainer::OptimizerKind::default() {
            blob["optimizer"] = serde_json::Value::String(self.optimizer.label().to_string());
        }
        // The acting rule can be the build const OR a per-run setter, so the resume guard must see it: a run recorded under `softmax` cannot resume into an `argmax` trainer.
        if self.action_rule != ActionRule::Argmax {
            blob["action_rule"] = serde_json::Value::String(self.action_rule.as_str().to_string());
            if self.softmax_temperature != SOFTMAX_TEMPERATURE {
                blob["softmax_temperature"] = serde_json::json!(self.softmax_temperature);
            }
        }
        // Same rule for the EXAM's arm: a sampled exam measures a different quantity from a greedy one, so a resume must not swap it.
        if self.eval_action_rule != EVAL_ACTION_RULE {
            blob["eval_action_rule"] =
                serde_json::Value::String(self.eval_action_rule.as_str().to_string());
        }
        Some(blob)
    }

    /// One step: play the TRAIN episodes (challenge-aware), update, then measure
    /// on the shared EVAL exam — the fitness that ranks.
    fn train_step(
        &mut self,
        net: &mut Network,
        optimizer: &mut dyn Optimizer,
        step: usize,
        ctx: &RlContext<'_>,
    ) -> Result<RlStepReport> {
        let actions = self.env.action_count();
        // On a fired step the policy forces an action on every TRAIN turn — a pure
        // fn of (run_seed, net_seed, step), so a resume forces the identical action.
        let challenged = challenge_fires(
            ctx.env.run_seed,
            ctx.net_seed,
            step,
            self.challenge_prob,
            ctx.env.max_steps,
            self.challenge_decay,
        );
        let forced =
            challenged.then(|| forced_action(self.challenge_policy, ctx.net_seed, step, actions));

        // The rate for THIS clock, before any gradient flows: a pure function
        // the clock and the budget, so a replay sets the identical value.
        if let Some(named) = &self.lr_schedule {
            optimizer.set_lr(named.lr(self.learning_rate, step, ctx.env.max_steps) as f64);
        }

        // 1.
        let train_base = ctx.net_seed ^ ctx.env.run_seed;
        let attempt_block = ctx.env.attempt.wrapping_mul(self.matches_per_step as u64);
        let mut episodes: Vec<Episode> = Vec::with_capacity(self.matches_per_step);
        for match_i in 0..self.matches_per_step {
            let seed = episode_start_seed(train_base, step, attempt_block + match_i as u64);
            episodes.push(self.play_episode(net, seed, forced)?);
        }
        let total: usize = episodes.iter().map(Episode::len).sum();

        // 2.
        let train_loss = if total == 0 {
            0.0
        } else {
            // The observation width comes from the observation itself: `Env`
            // reports no size, and the first turn is the only place it shows.
            let input_dim = episodes
                .iter()
                .find_map(|e| e.turns.first().map(|(obs, _)| obs.len()))
                .expect("a played episode has at least one turn");
            self.reinforce_update(net, optimizer, &episodes, input_dim)?
        };

        // 3.
        let eval_base = eval_seed_base(ctx.env.run_seed);
        let exam = self.exam_axis(step, ctx.env.checkpoint_every);
        let mut outcomes: Vec<f32> = Vec::with_capacity(self.eval_matches_per_step);
        let mut eval_turns = 0usize;
        for match_i in 0..self.eval_matches_per_step {
            let seed = episode_start_seed(eval_base, exam, match_i as u64);
            let episode = self.play_episode_with_rule(net, seed, None, self.eval_action_rule)?;
            eval_turns += episode.len();
            outcomes.push(episode.outcome(self.signal));
        }

        // 4. Report: fitness = the exam's mean, the same quantity the guardrail
        //    measures — ranking and holdout agree by construction.
        Ok(RlStepReport {
            train_loss,
            fitness: mean(&outcomes),
            informative: self.score_metrics(ctx.metrics, &outcomes)?,
            rl: Some(RlStepMeta {
                matches: self.matches_per_step + self.eval_matches_per_step,
                // The split matters: a challenge can only force TRAIN turns,
                // `turns/match` stays honest.
                train_turns: total,
                eval_turns,
            }),
        })
    }
}

// ── Pure helpers — the replay contract, in one place each ────────────────────

/// The seed of one episode: a pure function of `(seed_base, step, match_i)`.
pub fn episode_start_seed(seed_base: u64, step: usize, match_i: u64) -> u64 {
    seed_base
        ^ (step as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15)
        ^ match_i.wrapping_mul(0xBF58_476D_1CE4_E5B9)
}

/// The base seed of a step's EVAL exam: the run seed alone, held off the TRAIN draw (which rides
/// `net_seed ^ run_seed`).
fn eval_seed_base(run_seed: u64) -> u64 {
    run_seed.wrapping_add(EVAL_SEED_OFFSET)
}

/// The ERA a clock sits: `era_len` clocks share one — the opt-in axis (`with_per_clock_exam(false)`), where a net read at clock 118 and a newborn read at 121 are graded on…
fn eval_era_of(step: usize, era_len: usize) -> usize {
    if era_len == 0 { step } else { step / era_len }
}

/// The policy's preferred action: the argmax over its action values, ties to the lowest index.
fn greedy_action(values: &[f32]) -> usize {
    let mut best = 0usize;
    for (i, v) in values.iter().enumerate() {
        let better = if v.is_nan() {
            false // a NaN action value is never the preferred one
        } else if values[best].is_nan() {
            true // any number beats a NaN incumbent
        } else {
            matches!(v.partial_cmp(&values[best]), Some(Ordering::Greater))
        };
        if better {
            best = i;
        }
    }
    best
}

/// How the ACTING forward pass turns a net's action values into a move.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ActionRule {
    /// The greedy head: argmax over the action values, ties to the lowest index.
    Argmax,
    /// Sample from `softmax(values / T)`, `T` the run's temperature (`with_action_rule`, default [`SOFTMAX_TEMPERATURE`]).
    Softmax,
}

impl ActionRule {
    /// The name `describe()` records in `engine.json`.
    pub fn as_str(self) -> &'static str {
        match self {
            ActionRule::Argmax => "argmax",
            ActionRule::Softmax => "softmax",
        }
    }
}

/// THE default acting switch: [`ActionRule::Argmax`] (default) or [`ActionRule::Softmax`].
pub const ACTION_RULE: ActionRule = ActionRule::Argmax;

/// THE default EXAM switch: [`ActionRule::Argmax`].  eli5: exploration belongs to the learning side.
pub const EVAL_ACTION_RULE: ActionRule = ActionRule::Argmax;

/// Temperature for [`ActionRule::Softmax`]: `π ∝ exp(values / T)`. `1.0` keeps the
/// net's own scale; smaller sharpens toward [`ActionRule::Argmax`], larger flattens.
pub const SOFTMAX_TEMPERATURE: f32 = 1.0;

/// Whether the REINFORCE loss is the batch's TURN MEAN instead of its SUM.  eli5: one update's gradient should not get 50× louder just because the episodes it happened to…
pub const LOSS_MEAN_OVER_TURNS: bool = true;

/// Salt for the acting generator, so the sampler's stream is independent of the
/// episode's `Env::reset` stream (both start from the same seed).
const ACTION_RULE_SEED_SALT: u64 = 0xA5A5_5A5A_C3C3_3C3C;

/// One action under `rule` at `temperature`: the greedy head, or a seeded softmax draw.
fn choose_action(
    rule: ActionRule,
    temperature: f32,
    values: &[f32],
    rng: &mut fastrand::Rng,
) -> usize {
    match rule {
        ActionRule::Argmax => greedy_action(values),
        ActionRule::Softmax => softmax_action(values, temperature, rng),
    }
}

/// Sample one action from `softmax(values / temperature)`: subtract the max (so the exponentials cannot overflow), draw uniformly in `[0, Σ)`, take the first bucket whose…
fn softmax_action(values: &[f32], temperature: f32, rng: &mut fastrand::Rng) -> usize {
    let t = if temperature.is_finite() && temperature > 0.0 {
        temperature
    } else {
        1.0
    };
    let max = values
        .iter()
        .copied()
        .filter(|v| !v.is_nan())
        .fold(f32::NEG_INFINITY, f32::max);
    let max = if max.is_finite() { max } else { 0.0 };
    let mass: Vec<f32> = values
        .iter()
        .map(|v| {
            if v.is_nan() {
                0.0
            } else {
                ((v - max) / t).exp()
            }
        })
        .collect();
    let total: f32 = mass.iter().sum();
    if !(total > 0.0) {
        return greedy_action(values);
    }
    let draw = rng.f32() * total;
    let mut acc = 0.0;
    for (i, w) in mass.iter().enumerate() {
        acc += w;
        if draw < acc {
            return i;
        }
    }
    // Float drift on the last bucket: the last action with any mass.
    mass.iter().rposition(|w| *w > 0.0).unwrap_or(0)
}

/// The factor the summed per-turn loss is multiplied by: `scale` alone (the turn SUM), or `scale / turns` (the turn MEAN) when `mean_over_turns` — see…
fn loss_scale(scale: f32, turns: usize, mean_over_turns: bool) -> f32 {
    if mean_over_turns {
        scale / turns.max(1) as f32
    } else {
        scale
    }
}

/// The mean of a slice; `0.0` for an empty one (no exam configured
/// configuration, not a division by zero).
fn mean(values: &[f32]) -> f32 {
    if values.is_empty() {
        0.0
    } else {
        values.iter().sum::<f32>() / values.len() as f32
    }
}

/// One played episode: its turns in order, and what each turn earned.
#[derive(Default)]
struct Episode {
    /// Per turn: the observation the action was chosen from, and the action taken.
    turns: Vec<(Vec<f32>, usize)>,
    /// Reward per turn, aligned with `turns`.
    rewards: Vec<f32>,
}

impl Episode {
    /// Turns played.
    fn len(&self) -> usize {
        self.turns.len()
    }

    /// Per-turn returns `G_t` under `signal`, in turn order.
    fn returns(&self, signal: Signal) -> Vec<f32> {
        let n = self.len();
        let mut out = vec![0.0f32; n];
        match signal {
            // eli5: each turn's return is the survival it has left.
            Signal::Turns => {
                for (t, g) in out.iter_mut().enumerate() {
                    *g = (n - t) as f32;
                }
            }
            // eli5: fold the rewards backwards, discounting one step per turn.
            Signal::Return { discount } => {
                let mut running = 0.0f32;
                for t in (0..n).rev() {
                    running = self.rewards[t] + discount * running;
                    out[t] = running;
                }
            }
        }
        out
    }

    /// The episode's own score — what the run ranks on: turns survived,
    /// episode's total reward.
    fn outcome(&self, signal: Signal) -> f32 {
        match signal {
            Signal::Turns => self.len() as f32,
            Signal::Return { .. } => self.rewards.iter().sum(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::trainer::env::toy::ToyEnv;
    use crate::utils::fitness::{Direction, Fitness};

    /// The loss is the batch's TURN MEAN, not its sum: a step's size stops depending on how long the world let the policy live, and the pre-2026-11-10 sum is still reachable…
    #[test]
    fn loss_is_the_turn_mean_not_the_sum() {
        let scale = 2.0;
        assert_eq!(loss_scale(scale, 1, true), scale);
        // 500 turns carry 1/500 each under the mean — the same as one turn does.
        assert_eq!(loss_scale(scale, 500, true), scale / 500.0);
        // The sum mode is unchanged: the factor was, and still is, the advantage normalizer.
        assert_eq!(loss_scale(scale, 500, false), scale);
        // An empty batch reads one turn rather than dividing by zero.
        assert_eq!(loss_scale(scale, 0, true), scale);
    }

    /// A tiny net with the shape a `ToyEnv` needs: 2 observations in, `output_dim` action values
    /// out.
    fn tiny_net(output_dim: usize, dropout_prob: f32) -> Network {
        use crate::graph::node::Node;
        use crate::graph::topology::{Connection, Port, Topology, TopologyOptions};
        let mut topo = Topology::new(
            3,
            Some(TopologyOptions {
                input_dim: Some(2),
                output_dim: Some(output_dim),
                dropout_prob,
                ..Default::default()
            }),
        );
        topo.nodes.push(Node::new_input(0, 2));
        topo.nodes.push(Node::new_hidden(1, 1, 1));
        topo.nodes.push(Node::new_output(2, 1, 1));
        topo.connections.push(Connection {
            from: Port { node: 0, index: 0 },
            to: Port { node: 1, index: 0 },
        });
        topo.connections.push(Connection {
            from: Port { node: 1, index: 0 },
            to: Port { node: 2, index: 0 },
        });
        topo.finalize();
        Network::build(&topo, Device::CPU).unwrap()
    }

    /// A context for calling `train_step` directly.
    fn ctx<'a>(fitness: &'a Fitness, net_seed: u64, run_seed: u64, step: usize) -> RlContext<'a> {
        RlContext {
            fitness,
            metrics: &[],
            env: crate::trainer::StepEnv {
                step,
                run_seed,
                pop_size: 1,
                live_count: 1,
                checkpoint_every: 0,
                smoothing_window: 1,
                max_steps: Some(10),
                attempt: 0,
            },
            net_hash: "test-net",
            net_seed,
        }
    }

    /// A world with a FIXED shape and a reward ladder: every episode is exactly `max_turns` turns,
    /// turn `r` pays `r + 1`, and nothing ends an episode early.
    struct LadderEnv {
        max_turns: usize,
        turns: usize,
        seed: u64,
    }

    impl LadderEnv {
        fn new(max_turns: usize) -> Self {
            Self {
                max_turns,
                turns: 0,
                seed: 0,
            }
        }
    }

    impl Env for LadderEnv {
        fn reset(&mut self, seed: u64) -> Result<Vec<f32>> {
            self.seed = seed;
            self.turns = 0;
            Ok(vec![0.5, -0.5])
        }

        fn step(&mut self, _action: usize) -> Result<(Vec<f32>, f32, bool)> {
            self.turns += 1;
            let reward = self.turns as f32;
            Ok((vec![reward, 0.0], reward, self.turns >= self.max_turns))
        }

        fn action_count(&self) -> usize {
            2
        }

        fn max_turns(&self) -> usize {
            self.max_turns
        }

        fn describe(&self) -> serde_json::Value {
            serde_json::json!({ "env": "ladder", "max_turns": self.max_turns })
        }
    }

    /// `RlStep` requires `Send`, so an environment that is not `Send` cannot be
    /// trained by this type
    #[test]
    fn reinforce_is_an_rl_step() {
        fn assert_rl_step<T: RlStep>() {}
        assert_rl_step::<Reinforce<ToyEnv>>();
    }

    /// The seed derivation is pure — same inputs, same seed — and separates every axis it is given.
    #[test]
    fn episode_seeds_are_pure_and_domain_separated() {
        assert_eq!(
            episode_start_seed(11, 3, 2),
            episode_start_seed(11, 3, 2),
            "pure: same inputs, same seed"
        );
        let base = episode_start_seed(11, 3, 2);
        assert_ne!(
            base,
            episode_start_seed(12, 3, 2),
            "a different net is a different run"
        );
        assert_ne!(
            base,
            episode_start_seed(11, 4, 2),
            "a different clock is a different run"
        );
        assert_ne!(
            base,
            episode_start_seed(11, 3, 3),
            "a different match is a different run"
        );
        assert_ne!(
            episode_start_seed(11, 3, 2),
            episode_start_seed(11, 2, 3),
            "step and match must not be interchangeable"
        );

        // Golden values (the derivation cartpole has been training
        assert_eq!(episode_start_seed(42, 0, 0), 42);
        assert_eq!(episode_start_seed(0, 1, 0), 0x9E37_79B9_7F4A_7C15);
    }

    /// The exam base is blind to `net_seed` (which is why it takes none) and off
    /// the train draw.
    #[test]
    fn the_exam_base_is_shared_and_off_the_train_draw() {
        assert_ne!(
            eval_seed_base(42),
            42,
            "the exam must not reuse the train base"
        );
        assert_eq!(eval_seed_base(42), 1042, "a plain offset: golden value");
        // Both nets get the same exam seeds, whatever their own seeds
        for net_seed in [1u64, 99] {
            assert_eq!(
                episode_start_seed(eval_seed_base(7), 2, 1),
                episode_start_seed(eval_seed_base(7), 2, 1),
                "net {net_seed} sits its own copy of the same exam"
            );
        }
    }

    /// The greedy head: argmax, ties to the lowest index, NaN never preferred,
    /// single-value and empty slices safe.
    #[test]
    fn greedy_action_is_argmax_with_ties_to_the_lowest_index() {
        assert_eq!(greedy_action(&[0.1, 0.9]), 1);
        assert_eq!(greedy_action(&[0.9, 0.1]), 0);
        assert_eq!(greedy_action(&[1.0, 1.0]), 0, "ties go to the lowest index");
        assert_eq!(greedy_action(&[0.0, f32::NAN]), 0);
        assert_eq!(greedy_action(&[f32::NAN, 0.0]), 1);
        assert_eq!(greedy_action(&[f32::NAN, f32::NAN]), 0);
        assert_eq!(greedy_action(&[f32::INFINITY, f32::NEG_INFINITY]), 0);
        assert_eq!(greedy_action(&[3.0]), 0);
        assert_eq!(greedy_action(&[]), 0);
    }

    /// Softmax sampling is a pure function of the seed — same seed, same moves — and
    /// it can leave the argmax (otherwise it is a slower argmax).
    #[test]
    fn softmax_sampling_replays_from_its_seed() {
        let values = [0.0, 0.0, 0.0];
        let draw = |seed: u64| {
            let mut rng = fastrand::Rng::with_seed(seed);
            (0..64)
                .map(|_| softmax_action(&values, 1.0, &mut rng))
                .collect::<Vec<_>>()
        };
        assert_eq!(draw(7), draw(7), "the same seed replays the same moves");
        assert_ne!(draw(7), draw(8), "a different seed is a different draw");
        let moves = draw(7);
        assert!(
            moves.iter().any(|&a| a != moves[0]),
            "a flat policy must explore: {moves:?}"
        );
    }

    /// The switch: `Argmax` plays the preference and ignores the draw, `Softmax`
    /// follows it, NaN never wins, and a degenerate temperature is not a divide by zero.
    #[test]
    fn the_acting_rule_selects_argmax_or_softmax() {
        let sharp = [0.0, 40.0, 0.0];
        for seed in 0..32u64 {
            let mut rng = fastrand::Rng::with_seed(seed);
            assert_eq!(softmax_action(&sharp, 1.0, &mut rng), 1, "seed {seed}");
            let mut rng = fastrand::Rng::with_seed(seed);
            assert_eq!(choose_action(ActionRule::Argmax, 1.0, &sharp, &mut rng), 1);
        }
        let mut rng = fastrand::Rng::with_seed(3);
        assert_eq!(softmax_action(&[f32::NAN, 1.0], 1.0, &mut rng), 1);
        // Every value NaN: no mass anywhere, so the greedy fallback decides.
        let mut rng = fastrand::Rng::with_seed(3);
        assert_eq!(softmax_action(&[f32::NAN, f32::NAN], 1.0, &mut rng), 0);
        // A non-positive temperature is the plain softmax, never an inverted or infinite one.
        let mut rng = fastrand::Rng::with_seed(5);
        assert_eq!(softmax_action(&sharp, 0.0, &mut rng), 1);
        // The shipped default: the exam is measured on the net's OWN policy.
        assert_eq!(ACTION_RULE, ActionRule::Argmax);
        assert_eq!(ACTION_RULE.as_str(), "argmax");
        assert_eq!(ActionRule::Softmax.as_str(), "softmax");
    }

    /// An environment whose episode LENGTH depends on the action taken — action 1 survives both turns, action 0 dies at the first.
    struct PickyEnv {
        turns: usize,
    }

    impl Env for PickyEnv {
        fn reset(&mut self, _seed: u64) -> Result<Vec<f32>> {
            self.turns = 0;
            Ok(vec![0.5, -0.5])
        }

        fn step(&mut self, action: usize) -> Result<(Vec<f32>, f32, bool)> {
            self.turns += 1;
            let dead = action == 0;
            Ok((vec![0.0, 0.0], 1.0, dead || self.turns >= 2))
        }

        fn action_count(&self) -> usize {
            2
        }

        fn max_turns(&self) -> usize {
            2
        }

        fn describe(&self) -> serde_json::Value {
            serde_json::json!({ "env": "picky", "max_turns": 2 })
        }
    }

    /// THE PHASE SPLIT: `action_rule` governs the TRAIN episodes, `eval_action_rule` the exam.
    #[test]
    fn the_exam_plays_under_its_own_rule_not_the_training_one() {
        assert_eq!(EVAL_ACTION_RULE, ActionRule::Argmax);
        let fitness = Fitness::reported(Direction::Maximize, "turns");
        let read = |train: ActionRule, eval: ActionRule| {
            let mut trainer = Reinforce::new(PickyEnv { turns: 0 }, Device::CPU)
                .with_matches_per_step(0)
                .with_eval_matches_per_step(8)
                // One temperature for both arms: `1e6` makes either sampler near-uniform, so the
                // split is measured by WHICH arm samples, not by how sharply.
                .with_action_rule(train, 1e6)
                .with_eval_action_rule(eval);
            assert_eq!(trainer.eval_action_rule(), eval);
            let mut net = tiny_net(2, 0.0);
            let mut optimizer = trainer.make_optimizer(&net);
            trainer
                .train_step(&mut net, &mut *optimizer, 1, &ctx(&fitness, 42, 7, 1))
                .unwrap()
                .fitness
        };
        let greedy = read(ActionRule::Softmax, ActionRule::Argmax);
        assert_eq!(
            greedy,
            read(ActionRule::Argmax, ActionRule::Argmax),
            "the training rule cannot move the exam"
        );
        assert_ne!(
            greedy,
            read(ActionRule::Argmax, ActionRule::Softmax),
            "a sampled exam at a flat temperature grades a different policy"
        );
    }

    /// The blob records the acting rule ONLY when it is not the reference recipe — the same convention the named schedule and the optimizer follow, so every run recorded before…
    #[test]
    fn describe_omits_the_acting_rule_while_it_is_the_default() {
        let trainer = Reinforce::new(ToyEnv::new(2, 5), Device::CPU);
        let blob = trainer.describe().expect("reinforce records a blob");
        assert_eq!(blob["trainer"], serde_json::json!("reinforce"));
        assert!(
            blob.get("action_rule").is_none(),
            "the reference recipe adds no key, so old runs still resume: {blob}"
        );
        assert!(
            blob.get("eval_action_rule").is_none(),
            "and neither does the default exam: {blob}"
        );
        let sampled = trainer.with_eval_action_rule(ActionRule::Softmax);
        let blob = sampled.describe().expect("reinforce records a blob");
        assert_eq!(blob["eval_action_rule"], serde_json::json!("softmax"));
        assert_eq!(
            blob["action_rule"],
            serde_json::Value::Null,
            "the TRAIN arm stays the reference recipe"
        );
    }

    /// The two signals, on one hand-built episode: `Turns` credits survival,
    /// `Return` credits discounted reward, and the outcome matches its name.
    #[test]
    fn returns_follow_the_signal() {
        let episode = Episode {
            turns: vec![(vec![0.0; 2], 0), (vec![0.0; 2], 1), (vec![0.0; 2], 0)],
            rewards: vec![1.0, 2.0, 3.0],
        };
        // Survival: turns remaining, so the last turn is worth exactly 1.
        assert_eq!(episode.returns(Signal::Turns), vec![3.0, 2.0, 1.0]);
        assert_eq!(episode.outcome(Signal::Turns), 3.0);

        // Undiscounted return = suffix sums.
        let undiscounted = Signal::Return { discount: 1.0 };
        assert_eq!(episode.returns(undiscounted), vec![6.0, 5.0, 3.0]);
        assert_eq!(
            episode.outcome(undiscounted),
            6.0,
            "the outcome is the episode total"
        );

        // γ = 0.5: each step further out is worth half as much.
        let discounted = Signal::Return { discount: 0.5 };
        assert_eq!(episode.returns(discounted), vec![2.75, 3.5, 3.0]);
        assert_eq!(
            episode.outcome(discounted),
            6.0,
            "the discount shapes credit, not the total"
        );

        // An empty episode has no returns and no outcome to report.
        let empty = Episode::default();
        assert!(empty.returns(Signal::Turns).is_empty());
        assert_eq!(empty.outcome(Signal::Turns), 0.0);
        assert_eq!(empty.outcome(Signal::Return { discount: 0.9 }), 0.0);
    }

    /// The trainer hands the world the seeds its own derivation names: the TRAIN
    /// seed rides `net_seed ^ run_seed`, so two nets do not replay one world.
    #[test]
    fn a_step_seeds_train_episodes_per_net() {
        let fitness = Fitness::reported(Direction::Maximize, "turns");
        // No exam, so the world's last seed is the last TRAIN seed.
        let step = |net_seed: u64| {
            let mut trainer =
                Reinforce::new(ToyEnv::new(2, 5), Device::CPU).with_eval_matches_per_step(0);
            let mut net = tiny_net(2, 0.0);
            let mut optimizer = trainer.make_optimizer(&net);
            trainer
                .train_step(&mut net, &mut *optimizer, 3, &ctx(&fitness, net_seed, 7, 3))
                .unwrap();
            trainer.env().last_seed()
        };
        assert_eq!(step(100), episode_start_seed(100 ^ 7, 3, 0));
        assert_ne!(
            step(100),
            step(101),
            "a different net explores a different world"
        );
        assert_eq!(
            step(100),
            episode_start_seed(100 ^ 7, 3, 0),
            "and the seed is a pure function of the recorded inputs"
        );
    }

    /// ...and the EVAL seeds do NOT: every net sits the same exam, whatever its own seed.
    #[test]
    fn the_exam_seeds_are_shared_across_nets() {
        let fitness = Fitness::reported(Direction::Maximize, "turns");
        let last_exam_seed = |net_seed: u64, step: usize| {
            let mut trainer =
                Reinforce::new(ToyEnv::new(2, 5), Device::CPU).with_eval_matches_per_step(2);
            let mut net = tiny_net(2, 0.0);
            let mut optimizer = trainer.make_optimizer(&net);
            trainer
                .train_step(
                    &mut net,
                    &mut *optimizer,
                    step,
                    &ctx(&fitness, net_seed, 7, step),
                )
                .unwrap();
            trainer.env().last_seed()
        };
        // The exam runs last, so the world's last seed is the last EVAL seed.
        assert_eq!(
            last_exam_seed(100, 3),
            episode_start_seed(eval_seed_base(7), 3, 1)
        );
        assert_eq!(
            last_exam_seed(100, 3),
            last_exam_seed(999, 3),
            "the exam is the same exam for every net"
        );
        assert_ne!(
            last_exam_seed(100, 3),
            last_exam_seed(100, 4),
            "a fresh clock draws fresh games — the default per-clock exam"
        );
    }

    /// Every match inside ONE clock draws its own game — TRAIN and EVAL alike.
    #[test]
    fn every_match_inside_one_clock_draws_its_own_game() {
        let step = 3usize;
        for (kind, base) in [("train", 100 ^ 7), ("eval", eval_seed_base(7))] {
            let seeds: Vec<u64> = (0..5).map(|i| episode_start_seed(base, step, i)).collect();
            let unique: std::collections::HashSet<u64> = seeds.iter().copied().collect();
            assert_eq!(
                unique.len(),
                5,
                "{kind}: five matches, five games: {seeds:?}"
            );
        }
        // ...and the trainer hands `match_i` over, it does not loop one seed: with the exam
        // off, the world's last seed is the LAST train game, index `matches_per_step - 1`.
        let fitness = Fitness::reported(Direction::Maximize, "turns");
        let mut trainer = Reinforce::new(ToyEnv::new(2, 5), Device::CPU)
            .with_matches_per_step(3)
            .with_eval_matches_per_step(0);
        let mut net = tiny_net(2, 0.0);
        let mut optimizer = trainer.make_optimizer(&net);
        trainer
            .train_step(
                &mut net,
                &mut *optimizer,
                step,
                &ctx(&fitness, 100, 7, step),
            )
            .unwrap();
        assert_eq!(
            trainer.env().last_seed(),
            episode_start_seed(100 ^ 7, step, 2),
            "the third train match of the clock played its own seed"
        );
    }

    /// The DEFAULT exam is per-clock: even with a tick cadence recorded, two clocks draw different games (and every net sits the same ones) — so a reading that does not move…
    #[test]
    fn the_default_exam_draws_fresh_games_every_clock() {
        let fitness = Fitness::reported(Direction::Maximize, "turns");
        let last_exam_seed = |net_seed: u64, step: usize| {
            let mut trainer =
                Reinforce::new(ToyEnv::new(2, 5), Device::CPU).with_eval_matches_per_step(1);
            let mut net = tiny_net(2, 0.0);
            let mut optimizer = trainer.make_optimizer(&net);
            let mut c = ctx(&fitness, net_seed, 7, step);
            // Every real run records a cadence; the default exam must ignore it.
            c.env.checkpoint_every = 4;
            trainer
                .train_step(&mut net, &mut *optimizer, step, &c)
                .unwrap();
            trainer.env().last_seed()
        };
        assert_eq!(
            last_exam_seed(100, 5),
            episode_start_seed(eval_seed_base(7), 5, 0),
            "the exam's step axis is the CLOCK"
        );
        assert_ne!(
            last_exam_seed(100, 5),
            last_exam_seed(100, 7),
            "two clocks inside one era are two exams"
        );
        assert_eq!(
            last_exam_seed(100, 5),
            last_exam_seed(999, 5),
            "and it is still one exam for every net"
        );
    }

    /// The era exam is OPT-IN ([`Reinforce::with_per_clock_exam`] `false`): clocks inside one era sit the identical games, so a net born mid-era is ranked on what its parents…
    #[test]
    fn the_era_exam_is_stable_within_an_era_and_rotates_between_them() {
        assert_eq!(eval_era_of(0, 20), 0);
        assert_eq!(eval_era_of(19, 20), 0, "the era's last clock");
        assert_eq!(eval_era_of(20, 20), 1, "the next era's first clock");
        assert_eq!(eval_era_of(141, 20), 7);
        assert_eq!(eval_era_of(7, 0), 7, "no tick ⇒ the per-clock exam");
        assert_eq!(eval_era_of(7, 1), 7, "an era of one clock ⇒ per-clock too");

        // Through a real step: two clocks inside one era must sit the same last
        // game, and a clock in the next era must
        let fitness = Fitness::reported(Direction::Maximize, "turns");
        let last_exam_seed = |step: usize| {
            let mut trainer = Reinforce::new(ToyEnv::new(2, 5), Device::CPU)
                .with_eval_matches_per_step(1)
                .with_per_clock_exam(false);
            let mut net = tiny_net(2, 0.0);
            let mut optimizer = trainer.make_optimizer(&net);
            let mut c = ctx(&fitness, 7, 7, step);
            c.env.checkpoint_every = 4;
            trainer
                .train_step(&mut net, &mut *optimizer, step, &c)
                .unwrap();
            trainer.env().last_seed()
        };
        assert_eq!(last_exam_seed(5), last_exam_seed(7), "one era, one exam");
        assert_ne!(
            last_exam_seed(5),
            last_exam_seed(9),
            "a new era is a new exam"
        );
        assert_eq!(
            last_exam_seed(5),
            episode_start_seed(eval_seed_base(7), eval_era_of(5, 4), 0),
            "the exam seed is a pure function of (base, era, match)"
        );
    }

    /// A full step against a real net: exact volume, a real update, and the same inputs reporting
    /// the same numbers (the trainer holds no state between steps).
    #[test]
    fn a_step_reports_exact_volume_and_is_a_pure_function_of_its_inputs() {
        let fitness = Fitness::reported(Direction::Maximize, "turns");
        let step = || {
            let mut trainer = Reinforce::new(LadderEnv::new(4), Device::CPU);
            let mut net = tiny_net(2, 0.0);
            let mut optimizer = trainer.make_optimizer(&net);
            let before = net.export_weights().unwrap();
            let report = trainer
                .train_step(&mut net, &mut *optimizer, 2, &ctx(&fitness, 42, 7, 2))
                .unwrap();
            (report, before, net.export_weights().unwrap())
        };

        let (report, before, after) = step();
        assert_eq!(report.fitness, 4.0, "every exam episode is exactly 4 turns");
        let rl = report
            .rl
            .expect("an RL step reports its environment volume");
        assert_eq!(rl.matches, 6, "1 train + 5 eval episodes by default");
        assert_eq!(rl.train_turns, 4, "one train episode, capped at max_turns");
        assert_eq!(rl.eval_turns, 20, "five exam episodes, capped at max_turns");
        assert_eq!(rl.turns(), 24);
        assert!(
            report.train_loss.is_finite(),
            "a real update reports a finite loss"
        );
        assert_ne!(
            before, after,
            "the update moved the weights, so the step is not a no-op"
        );

        // Bit-identical, not merely close: nothing here is a function of wall time
        // or of state carried between steps.
        let (again, _, _) = step();
        assert_eq!(report.train_loss, again.train_loss);
        assert_eq!(report.fitness, again.fitness);
        assert_eq!(report.rl, again.rl);
    }

    /// The memory channel is a pure function of the observation history: the FIRST turn cannot show
    /// a spike (delta 0, EMA = the observation), the fed row doubles, and two states fed the same
    #[test]
    fn obs_memory_rows_are_pure_and_cold_start_free() {
        let a = vec![1.0f32, 2.0];
        let b = vec![3.0f32, 4.0];

        let mut none = MemoryState::new(ObsMemory::None, &a);
        assert_eq!(none.row(&a), a, "no channel: the row IS the observation");
        assert_eq!(ObsMemory::None.width_factor(), 1);

        let mut delta = MemoryState::new(ObsMemory::Delta, &a);
        assert_eq!(
            delta.row(&a),
            vec![1.0, 2.0, 0.0, 0.0],
            "turn 0 has no past to subtract"
        );
        assert_eq!(
            delta.row(&b),
            vec![3.0, 4.0, 2.0, 2.0],
            "then the discrete derivative"
        );
        assert_eq!(ObsMemory::Delta.width_factor(), 2);

        let mut ema = MemoryState::new(ObsMemory::Ema { beta: 0.5 }, &a);
        assert_eq!(
            ema.row(&a),
            vec![1.0, 2.0, 1.0, 2.0],
            "seeded AT the first observation, so no spike"
        );
        assert_eq!(
            ema.row(&b),
            vec![3.0, 4.0, 2.0, 3.0],
            "ema = 0.5·prev + 0.5·obs"
        );
        assert_eq!(ObsMemory::Ema { beta: 0.5 }.width_factor(), 2);

        // Replay: the same memory fed the same episode yields the same rows.
        let mut again = MemoryState::new(ObsMemory::Ema { beta: 0.5 }, &a);
        assert_eq!(again.row(&a), vec![1.0, 2.0, 1.0, 2.0]);
        assert_eq!(again.row(&b), vec![3.0, 4.0, 2.0, 3.0]);
    }

    /// The signal decides both the objective and the unit the fitness is measured
    /// in: `Turns` counts turns (and ignores the reward), `Return` sums
    #[test]
    fn the_signal_choice_changes_the_objective_and_the_unit() {
        let fitness = Fitness::reported(Direction::Maximize, "score");
        let run = |signal: Signal| {
            let mut trainer = Reinforce::new(LadderEnv::new(4), Device::CPU).with_signal(signal);
            let mut net = tiny_net(2, 0.0);
            let mut optimizer = trainer.make_optimizer(&net);
            trainer
                .train_step(&mut net, &mut *optimizer, 0, &ctx(&fitness, 42, 7, 0))
                .unwrap()
        };
        let turns = run(Signal::Turns);
        let ret = run(Signal::Return { discount: 1.0 });

        assert_eq!(turns.fitness, 4.0, "turns survived");
        assert_eq!(ret.fitness, 10.0, "1 + 2 + 3 + 4 of reward");
        // The returns differ (linear survival credit vs suffix sums), so the two
        // steps optimize different objectives — not merely measure different things.
        assert!(turns.train_loss.is_finite() && ret.train_loss.is_finite());
        assert_ne!(
            turns.train_loss, ret.train_loss,
            "the signal changes the objective"
        );
    }

    /// The recorded blob names the world, the caps, the signal and every knob — and a changed knob
    /// changes the blob, which is what makes resume's diff something real rather than decoration.
    #[test]
    fn describe_records_the_world_the_caps_and_the_knobs() {
        let trainer = Reinforce::new(ToyEnv::new(3, 12), Device::CPU);
        let blob = trainer.describe().unwrap();
        assert_eq!(blob["trainer"], "reinforce");
        assert_eq!(blob["env"]["env"], "toy", "the world describes itself");
        assert_eq!(blob["actions"], 3);
        assert_eq!(blob["max_turns"], 12);
        assert_eq!(blob["signal"]["kind"], "turns");
        assert_eq!(blob["challenge_policy"], "least_action");
        assert_eq!(blob["challenge_decay"], "custom:0.5");
        assert_eq!(blob["matches_per_step"], 1);
        assert_eq!(blob["eval_matches_per_step"], 5);
        assert_eq!(blob["exam"], "per_clock");

        let changed = trainer
            .with_signal(Signal::Return { discount: 0.5 })
            .with_matches_per_step(3)
            .with_per_clock_exam(false)
            .with_learning_rate(2e-3)
            .with_challenge(0.0, ChallengePolicy::Random, ChallengeDecay::Linear)
            .describe()
            .unwrap();
        assert_ne!(
            blob, changed,
            "a changed knob must change the recorded blob"
        );
        assert_eq!(changed["signal"]["kind"], "return");
        // 0.5, not 0.9: an f32 in JSON is a wide decimal (0.9 is not exact),
        // the exact-value assertion uses a discount that round-trips.
        assert_eq!(changed["signal"]["discount"], 0.5);
        assert_eq!(changed["challenge_policy"], "random");
        assert_eq!(changed["challenge_decay"], "linear");
        assert_eq!(changed["exam"], "era", "the axis is recorded by name");
    }
}