oarust 0.19.0

GPU-first semantic computing runtime written in Rust
Documentation
//! Short driver around the caller-driven PPO trainer.
//!
//! Every PPO workflow needs the same loop: collect one fixed-horizon rollout
//! through the vector environment, run the update epochs, evaluate the policy
//! on independent seeds at a declared cadence, and stop at the trainer's
//! rollout budget. Tutorials and benchmarks used to hand-roll this loop with
//! subtly divergent accounting. [`drive_categorical_ppo`] owns it once:
//! environment transaction discipline, abort/cancel pairing on failure,
//! evaluation on a fresh independently seeded environment instance, and a
//! report separating training and evaluation accounting.
//!
//! The driver stays categorical because the admitted PPO trainer is
//! categorical; continuous PPO is qualified separately in the roadmap. The
//! environment is caller-constructed and caller-typed — the driver is generic
//! over the [`Environment`](crate::ml::environment::Environment) behavior
//! contract only — and evaluation environments come from a caller factory so
//! environment construction flags stay workload-owned; the driver owns each
//! evaluation instance's initial reset with its independent seed.

use std::time::Instant;

use crate::Result;
use crate::ml::CategoricalActorCritic;
use crate::ml::environment::Environment;
use crate::ml::evaluation::{
	PolicyEvaluationConfig, PolicyEvaluationMetrics, evaluate_categorical,
};

use super::PpoTrainer;

/// Evaluation cadence and seeds for one driven PPO run. The rollout budget
/// itself lives in the trainer configuration — the trainer owns pacing and
/// completion.
#[derive(Clone, Debug)]
pub struct PpoDriverConfig {
	/// Completed-rollout interval between evaluations. Zero disables
	/// periodic evaluation; the final evaluation after training completion
	/// always runs.
	pub evaluation_interval: u64,
	/// Evaluation horizon per evaluation, in vector steps.
	pub evaluation_horizon: usize,
	/// Seed for the initial training-environment reset when the environment
	/// has never been submitted.
	pub training_seed: u64,
	/// Base seed for evaluation — independent of training seeds so learning
	/// claims never measure the training distribution. Each evaluation
	/// offsets this base by its own index.
	pub evaluation_seed: u64,
}

impl Default for PpoDriverConfig {
	fn default() -> Self {
		Self {
			evaluation_interval: 0,
			evaluation_horizon: 500,
			training_seed: 0,
			evaluation_seed: 0x0e7a1,
		}
	}
}

impl PpoDriverConfig {
	/// Construct the default driver configuration.
	#[inline]
	#[must_use]
	pub fn new() -> Self {
		Self::default()
	}
}

/// One evaluation observation inside a driven run.
#[derive(Clone, Debug)]
pub struct PpoEvaluationRecord {
	/// One-based completed-rollout count at which the evaluation ran.
	pub after_rollout: u64,
	/// The full metrics of the independent evaluation instance.
	pub metrics: PolicyEvaluationMetrics,
}

/// Accounting-separated outcome of one driven PPO run.
#[derive(Clone, Debug)]
pub struct PpoDriverReport {
	/// Rollouts collected and updated to trainer completion.
	pub rollouts_completed: u64,
	/// Individual lane transitions collected across all rollouts.
	pub transitions_collected: u64,
	/// Every evaluation in cadence order, ending with the final one.
	pub evaluations: Vec<PpoEvaluationRecord>,
	/// Composite total loss after each completed rollout, in rollout order —
	/// the learning-curve feed for progress output and plots.
	pub rollout_losses: Vec<f32>,
	/// Wall time inside collection and update, excluding evaluation.
	pub training_seconds: f64,
	/// Wall time inside evaluation, excluding training.
	pub evaluation_seconds: f64,
}

impl PpoDriverReport {
	/// Individual lane transitions collected per second of training wall
	/// time — the environment-throughput signal for performance comparison.
	/// Zero when no training time was recorded.
	#[must_use]
	pub fn transitions_per_second(&self) -> f64 {
		if self.training_seconds > 0.0 {
			self.transitions_collected as f64 / self.training_seconds
		} else {
			0.0
		}
	}
}

