Skip to main content

oa/ml/training/
ppo_driver.rs

1//! Short driver around the caller-driven PPO trainer.
2//!
3//! Every PPO workflow needs the same loop: collect one fixed-horizon rollout
4//! through the vector environment, run the update epochs, evaluate the policy
5//! on independent seeds at a declared cadence, and stop at the trainer's
6//! rollout budget. Tutorials and benchmarks used to hand-roll this loop with
7//! subtly divergent accounting. [`drive_categorical_ppo`] owns it once:
8//! environment transaction discipline, abort/cancel pairing on failure,
9//! evaluation on a fresh independently seeded environment instance, and a
10//! report separating training and evaluation accounting.
11//!
12//! The driver stays categorical because the admitted PPO trainer is
13//! categorical; continuous PPO is qualified separately in the roadmap. The
14//! environment is caller-constructed and caller-typed — the driver is generic
15//! over the [`Environment`](crate::ml::environment::Environment) behavior
16//! contract only — and evaluation environments come from a caller factory so
17//! environment construction flags stay workload-owned; the driver owns each
18//! evaluation instance's initial reset with its independent seed.
19
20use std::time::Instant;
21
22use crate::Result;
23use crate::ml::CategoricalActorCritic;
24use crate::ml::environment::Environment;
25use crate::ml::evaluation::{
26	PolicyEvaluationConfig, PolicyEvaluationMetrics, evaluate_categorical,
27};
28
29use super::PpoTrainer;
30
31/// Evaluation cadence and seeds for one driven PPO run. The rollout budget
32/// itself lives in the trainer configuration — the trainer owns pacing and
33/// completion.
34#[derive(Clone, Debug)]
35pub struct PpoDriverConfig {
36	/// Completed-rollout interval between evaluations. Zero disables
37	/// periodic evaluation; the final evaluation after training completion
38	/// always runs.
39	pub evaluation_interval: u64,
40	/// Evaluation horizon per evaluation, in vector steps.
41	pub evaluation_horizon: usize,
42	/// Seed for the initial training-environment reset when the environment
43	/// has never been submitted.
44	pub training_seed: u64,
45	/// Base seed for evaluation — independent of training seeds so learning
46	/// claims never measure the training distribution. Each evaluation
47	/// offsets this base by its own index.
48	pub evaluation_seed: u64,
49}
50
51impl Default for PpoDriverConfig {
52	fn default() -> Self {
53		Self {
54			evaluation_interval: 0,
55			evaluation_horizon: 500,
56			training_seed: 0,
57			evaluation_seed: 0x0e7a1,
58		}
59	}
60}
61
62impl PpoDriverConfig {
63	/// Construct the default driver configuration.
64	#[inline]
65	#[must_use]
66	pub fn new() -> Self {
67		Self::default()
68	}
69}
70
71/// One evaluation observation inside a driven run.
72#[derive(Clone, Debug)]
73pub struct PpoEvaluationRecord {
74	/// One-based completed-rollout count at which the evaluation ran.
75	pub after_rollout: u64,
76	/// The full metrics of the independent evaluation instance.
77	pub metrics: PolicyEvaluationMetrics,
78}
79
80/// Accounting-separated outcome of one driven PPO run.
81#[derive(Clone, Debug)]
82pub struct PpoDriverReport {
83	/// Rollouts collected and updated to trainer completion.
84	pub rollouts_completed: u64,
85	/// Individual lane transitions collected across all rollouts.
86	pub transitions_collected: u64,
87	/// Every evaluation in cadence order, ending with the final one.
88	pub evaluations: Vec<PpoEvaluationRecord>,
89	/// Composite total loss after each completed rollout, in rollout order —
90	/// the learning-curve feed for progress output and plots.
91	pub rollout_losses: Vec<f32>,
92	/// Wall time inside collection and update, excluding evaluation.
93	pub training_seconds: f64,
94	/// Wall time inside evaluation, excluding training.
95	pub evaluation_seconds: f64,
96}
97
98impl PpoDriverReport {
99	/// Individual lane transitions collected per second of training wall
100	/// time — the environment-throughput signal for performance comparison.
101	/// Zero when no training time was recorded.
102	#[must_use]
103	pub fn transitions_per_second(&self) -> f64 {
104		if self.training_seconds > 0.0 {
105			self.transitions_collected as f64 / self.training_seconds
106		} else {
107			0.0
108		}
109	}
110}
111
112/// Drive a categorical PPO trainer against one vector environment to
113/// completion.
114///
115/// The loop follows the trainer's own pacing: while the trainer is not
116/// done, collect when the trainer needs collection, then apply one update
117/// step. Collection per rollout begins one environment transaction, acts
118/// and observes across the configured horizon with auto-reset of completed
119/// lanes, ends collection, and submits/waits the transaction; any recording
120/// failure aborts collection and cancels the transaction in pairs, matching
121/// the tutorial discipline. Evaluation runs every
122/// `evaluation_interval` completed rollouts and once after completion on a
123/// fresh environment from `make_evaluation_environment`, seeded
124/// independently of training. `model` is the policy under training —
125/// caller-owned exactly as the trainer borrows it — used for evaluation.
126///
127/// # Errors
128///
129/// Returns environment, collection, update, or evaluation errors.
130pub fn drive_categorical_ppo<E, F>(
131	trainer: &mut PpoTrainer<'_, '_>,
132	model: &CategoricalActorCritic,
133	environment: &mut E,
134	mut make_evaluation_environment: F,
135	config: &PpoDriverConfig,
136) -> Result<PpoDriverReport>
137where
138	E: Environment,
139	F: FnMut() -> Result<E>,
140{
141	let mut evaluation_index = 0_u64;
142	let mut report = PpoDriverReport {
143		rollouts_completed: 0,
144		transitions_collected: 0,
145		evaluations: Vec::new(),
146		rollout_losses: Vec::new(),
147		training_seconds: 0.0,
148		evaluation_seconds: 0.0,
149	};
150	let transitions_per_rollout =
151		u64::try_from(trainer.config().horizon).unwrap_or(0) * trainer.config().environments as u64;
152
153	let mut evaluate = |after_rollout: u64, report: &mut PpoDriverReport| -> Result<()> {
154		let started = Instant::now();
155		let mut eval_env = make_evaluation_environment()?;
156		let seed = config
157			.evaluation_seed
158			.wrapping_add(evaluation_index.wrapping_mul(0x9e37_79b9));
159		evaluation_index += 1;
160		// Finish constructor-recorded work before evaluation allocates its
161		// rollout buffer. The evaluator records the independently seeded reset.
162		if eval_env.execution().has_active_recording() {
163			let initialized = eval_env.submit()?;
164			eval_env.wait(&initialized)?;
165		}
166		let metrics = evaluate_categorical(
167			&mut eval_env,
168			model,
169			PolicyEvaluationConfig {
170				horizon: config.evaluation_horizon,
171				seed,
172			},
173		)?;
174		eval_env.close()?;
175		report.evaluation_seconds += started.elapsed().as_secs_f64();
176		report.evaluations.push(PpoEvaluationRecord {
177			after_rollout,
178			metrics,
179		});
180		Ok(())
181	};
182
183	while !trainer.is_done() {
184		let started = Instant::now();
185		if trainer.needs_collection() {
186			if environment.execution().submission_count() == 0
187				&& !environment.execution().has_active_recording()
188				&& !environment.holds_committed_state()
189			{
190				environment.reset(config.training_seed)?;
191			}
192			environment.begin()?;
193			if let Err(error) = trainer.begin_collection() {
194				let _ = environment.cancel();
195				return Err(error);
196			}
197			let recorded = (|| {
198				for _ in 0..trainer.config().horizon {
199					let policy = trainer.act(environment.observation())?;
200					let transition = environment.step(&policy.action)?;
201					trainer.observe(
202						transition.observation(),
203						transition.next_observation(),
204						transition.reward(),
205						transition.terminated(),
206						transition.truncated(),
207						&policy,
208					)?;
209					environment.reset_completed()?;
210				}
211				trainer.end_collection()
212			})();
213			if let Err(error) = recorded {
214				let _ = environment.cancel();
215				let _ = trainer.abort_collection();
216				return Err(error);
217			}
218			let event = match environment.submit() {
219				Ok(event) => event,
220				Err(error) => {
221					let _ = trainer.abort_collection();
222					return Err(error);
223				}
224			};
225			environment.wait(&event)?;
226			report.transitions_collected += transitions_per_rollout;
227		}
228		trainer.update()?;
229		report.training_seconds += started.elapsed().as_secs_f64();
230		let rollout = trainer.metrics().rollout;
231		if rollout as usize > report.rollout_losses.len() {
232			report.rollout_losses.push(trainer.metrics().total_loss);
233		}
234		report.rollouts_completed = rollout;
235		if config.evaluation_interval != 0
236			&& rollout != 0
237			&& rollout.is_multiple_of(config.evaluation_interval)
238		{
239			evaluate(rollout, &mut report)?;
240		}
241	}
242	evaluate(report.rollouts_completed, &mut report)?;
243	Ok(report)
244}