use crate::engine::config::RaceConfig;
use crate::engine::fitness::Fitness;
use crate::trainer::Trainer;
pub struct RunSpec<T: Trainer + 'static = Box<dyn Trainer>> {
pub data_dir: std::path::PathBuf,
pub config: RaceConfig,
pub fitness: Fitness,
pub trainer: T,
pub seed: Option<u64>,
pub run_dir: Option<std::path::PathBuf>,
}
impl<T: Trainer + 'static> RunSpec<T> {
pub fn new<P: Into<std::path::PathBuf>>(
data_dir: impl Into<std::path::PathBuf>,
config: RaceConfig,
fitness: Fitness,
trainer: T,
seed: Option<u64>,
run_dir: Option<P>,
) -> Self {
Self {
data_dir: data_dir.into(),
config,
fitness,
trainer,
seed,
run_dir: run_dir.map(|p| p.into()),
}
}
pub fn with_trainer<U: Trainer + 'static>(self, trainer: U) -> RunSpec<Box<dyn Trainer>> {
RunSpec {
data_dir: self.data_dir,
config: self.config,
fitness: self.fitness,
trainer: Box::new(trainer),
seed: self.seed,
run_dir: self.run_dir,
}
}
}
pub struct DefaultTrainerBuilder {
loss: Option<
Box<
dyn Fn(&flodl::Variable, &flodl::Variable) -> flodl::tensor::Result<flodl::Variable>
+ Send
+ Sync
+ 'static,
>,
>,
learning_rate: f32,
grad_clip: f32,
}
impl DefaultTrainerBuilder {
pub fn new() -> Self {
Self {
loss: None,
learning_rate: 1e-3,
grad_clip: 1.0,
}
}
pub fn loss(
mut self,
loss: impl Fn(&flodl::Variable, &flodl::Variable) -> flodl::tensor::Result<flodl::Variable>
+ Send
+ Sync
+ 'static,
) -> Self {
self.loss = Some(Box::new(loss));
self
}
pub fn with_learning_rate(mut self, lr: f32) -> Self {
self.learning_rate = lr;
self
}
pub fn with_grad_clip(mut self, clip: f32) -> Self {
self.grad_clip = clip;
self
}
pub fn build(self) -> Box<dyn Trainer> {
let loss = self.loss.unwrap_or_else(|| {
Box::new(|pred, y| crate::utils::score::cross_entropy_onehot_loss(pred, y))
});
Box::new(
crate::trainer::TabularTrainer::new(loss)
.with_learning_rate(self.learning_rate)
.with_grad_clip(self.grad_clip),
)
}
}
#[derive(Clone, Copy, Debug)]
pub struct StreamShape {
pub batch_size: usize,
pub eval_batch_size: usize,
}
impl StreamShape {
pub fn none() -> Self {
Self {
batch_size: 16,
eval_batch_size: 16,
}
}
pub fn with_batch_size(mut self, n: usize) -> Self {
self.batch_size = n;
self
}
pub fn with_eval_batch_size(mut self, n: usize) -> Self {
self.eval_batch_size = n;
self
}
pub fn uniform(n: usize) -> Self {
Self {
batch_size: n,
eval_batch_size: n,
}
}
}