/// Drive a categorical PPO trainer against one vector environment to
/// completion.
///
/// The loop follows the trainer's own pacing: while the trainer is not
/// done, collect when the trainer needs collection, then apply one update
/// step. Collection per rollout begins one environment transaction, acts
/// and observes across the configured horizon with auto-reset of completed
/// lanes, ends collection, and submits/waits the transaction; any recording
/// failure aborts collection and cancels the transaction in pairs, matching
/// the tutorial discipline. Evaluation runs every
/// `evaluation_interval` completed rollouts and once after completion on a
/// fresh environment from `make_evaluation_environment`, seeded
/// independently of training. `model` is the policy under training —
/// caller-owned exactly as the trainer borrows it — used for evaluation.
///
/// # Errors
///
/// Returns environment, collection, update, or evaluation errors.
pub fn drive_categorical_ppo<E, F>(
	trainer: &mut PpoTrainer<'_, '_>,
	model: &CategoricalActorCritic,
	environment: &mut E,
	mut make_evaluation_environment: F,
	config: &PpoDriverConfig,
) -> Result<PpoDriverReport>
where
	E: Environment,
	F: FnMut() -> Result<E>,
{
	let mut evaluation_index = 0_u64;
	let mut report = PpoDriverReport {
		rollouts_completed: 0,
		transitions_collected: 0,
		evaluations: Vec::new(),
		rollout_losses: Vec::new(),
		training_seconds: 0.0,
		evaluation_seconds: 0.0,
	};
	let transitions_per_rollout =
		u64::try_from(trainer.config().horizon).unwrap_or(0) * trainer.config().environments as u64;

	let mut evaluate = |after_rollout: u64, report: &mut PpoDriverReport| -> Result<()> {
		let started = Instant::now();
		let mut eval_env = make_evaluation_environment()?;
		let seed = config
			.evaluation_seed
			.wrapping_add(evaluation_index.wrapping_mul(0x9e37_79b9));
		evaluation_index += 1;
		// Finish constructor-recorded work before evaluation allocates its
		// rollout buffer. The evaluator records the independently seeded reset.
		if eval_env.execution().has_active_recording() {
			let initialized = eval_env.submit()?;
			eval_env.wait(&initialized)?;
		}
		let metrics = evaluate_categorical(
			&mut eval_env,
			model,
			PolicyEvaluationConfig {
				horizon: config.evaluation_horizon,
				seed,
			},
		)?;
		eval_env.close()?;
		report.evaluation_seconds += started.elapsed().as_secs_f64();
		report.evaluations.push(PpoEvaluationRecord {
			after_rollout,
			metrics,
		});
		Ok(())
	};

	while !trainer.is_done() {
		let started = Instant::now();
		if trainer.needs_collection() {
			if environment.execution().submission_count() == 0
				&& !environment.execution().has_active_recording()
				&& !environment.holds_committed_state()
			{
				environment.reset(config.training_seed)?;
			}
			environment.begin()?;
			if let Err(error) = trainer.begin_collection() {
				let _ = environment.cancel();
				return Err(error);
			}
			let recorded = (|| {
				for _ in 0..trainer.config().horizon {
					let policy = trainer.act(environment.observation())?;
					let transition = environment.step(&policy.action)?;
					trainer.observe(
						transition.observation(),
						transition.next_observation(),
						transition.reward(),
						transition.terminated(),
						transition.truncated(),
						&policy,
					)?;
					environment.reset_completed()?;
				}
				trainer.end_collection()
			})();
			if let Err(error) = recorded {
				let _ = environment.cancel();
				let _ = trainer.abort_collection();
				return Err(error);
			}
			let event = match environment.submit() {
				Ok(event) => event,
				Err(error) => {
					let _ = trainer.abort_collection();
					return Err(error);
				}
			};
			environment.wait(&event)?;
			report.transitions_collected += transitions_per_rollout;
		}
		trainer.update()?;
		report.training_seconds += started.elapsed().as_secs_f64();
		let rollout = trainer.metrics().rollout;
		if rollout as usize > report.rollout_losses.len() {
			report.rollout_losses.push(trainer.metrics().total_loss);
		}
		report.rollouts_completed = rollout;
		if config.evaluation_interval != 0
			&& rollout != 0
			&& rollout.is_multiple_of(config.evaluation_interval)
		{
			evaluate(rollout, &mut report)?;
		}
	}
	evaluate(report.rollouts_completed, &mut report)?;
	Ok(report)
}