Skip to main content

EvolutionaryHarness

Struct EvolutionaryHarness 

Source
pub struct EvolutionaryHarness<B, S, F>
where B: Backend, S: Strategy<B>, F: BatchFitnessFn<B, S::Genome>,
{ /* private fields */ }
Expand description

Wraps a Strategy into a BenchEnv so the benchmark harness can drive it.

§Example

use burn::backend::Flex;
use rlevo_core::fitness::FitnessEvaluable;
use rlevo_core::evaluation::BenchEnv;
use rlevo_evolution::algorithms::ga::{GaConfig, GeneticAlgorithm};
use rlevo_evolution::fitness::FromFitnessEvaluable;
use rlevo_evolution::strategy::EvolutionaryHarness;

struct Sphere;
struct SphereFit;
impl FitnessEvaluable for SphereFit {
    type Individual = Vec<f64>;
    type Landscape = Sphere;
    fn evaluate(&self, x: &Self::Individual, _: &Self::Landscape) -> f64 {
        x.iter().map(|v| v * v).sum()
    }
}

let device = Default::default();
let mut harness = EvolutionaryHarness::<Flex, _, _>::new(
    GeneticAlgorithm::<Flex>::new(),
    GaConfig::default_for(32, 5),
    FromFitnessEvaluable::new(SphereFit, Sphere),
    0, device, 100,
);
harness.reset();
while !harness.step(()).done {}

Each step runs one generation (ask → evaluate → tell). The reward returned to the harness is -best_fitness_ever so the harness’s “higher = better” convention matches the strategy’s minimization direction, and so the per-episode cumulative return (Σ step rewards) integrates the optimization trajectory — return_value / num_steps bounds the final best_fitness_ever from above. The harness only exposes episode-level returns to reporters, so the “best at end” signal would otherwise be lost.

§Determinism and parallel execution

Burn backends seed their tensor RNG through process-global state — the flex backend uses a Mutex<Option<FlexRng>>, the wgpu backend a per-device seeded stream. When multiple harness instances run in parallel threads (e.g. Evaluator::run_suite with the default rayon pool), their interleaved B::seed(...) → Tensor::random(...) call pairs race on that shared state and destroy bit-reproducibility across runs.

For deterministic reproduction, pass EvaluatorConfig::num_threads = Some(1) or run one harness per process. The tests/determinism.rs and tests/rastrigin_run_suite.rs integration tests both enforce serial execution for this reason.

Implementations§

Source§

impl<B, S, F> EvolutionaryHarness<B, S, F>
where B: Backend, S: Strategy<B>, F: BatchFitnessFn<B, S::Genome>,

Source

pub fn new( strategy: S, params: S::Params, fitness_fn: F, seed: u64, device: B::Device, max_generations: usize, ) -> Self

Build a new harness from its parts.

The harness is lazily initialized — the first reset call materializes the initial state on the supplied device.

Source

pub fn with_observer(self, observer: SharedPopulationObserver) -> Self

Attach a per-generation PopulationObserver.

The observer is called once per step call, after the canonical tracing::info!("evolution generation", …) event. It receives a PopulationSnapshot carrying the full per-individual fitness vector for the completed generation. The intended consumer is a benchmark-tier recording sink that persists population-level data alongside the scalar metric stream.

Attaching an observer adds one device→host transfer of the fitness tensor per generation; runs without an observer pay nothing.

Source

pub fn latest_metrics(&self) -> Option<&StrategyMetrics>

Snapshot of the most recent generation’s metrics, if any.

Source

pub fn generation(&self) -> usize

Generation counter — number of completed tell calls.

Source

pub fn state(&self) -> Option<&S::State>

Borrow the current strategy state if it exists.

Source

pub fn best(&self) -> Option<(S::Genome, f32)>

Forward to Strategy::best when a state exists.

Source

pub fn reset(&mut self)

Reset to a fresh initial state.

Inherent shape (infallible): EvolutionaryHarness cannot legitimately fail to reset — it is a deterministic optimization driver. The BenchEnv trait impl wraps this in Ok(()) so the harness is callable both directly (this method) and via the BenchEnv surface when fed to Evaluator::run_suite.

Source

pub fn step(&mut self, _action: ()) -> BenchStep<()>

Run one ask → evaluate → tell generation.

Inherent shape (infallible). The BenchEnv trait impl wraps this in Ok(...). See Self::reset for the rationale.

§Panics

Panics if reset has not been called first.

Trait Implementations§

Source§

impl<B, S, F> BenchEnv for EvolutionaryHarness<B, S, F>
where B: Backend, S: Strategy<B>, F: BatchFitnessFn<B, S::Genome>,

Source§

type Observation = ()

The observation type the environment produces on each step.
Source§

type Action = ()

The action type the environment accepts on each step.
Source§

fn reset(&mut self) -> Result<Self::Observation, BenchError>

Reset the environment to an initial state and return the first observation. Read more
Source§

fn step( &mut self, action: Self::Action, ) -> Result<BenchStep<Self::Observation>, BenchError>

Apply action and advance the environment by one step. Read more
Source§

impl<B, S, F> Debug for EvolutionaryHarness<B, S, F>
where B: Backend, S: Strategy<B>, F: BatchFitnessFn<B, S::Genome>,

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<B, S, F> !RefUnwindSafe for EvolutionaryHarness<B, S, F>

§

impl<B, S, F> !UnwindSafe for EvolutionaryHarness<B, S, F>

§

impl<B, S, F> Freeze for EvolutionaryHarness<B, S, F>
where S: Freeze, <S as Strategy<B>>::Params: Freeze, F: Freeze, <B as BackendTypes>::Device: Freeze, <S as Strategy<B>>::State: Freeze,

§

impl<B, S, F> Send for EvolutionaryHarness<B, S, F>

§

impl<B, S, F> Sync for EvolutionaryHarness<B, S, F>
where F: Sync, <S as Strategy<B>>::State: Sync,

§

impl<B, S, F> Unpin for EvolutionaryHarness<B, S, F>
where S: Unpin, <S as Strategy<B>>::Params: Unpin, F: Unpin, <B as BackendTypes>::Device: Unpin, <S as Strategy<B>>::State: Unpin, B: Unpin,

§

impl<B, S, F> UnsafeUnpin for EvolutionaryHarness<B, S, F>

Blanket Implementations§

Source§

impl<T> Adaptor<()> for T

Source§

fn adapt(&self)

Adapt the type to be passed to a metric.
Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> Downcast<T> for T

Source§

fn downcast(&self) -> &T

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoComptime for T

Source§

fn comptime(self) -> Self

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> Upcast<T> for T

Source§

fn upcast(&self) -> Option<&T>

Source§

impl<T> WasmNotSend for T
where T: Send,

Source§

impl<T> WasmNotSendSync for T

Source§

impl<T> WasmNotSync for T
where T: Sync,

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more