use std::collections::HashMap;
use std::path::Path;
use flodl::tensor::Result;
use serde::{Deserialize, Serialize};
use crate::engine::config::{RaceConfig, SMOOTHING_WINDOW};
use crate::engine::fitness::{Direction, FitnessLabel, Metric};
use crate::graph::topology::{Topology, TopologyOptions};
use crate::utils::error::EngineError;
use crate::utils::seed::topo_hash;
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct ConfigSnapshot {
pub pop_size: usize,
pub checkpoint_every: usize,
pub crossover_rolls: usize,
pub mutate_rolls: usize,
pub crossover_gating: String,
pub crossover_retries: usize,
pub crossover_cull_policy: String,
pub elite_count: usize,
pub crossover_ops_pool: Vec<String>,
pub crossover_prob: f32,
pub mutate_prob: f32,
pub max_target_fitness: Option<f32>,
pub has_custom_stop: bool,
pub log_level: String,
pub mode: String,
pub batch_size: usize,
pub eval_batch_size: usize,
pub smoothing_window: usize,
pub device: String,
pub csv_export: bool,
#[serde(default)]
pub pop_pruner: Option<(String, usize)>,
}
impl ConfigSnapshot {
pub fn from_config(cfg: &RaceConfig, batch_size: usize, eval_batch_size: usize) -> Self {
ConfigSnapshot {
pop_size: cfg.pop_size,
checkpoint_every: cfg.checkpoint_every,
crossover_rolls: cfg.crossover_rolls,
mutate_rolls: cfg.mutate_rolls,
crossover_gating: format!("{:?}", cfg.crossover_gating).to_lowercase(),
crossover_retries: cfg.crossover_retries,
crossover_cull_policy: format!("{:?}", cfg.crossover_cull_policy).to_lowercase(),
elite_count: cfg.elite_count,
crossover_ops_pool: cfg.crossover_ops_pool.clone(),
crossover_prob: cfg.crossover_prob,
mutate_prob: cfg.mutate_prob,
max_target_fitness: cfg.max_target_fitness,
has_custom_stop: cfg.custom_stop.is_some(),
log_level: format!("{:?}", cfg.log_level).to_lowercase(),
mode: format!("{:?}", cfg.mode).to_lowercase(),
batch_size,
eval_batch_size,
smoothing_window: SMOOTHING_WINDOW,
device: if cfg!(feature = "cuda") { "cuda:0" } else { "cpu" }.to_string(),
csv_export: cfg.csv_export,
pop_pruner: cfg.pop_pruner.map(|p| (format!("{:?}", p.method).to_lowercase(), p.steps)),
}
}
}
#[derive(Clone, Debug, Serialize)]
pub struct RunHeader {
pub run_id: String,
pub run_seed: u64,
pub fitness_label: FitnessLabel,
pub fitness_direction: Direction,
pub input_dim: usize,
pub output_dim: usize,
pub topology_options: TopologyOptions,
pub hidden_dim_pool: String,
pub hidden_dim_stride: usize,
pub combine_op_pool: Vec<String>,
pub activation_pool: Vec<String>,
pub standardize_op_pool: Vec<String>,
pub informative_metrics: Vec<String>,
pub max_steps: Option<usize>,
pub started_at: Option<String>,
pub train_eval_split_ratio: Option<f32>,
pub held_out_eval_rows: Option<usize>,
#[serde(default)]
pub config: ConfigSnapshot,
#[serde(default)]
pub trainer: Option<serde_json::Value>,
}
#[derive(Debug)]
pub struct RunConfig {
pub run_id: String,
pub run_seed: u64,
pub fitness_label: FitnessLabel,
pub fitness_direction: Direction,
pub input_dim: usize,
pub output_dim: usize,
pub topology_options: TopologyOptions,
pub hidden_dim_pool: std::ops::RangeInclusive<usize>,
pub hidden_dim_stride: usize,
pub combine_op_pool: Vec<String>,
pub activation_pool: Vec<String>,
pub standardize_op_pool: Vec<String>,
pub informative_metrics: Vec<Metric>,
pub max_steps: Option<usize>,
pub train_eval_split_ratio: Option<f32>,
pub held_out_eval_rows: Option<usize>,
pub config: ConfigSnapshot,
pub trainer: Option<serde_json::Value>,
}
impl RunHeader {
pub fn from_race_options(cfg: RunConfig) -> Self {
let RunConfig {
run_id,
run_seed,
fitness_label,
fitness_direction,
input_dim,
output_dim,
topology_options,
hidden_dim_pool,
hidden_dim_stride,
combine_op_pool,
activation_pool,
standardize_op_pool,
informative_metrics,
max_steps,
train_eval_split_ratio,
held_out_eval_rows,
config,
trainer,
} = cfg;
RunHeader {
run_id,
run_seed,
fitness_label,
fitness_direction,
input_dim,
output_dim,
topology_options,
hidden_dim_pool: format!("{}..={}", hidden_dim_pool.start(), hidden_dim_pool.end()),
hidden_dim_stride,
combine_op_pool,
activation_pool,
standardize_op_pool,
informative_metrics: informative_metrics
.into_iter()
.map(|m| m.label().to_string())
.collect(),
max_steps,
started_at: None,
train_eval_split_ratio,
held_out_eval_rows,
config,
trainer,
}
}
pub fn from_race_options_at(cfg: RunConfig, started_at: String) -> Self {
let mut out = Self::from_race_options(cfg);
out.started_at = Some(started_at);
out
}
pub fn to_json(&self) -> Result<String> {
Ok(serde_json::to_string_pretty(self)
.map_err(|e| EngineError::Json(format!("engine.json serialize: {e}")))?)
}
pub fn from_json(raw: &str) -> Result<Self> {
let v: serde_json::Value = serde_json::from_str(raw)
.map_err(|e| EngineError::Json(format!("engine.json parse: {e}")))?;
let fitness_direction = v
.get("fitness_direction")
.and_then(|f| f.as_str())
.and_then(|s| match s {
"Minimize" => Some(Direction::Minimize),
"Maximize" => Some(Direction::Maximize),
_ => None,
})
.unwrap_or(Direction::Maximize);
let fitness_label = serde_json::from_value(
v.get("fitness_label")
.cloned()
.unwrap_or_else(|| serde_json::Value::String("loss".into())),
)
.unwrap_or(FitnessLabel("loss".into()));
let input_dim = v.get("input_dim").and_then(|f| f.as_u64()).unwrap_or(0) as usize;
let output_dim = v.get("output_dim").and_then(|f| f.as_u64()).unwrap_or(0) as usize;
let topology_options = v
.get("topology_options")
.map(|t| serde_json::from_value(t.clone()).unwrap_or_default())
.unwrap_or_default();
let hidden_dim_pool = v
.get("hidden_dim_pool")
.and_then(|f| f.as_str())
.map(|s| s.to_string())
.unwrap_or_else(|| "4..=8".into());
let hidden_dim_stride: usize = v
.get("hidden_dim_stride")
.and_then(|f| f.as_u64())
.map(|n| n as usize)
.unwrap_or(1);
let combine_op_pool: Vec<String> = serde_json::from_value(
v.get("combine_op_pool")
.cloned()
.unwrap_or(serde_json::Value::Null),
)
.unwrap_or_default();
let activation_pool: Vec<String> = serde_json::from_value(
v.get("activation_pool")
.cloned()
.unwrap_or(serde_json::Value::Null),
)
.unwrap_or_default();
let standardize_op_pool: Vec<String> = serde_json::from_value(
v.get("standardize_op_pool")
.cloned()
.unwrap_or(serde_json::Value::Null),
)
.unwrap_or_default();
let informative_metrics: Vec<String> = serde_json::from_value(
v.get("informative_metrics")
.cloned()
.unwrap_or(serde_json::Value::Null),
)
.unwrap_or_default();
let max_steps = v
.get("max_steps")
.and_then(|f| f.as_u64())
.map(|n| n as usize);
let started_at = v
.get("started_at")
.and_then(|f| f.as_str())
.map(|s| s.to_string());
let train_eval_split_ratio = v
.get("train_eval_split_ratio")
.and_then(|f| f.as_f64())
.map(|n| n as f32);
let held_out_eval_rows = v
.get("held_out_eval_rows")
.and_then(|f| f.as_u64())
.map(|n| n as usize);
let config: ConfigSnapshot = v
.get("config")
.cloned()
.and_then(|c| serde_json::from_value(c).ok())
.unwrap_or_default();
let trainer = v.get("trainer").cloned();
Ok(RunHeader {
run_id: v
.get("run_id")
.and_then(|f| f.as_str())
.unwrap_or("unknown")
.to_string(),
run_seed: v.get("run_seed").and_then(|f| f.as_u64()).unwrap_or(0),
fitness_label,
fitness_direction,
input_dim,
output_dim,
topology_options,
hidden_dim_pool,
hidden_dim_stride,
combine_op_pool,
activation_pool,
standardize_op_pool,
informative_metrics,
max_steps,
started_at,
train_eval_split_ratio,
held_out_eval_rows,
config,
trainer,
})
}
}
fn default_alive() -> bool {
true
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct NetState {
pub hash: String,
pub topology: String,
pub net_seed: usize,
pub step: usize,
#[serde(default = "default_alive")]
pub is_alive: bool,
#[serde(default)]
pub culled_at_step: Option<usize>,
#[serde(default)]
pub cull_reason: Option<String>,
#[serde(default)]
pub final_smoothed_fitness: Option<f32>,
pub entered_at_step: usize,
pub created_from: Option<String>,
pub last_metrics: Option<NetMetrics>,
#[serde(default)]
pub meta: NetMeta,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
pub struct NetMeta {
#[serde(default)]
pub params: Option<i64>,
#[serde(default)]
pub param_tensors: Option<usize>,
#[serde(default)]
pub input_dim: Option<usize>,
#[serde(default)]
pub output_dim: Option<usize>,
#[serde(default)]
pub batch_size: Option<usize>,
#[serde(default)]
pub learning_rate: Option<f32>,
#[serde(default)]
pub grad_clip: Option<f32>,
#[serde(default)]
pub dropout_prob: Option<f32>,
#[serde(default)]
pub fitness_label: Option<String>,
#[serde(default)]
pub loss_label: Option<String>,
#[serde(default)]
pub direction: Option<String>,
#[serde(default)]
pub born_at_step: Option<usize>,
#[serde(default)]
pub pop_size: Option<usize>,
#[serde(default)]
pub run_seed: Option<u64>,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct NetMetrics {
pub step: usize,
pub train_loss: f32,
pub eval_loss: Option<f32>,
pub fitness: f32,
pub informative: Vec<f32>,
}
impl NetState {
pub fn stamp_meta(
&mut self,
net: &crate::graph::network::Network,
run: &crate::engine::config::RunMetaCtx,
) {
use flodl::Module;
let params = net.parameters();
self.meta.param_tensors = Some(params.len());
self.meta.params = Some(params.iter().map(|p| p.variable.numel()).sum());
self.meta.input_dim = Some(run.input_dim);
self.meta.output_dim = Some(run.output_dim);
self.meta.batch_size = Some(run.batch_size);
self.meta.fitness_label = Some(run.fitness_label.clone());
self.meta.loss_label = Some(run.loss_label.clone());
self.meta.direction = Some(run.direction.clone());
self.meta.born_at_step = Some(self.entered_at_step);
self.meta.pop_size = Some(run.pop_size);
self.meta.run_seed = Some(run.run_seed);
self.meta.dropout_prob = Some(run.dropout_prob);
}
pub fn new(topo: &Topology, step: usize, created_from: Option<String>) -> Result<Self> {
let topo_json = topo
.to_json()
.map_err(|e| EngineError::Json(format!("net state topology json: {e}")))?;
let net_seed = topo.options.topology_seed;
Ok(NetState {
hash: topo_hash(&topo_json),
topology: topo_json,
net_seed,
step,
is_alive: true,
culled_at_step: None,
cull_reason: None,
final_smoothed_fitness: None,
entered_at_step: step,
created_from,
last_metrics: None,
meta: NetMeta::default(),
})
}
pub fn to_json(&self) -> Result<String> {
let mut to_write = self.clone();
if to_write.meta.params.is_none() {
let topo = crate::graph::topology::Topology::from_json(&to_write.topology)
.map_err(|e| EngineError::Json(format!("net state meta backfill: {e}")))?;
let net = crate::graph::network::Network::build(&topo, crate::Device::CPU)
.map_err(|e| EngineError::Json(format!("net state meta backfill build: {e}")))?;
to_write.stamp_meta(&net, &crate::engine::config::RunMetaCtx::default());
}
Ok(serde_json::to_string_pretty(&to_write)
.map_err(|e| EngineError::Json(format!("net state json: {e}")))?)
}
pub fn from_json(raw: &str) -> Result<Self> {
Ok(serde_json::from_str(raw)
.map_err(|e| EngineError::Json(format!("net state parse: {e}")))?)
}
pub fn record_metrics(&mut self, metrics: NetMetrics) {
self.last_metrics = Some(metrics);
}
pub fn advance_step(&mut self) {
self.step += 1;
}
pub fn topology(&self) -> Result<Topology> {
Ok(Topology::from_json(&self.topology)
.map_err(|e| EngineError::Json(format!("net state topology parse: {e}")))?)
}
}
pub struct RaceState {
nets: HashMap<String, NetState>,
topology_lifetime: HashMap<String, TopologyLifetime>,
}
#[derive(Clone, Debug)]
pub struct TopologyLifetime {
appearances: usize,
first_step: usize,
last_step: usize,
last_fitness: Option<f32>,
}
impl TopologyLifetime {
pub fn new(first_step: usize, fitness: Option<f32>) -> Self {
TopologyLifetime {
appearances: 1,
first_step,
last_step: first_step,
last_fitness: fitness,
}
}
pub fn record_entry(&mut self, step: usize, fitness: Option<f32>) {
self.appearances = self.appearances.saturating_add(1);
self.last_step = step;
self.last_fitness = fitness;
}
pub fn record_progress(&mut self, step: usize, fitness: Option<f32>) {
self.last_step = self.last_step.max(step);
if let Some(f) = fitness {
self.last_fitness = Some(f);
}
}
pub fn appearances(&self) -> usize {
self.appearances
}
pub fn first_step(&self) -> usize {
self.first_step
}
pub fn last_step(&self) -> usize {
self.last_step
}
pub fn span(&self) -> usize {
self.last_step.saturating_sub(self.first_step)
}
pub fn last_fitness(&self) -> Option<f32> {
self.last_fitness
}
}
impl Default for RaceState {
fn default() -> Self {
Self::new()
}
}
impl RaceState {
pub fn new() -> Self {
RaceState {
nets: HashMap::new(),
topology_lifetime: HashMap::new(),
}
}
pub fn insert(&mut self, state: NetState, initial_fitness: Option<f32>) {
let key = state.hash.clone();
if let Some(entry) = self.topology_lifetime.get_mut(&key) {
entry.record_entry(state.entered_at_step, initial_fitness);
} else {
self.topology_lifetime.insert(
key.clone(),
TopologyLifetime::new(state.entered_at_step, initial_fitness),
);
}
self.nets.insert(key, state);
}
pub fn record_step(&mut self, hash: &str, metrics: NetMetrics) -> Result<()> {
let state = self.nets.get_mut(hash).ok_or_else(|| {
EngineError::InvalidOptions(format!("race state: net {hash} not live"))
})?;
state.record_metrics(metrics.clone());
state.advance_step();
let fitness = metrics.fitness;
let fitness = if fitness.is_finite() {
Some(fitness)
} else {
None
};
let entry = self
.topology_lifetime
.entry(hash.to_string())
.or_insert_with(|| TopologyLifetime::new(state.entered_at_step, fitness));
entry.record_progress(metrics.step, fitness);
Ok(())
}
pub fn net(&self, hash: &str) -> Option<&NetState> {
self.nets.get(hash)
}
pub fn net_mut(&mut self, hash: &str) -> Option<&mut NetState> {
self.nets.get_mut(hash)
}
pub fn live_hashes(&self) -> Vec<String> {
let mut hashes: Vec<String> = self.nets.keys().cloned().collect();
hashes.sort();
hashes
}
pub fn live_count(&self) -> usize {
self.nets.len()
}
pub fn remove(&mut self, hash: &str) -> Option<NetState> {
let state = self.nets.remove(hash);
if let Some(state) = &state {
self.topology_lifetime.remove(&state.hash);
}
state
}
pub fn lifetimes(&self) -> Vec<(&String, &TopologyLifetime)> {
let mut out: Vec<_> = self.topology_lifetime.iter().collect();
out.sort_by_key(|(a, _)| *a);
out
}
pub fn clear(&mut self) {
self.nets.clear();
self.topology_lifetime.clear();
}
}
pub fn write_engine_json(dir: &Path, header: &RunHeader) -> Result<()> {
std::fs::create_dir_all(dir).map_err(|source| EngineError::Io {
path: dir.display().to_string(),
source,
})?;
let path = dir.join("engine.json");
let json = header.to_json()?;
std::fs::write(&path, json).map_err(|source| EngineError::Io {
path: path.display().to_string(),
source,
})?;
Ok(())
}
pub fn load_engine_json(dir: &Path) -> Result<RunHeader> {
let path = dir.join("engine.json");
let raw = std::fs::read_to_string(&path).map_err(|source| EngineError::Io {
path: path.display().to_string(),
source,
})?;
RunHeader::from_json(&raw)
}
pub fn ensure_nets_dir(dir: &Path) -> Result<()> {
std::fs::create_dir_all(dir.join("nets")).map_err(|source| EngineError::Io {
path: dir.display().to_string(),
source,
})?;
Ok(())
}
pub fn write_net_state(dir: &Path, state: &NetState) -> Result<()> {
ensure_nets_dir(dir)?;
let path = dir.join("nets").join(format!("{}.json", state.hash));
let json = state.to_json()?;
std::fs::write(&path, json).map_err(|source| EngineError::Io {
path: path.display().to_string(),
source,
})?;
Ok(())
}
pub fn load_net_state(dir: &Path, hash: &str) -> Result<NetState> {
let path = dir.join("nets").join(format!("{}.json", hash));
let raw = std::fs::read_to_string(&path).map_err(|source| EngineError::Io {
path: path.display().to_string(),
source,
})?;
NetState::from_json(&raw)
}
pub fn remove_net_state(dir: &Path, hash: &str) -> Result<bool> {
let path = dir.join("nets").join(format!("{}.json", hash));
if path.exists() {
std::fs::remove_file(&path).map_err(|source| EngineError::Io {
path: path.display().to_string(),
source,
})?;
Ok(true)
} else {
Ok(false)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::engine::fitness::{Direction, FitnessLabel};
use crate::graph::topology::TopologyOptions;
use std::path::PathBuf;
fn fresh_dir() -> PathBuf {
let dir = std::env::temp_dir().join(format!(
"gras_race_state_test_{}",
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
let _ = std::fs::remove_dir_all(&dir);
dir
}
fn baseline_header(run_id: &str) -> RunHeader {
RunHeader::from_race_options(RunConfig {
run_id: run_id.to_string(),
run_seed: 42,
fitness_label: FitnessLabel("f1".to_string()),
fitness_direction: Direction::Maximize,
input_dim: 784,
output_dim: 10,
topology_options: TopologyOptions::default(),
hidden_dim_pool: 4..=8,
hidden_dim_stride: 1,
combine_op_pool: vec!["Mean".into(), "Min".into()],
activation_pool: vec!["ReLU".into(), "SELU".into()],
standardize_op_pool: vec!["Identity".into()],
informative_metrics: vec![Metric("dummy".to_string())],
max_steps: Some(10_000),
train_eval_split_ratio: Some(0.2),
held_out_eval_rows: Some(256),
config: ConfigSnapshot::default(),
trainer: None,
})
}
fn tiny_topology() -> Topology {
let mut topo = crate::graph::topology::Topology::new(
0,
Some(crate::graph::topology::TopologyOptions {
topology_seed: 7,
min_hidden_num_nodes: 1,
max_hidden_num_nodes: 1,
min_hidden_inputs_per_node: 1,
max_hidden_inputs_per_node: 1,
min_hidden_outputs_per_node: 1,
max_hidden_outputs_per_node: 1,
input_dim: Some(2),
output_dim: Some(2),
dropout_prob: 0.0,
}),
);
topo.nodes.push(crate::graph::node::Node::new_input(0, 2));
topo.nodes
.push(crate::graph::node::Node::new_hidden(1, 2, 4));
topo.nodes
.push(crate::graph::node::Node::new_output(2, 4, 2));
topo
}
#[test]
fn engine_json_write_and_read_back_identical() {
let dir = fresh_dir();
let header = baseline_header("run-1");
write_engine_json(&dir, &header).unwrap();
let loaded = load_engine_json(&dir).unwrap();
assert_eq!(loaded.run_id, "run-1");
assert_eq!(loaded.run_seed, 42);
assert_eq!(loaded.fitness_label.0, "f1");
assert_eq!(loaded.fitness_direction, Direction::Maximize);
assert_eq!(loaded.input_dim, 784);
assert_eq!(loaded.output_dim, 10);
assert_eq!(loaded.max_steps, Some(10_000));
let updated = baseline_header("run-2");
write_engine_json(&dir, &updated).unwrap();
let again = load_engine_json(&dir).unwrap();
assert_eq!(again.run_id, "run-2");
}
#[test]
fn net_state_round_trip_keeps_hash_and_seed_and_step() {
let dir = fresh_dir();
let topo = tiny_topology();
let mut state = NetState::new(&topo, 0, Some("parent-a x parent-b".into())).unwrap();
state.record_metrics(NetMetrics {
step: 5,
train_loss: 1.25,
eval_loss: Some(1.40),
fitness: 0.61,
informative: vec![0.4, 0.6],
});
write_net_state(&dir, &state).unwrap();
let loaded = load_net_state(&dir, &state.hash).unwrap();
assert_eq!(loaded.hash, state.hash);
assert_eq!(loaded.net_seed, 7);
assert_eq!(loaded.step, 0);
assert_eq!(loaded.entered_at_step, 0);
assert_eq!(loaded.created_from.as_deref(), Some("parent-a x parent-b"));
let m = loaded.last_metrics.as_ref().unwrap();
assert_eq!(m.step, 5);
assert_eq!(m.train_loss, 1.25);
assert_eq!(m.eval_loss, Some(1.40));
assert_eq!(m.fitness, 0.61);
assert_eq!(m.informative, vec![0.4, 0.6]);
assert_eq!(loaded.hash, topo_hash(&loaded.topology));
let rebuilt = loaded.topology().unwrap();
let rebuilt_json = rebuilt.to_json().unwrap();
assert_eq!(rebuilt_json, loaded.topology);
}
#[test]
fn overwrite_replaces_previous_step() {
let dir = fresh_dir();
let topo = tiny_topology();
let mut state = NetState::new(&topo, 0, None).unwrap();
state.record_metrics(NetMetrics {
step: 0,
train_loss: 2.0,
eval_loss: Some(2.1),
fitness: 0.1,
informative: vec![],
});
write_net_state(&dir, &state).unwrap();
state.advance_step();
state.record_metrics(NetMetrics {
step: 1,
train_loss: 1.5,
eval_loss: Some(1.6),
fitness: 0.2,
informative: vec![],
});
write_net_state(&dir, &state).unwrap();
let loaded = load_net_state(&dir, &state.hash).unwrap();
assert_eq!(loaded.step, 1);
assert_eq!(loaded.last_metrics.as_ref().unwrap().fitness, 0.2);
}
#[test]
fn race_state_insert_and_remove() {
let mut st = RaceState::new();
let topo = tiny_topology();
let state = NetState::new(&topo, 0, None).unwrap();
st.insert(state, Some(0.3));
assert_eq!(st.live_count(), 1);
let hashes = st.live_hashes();
assert_eq!(hashes.len(), 1);
assert_eq!(hashes[0].len(), 16);
let removed = st.remove(&hashes[0]);
assert!(removed.is_some());
assert_eq!(st.live_count(), 0);
}
#[test]
fn race_state_lifetime_tracks_appearances_and_span() {
let mut st = RaceState::new();
let topo = tiny_topology();
let state = NetState::new(&topo, 10, None).unwrap();
st.insert(state, Some(0.3));
let h = st.live_hashes()[0].clone();
st.record_step(
&h,
NetMetrics {
step: 10,
train_loss: 0.0,
eval_loss: None,
fitness: 0.4,
informative: vec![],
},
)
.unwrap();
st.record_step(
&h,
NetMetrics {
step: 11,
train_loss: 0.0,
eval_loss: None,
fitness: 0.5,
informative: vec![],
},
)
.unwrap();
let (_, life) = st.lifetimes().into_iter().next().unwrap();
assert_eq!(life.appearances(), 1);
assert_eq!(life.first_step(), 10);
assert_eq!(life.last_step(), 11);
assert_eq!(life.span(), 1);
assert_eq!(life.last_fitness(), Some(0.5));
assert_eq!(st.live_count(), 1);
}
#[test]
fn removed_net_file_is_gone() {
let dir = fresh_dir();
let topo = tiny_topology();
let state = NetState::new(&topo, 0, None).unwrap();
write_net_state(&dir, &state).unwrap();
assert!(
dir.join("nets")
.join(format!("{}.json", state.hash))
.exists()
);
remove_net_state(&dir, &state.hash).unwrap();
assert!(
!dir.join("nets")
.join(format!("{}.json", state.hash))
.exists()
);
}
#[test]
fn load_nonexistent_net_errors() {
let dir = fresh_dir();
let err = load_net_state(&dir, "deadbeef").unwrap_err();
assert!(err.to_string().contains("cannot access"));
}
}