use crate::graph::node::{Activation, CombineOp, StandardizeOp};
use crate::graph::topology::FeatureSplitPolicy;
use super::config::{CrossoverOp, RaceConfig};
pub(crate) trait SearchPool {
type Choice;
const LABEL: &'static str;
const ACCEPTED: &'static [&'static str];
fn entries(cfg: &RaceConfig) -> &[String];
fn default_choices() -> Vec<Self::Choice>;
fn parse(entry: &str) -> Option<Self::Choice>;
fn wire(choice: &Self::Choice) -> String;
}
pub(crate) fn resolve<P: SearchPool>(cfg: &RaceConfig) -> Result<Vec<P::Choice>, String> {
let entries = P::entries(cfg);
if entries.is_empty() {
return Ok(P::default_choices());
}
entries
.iter()
.map(|raw| {
P::parse(raw).ok_or_else(|| {
format!(
"{} {raw:?}: expected one of {}",
P::LABEL,
P::ACCEPTED.join(", ")
)
})
})
.collect()
}
pub(crate) fn names<P: SearchPool>(cfg: &RaceConfig) -> Vec<String> {
match resolve::<P>(cfg) {
Ok(choices) => choices.iter().map(P::wire).collect(),
Err(_) => P::entries(cfg).to_vec(),
}
}
pub(crate) fn error<P: SearchPool>(cfg: &RaceConfig) -> Option<String> {
resolve::<P>(cfg).err()
}
pub(crate) struct CrossoverOpsPool;
impl SearchPool for CrossoverOpsPool {
type Choice = CrossoverOp;
const LABEL: &'static str = "crossover_ops_pool";
const ACCEPTED: &'static [&'static str] = &["one_point", "onepoint", "uniform"];
fn entries(cfg: &RaceConfig) -> &[String] {
&cfg.crossover_ops_pool
}
fn default_choices() -> Vec<CrossoverOp> {
vec![CrossoverOp::OnePoint, CrossoverOp::Uniform]
}
fn parse(entry: &str) -> Option<CrossoverOp> {
CrossoverOp::try_from(entry).ok()
}
fn wire(choice: &CrossoverOp) -> String {
match choice {
CrossoverOp::OnePoint => "one_point",
CrossoverOp::Uniform => "uniform",
}
.to_string()
}
}
pub(crate) struct ActivationPool;
impl SearchPool for ActivationPool {
type Choice = Activation;
const LABEL: &'static str = "activation_pool";
const ACCEPTED: &'static [&'static str] = &[
"identity",
"relu",
"gelu",
"silu",
"selu",
"tanh",
"sigmoid",
"mish",
"leaky_relu",
"elu",
"gelu_tanh",
"softplus",
"hardswish",
"hardsigmoid",
"sin",
"cos",
"softmax",
"log_softmax",
"logsoftmax",
];
fn entries(cfg: &RaceConfig) -> &[String] {
&cfg.activation_pool
}
fn default_choices() -> Vec<Activation> {
crate::evolution::pools::all_activations()
}
fn parse(entry: &str) -> Option<Activation> {
RaceConfig::parse_activation(entry).ok()
}
fn wire(choice: &Activation) -> String {
choice.to_string()
}
}
pub(crate) struct CombineOpPool;
impl SearchPool for CombineOpPool {
type Choice = CombineOp;
const LABEL: &'static str = "combine_op_pool";
const ACCEPTED: &'static [&'static str] = &[
"add", "mean", "max", "min", "mul", "multiply", "sub", "subtract", "div", "divide",
];
fn entries(cfg: &RaceConfig) -> &[String] {
&cfg.combine_op_pool
}
fn default_choices() -> Vec<CombineOp> {
crate::evolution::pools::all_combine_ops()
}
fn parse(entry: &str) -> Option<CombineOp> {
RaceConfig::parse_combine(entry).ok()
}
fn wire(choice: &CombineOp) -> String {
choice.to_string()
}
}
pub(crate) struct StandardizePool;
impl SearchPool for StandardizePool {
type Choice = StandardizeOp;
const LABEL: &'static str = "standardize_op_pool";
const ACCEPTED: &'static [&'static str] = &[
"identity",
"layernorm",
"rmsnorm",
"rms_norm",
"instancenorm",
"instance_norm",
"groupnorm",
"group_norm",
];
fn entries(cfg: &RaceConfig) -> &[String] {
&cfg.standardize_op_pool
}
fn default_choices() -> Vec<StandardizeOp> {
crate::evolution::pools::all_standardize_ops()
}
fn parse(entry: &str) -> Option<StandardizeOp> {
StandardizeOp::try_from(entry).ok()
}
fn wire(choice: &StandardizeOp) -> String {
choice.to_string()
}
}
pub(crate) struct FeatureSplitPool;
impl SearchPool for FeatureSplitPool {
type Choice = Option<FeatureSplitPolicy>;
const LABEL: &'static str = "feature_split_pool";
const ACCEPTED: &'static [&'static str] = &[
"none",
"off",
"random",
"split_random",
"exclusive",
"split_exclusive",
];
fn entries(cfg: &RaceConfig) -> &[String] {
&cfg.feature_split_pool
}
fn default_choices() -> Vec<Option<FeatureSplitPolicy>> {
vec![
None,
Some(FeatureSplitPolicy::Random),
Some(FeatureSplitPolicy::Exclusive),
]
}
fn parse(entry: &str) -> Option<Option<FeatureSplitPolicy>> {
super::config::parse_feature_split_pool_entry(entry)
}
fn wire(choice: &Option<FeatureSplitPolicy>) -> String {
choice
.map(|p| p.to_string())
.unwrap_or_else(|| "none".to_string())
}
}
#[cfg(test)]
mod tests {
use super::{
ActivationPool, CombineOpPool, CrossoverOpsPool, FeatureSplitPool, SearchPool,
StandardizePool, names, resolve,
};
use crate::engine::config::RaceConfig;
fn entries_mut<'a>(cfg: &'a mut RaceConfig, label: &str) -> &'a mut Vec<String> {
match label {
"crossover_ops_pool" => &mut cfg.crossover_ops_pool,
"activation_pool" => &mut cfg.activation_pool,
"combine_op_pool" => &mut cfg.combine_op_pool,
"standardize_op_pool" => &mut cfg.standardize_op_pool,
"feature_split_pool" => &mut cfg.feature_split_pool,
other => panic!("{other} is a new pool: add it to this match"),
}
}
fn contract<P: SearchPool>() {
for token in P::ACCEPTED {
assert!(
P::parse(token).is_some(),
"{} advertises {token:?}, but the parser refuses it",
P::LABEL
);
}
for choice in P::default_choices() {
let wire = P::wire(&choice);
let round = P::parse(&wire)
.unwrap_or_else(|| panic!("{} writes {wire:?}, which it cannot read", P::LABEL));
assert_eq!(P::wire(&round), wire, "{} wire is not a fixpoint", P::LABEL);
}
let cfg = RaceConfig::defaults();
assert!(P::entries(&cfg).is_empty(), "{} ships empty", P::LABEL);
let resolved = resolve::<P>(&cfg).expect("an empty pool always resolves");
let want: Vec<String> = P::default_choices().iter().map(P::wire).collect();
let got: Vec<String> = resolved.iter().map(P::wire).collect();
assert_eq!(got, want, "{}: empty ⇒ all", P::LABEL);
assert_eq!(names::<P>(&cfg), want, "{}: names ⇒ wire names", P::LABEL);
let mut typo = RaceConfig::defaults();
entries_mut(&mut typo, P::LABEL).push("no_such_thing".to_string());
let err = match resolve::<P>(&typo) {
Ok(_) => panic!("{}: a typo must not resolve", P::LABEL),
Err(err) => err,
};
assert!(
err.contains(P::LABEL) && err.contains("no_such_thing"),
"{}: refusal must name pool and entry, got {err}",
P::LABEL
);
assert_eq!(names::<P>(&typo), vec!["no_such_thing".to_string()]);
}
#[test]
fn every_name_pool_keeps_the_same_contract() {
contract::<CrossoverOpsPool>();
contract::<ActivationPool>();
contract::<CombineOpPool>();
contract::<StandardizePool>();
contract::<FeatureSplitPool>();
}
#[test]
fn no_split_is_a_choice_not_a_parse_failure() {
let cfg = RaceConfig {
feature_split_pool: vec!["none".to_string(), "split_random".to_string()],
..RaceConfig::defaults()
};
let pool = resolve::<FeatureSplitPool>(&cfg).expect("both entries parse");
assert_eq!(pool.len(), 2);
assert_eq!(pool[0], None);
assert_eq!(
pool[1],
Some(crate::graph::topology::FeatureSplitPolicy::Random)
);
assert_eq!(
names::<FeatureSplitPool>(&cfg),
vec!["none", "split_random"]
);
assert!(FeatureSplitPool::parse("split_inherited").is_none());
}
}