Skip to main content

oa/ml/training/
ppo_program.rs

1//! Bounded PPO update replay. Donor objective/schedule: oa/ml/ppoTrainer.cpp.
2//! Reuses OA capture, GradientTape and TrainingProgram; never owns execution.
3use super::{PpoTrainerConfig, PpoTrainerMetrics, RolloutTraining, TrainingProgram};
4use crate::ml::{ActorCritic, GradientTape, Parameter, RolloutBatch, advantage, loss, policy};
5use crate::{Error, Event, ExecutionPlan, Matrix, Result, Runtime, matrix};
6use std::time::Duration;
7
8/// Reusable fixed-geometry PPO backward and AdamW programs.
9///
10/// Retain this value across trainers when checkpointing between rollouts. Each
11/// minibatch reuses one bounded tape's storage, accumulating sample-weighted
12/// gradients before exactly one AdamW step per epoch. Tail shapes compile once.
13/// Drop never submits or waits. Different models/configurations are rejected.
14#[derive(Default)]
15pub struct PpoUpdateProgram {
16	state: Option<State>,
17	pub(super) rollout: Option<crate::ml::RolloutBuffer>,
18}
19struct State {
20	config: PpoTrainerConfig,
21	parameters: Vec<Parameter>,
22	ids: Vec<u64>,
23	accumulators: Vec<Matrix>,
24	inputs: [Matrix; 5],
25	normalize: ExecutionPlan,
26	cursor: Matrix,
27	metrics: [Matrix; 6],
28	batches: Vec<(usize, ExecutionPlan)>,
29	optimizer: TrainingProgram,
30	epochs: u64,
31}
32impl PpoUpdateProgram {
33	/// Construct an uncompiled PPO update program.
34	#[inline]
35	#[must_use]
36	pub fn new() -> Self {
37		Self::default()
38	}
39
40	/// Discard captured update graphs while retaining the reusable rollout storage.
41	///
42	/// Call between completed trainers when loss parameters change. The next update
43	/// captures its new configuration; collection plans retain their buffer identities.
44	/// Model parameters and optimizer state remain owned by their existing owners.
45	pub fn invalidate_updates(&mut self) {
46		self.state = None;
47	}
48
49	/// Number of complete epochs submitted through the compiled program.
50	pub fn replay_count(&self) -> u64 {
51		self.state.as_ref().map_or(0, |s| s.epochs)
52	}
53	/// Full graph-command recordings, excluding timestamp bracket commands.
54	pub fn command_recording_count(&self) -> u64 {
55		self.state.as_ref().map_or(0, |s| {
56			s.normalize.diagnostics().command_recording_count()
57				+ s.optimizer.diagnostics().command_recording_count()
58				+ s
59					.batches
60					.iter()
61					.map(|(_, p)| p.diagnostics().command_recording_count())
62					.sum::<u64>()
63		})
64	}
65
66	/// Whether the fixed update programs have been compiled.
67	pub fn is_compiled(&self) -> bool {
68		self.state.is_some()
69	}
70	pub(super) fn update(
71		&mut self,
72		runtime: &Runtime,
73		model: &dyn ActorCritic,
74		config: &PpoTrainerConfig,
75		rollout: &RolloutBatch,
76		training: &mut RolloutTraining<'_, '_>,
77	) -> Result<PpoTrainerMetrics> {
78		let batch = config
79			.horizon
80			.checked_mul(config.environments)
81			.ok_or_else(|| Error::resource_exhausted("PPO batch overflow"))?;
82		let width = config.observation_shape.iter().product::<usize>();
83		let inputs = [
84			matrix::reshape(rollout.observation(), [batch, width])?,
85			matrix::reshape(rollout.action(), [batch])?,
86			matrix::reshape(rollout.old_log_probability(), [batch])?,
87			matrix::reshape(rollout.advantage(), [batch])?,
88			matrix::reshape(rollout.returns(), [batch])?,
89		];
90		runtime.checkpoint()?.wait()?;
91		if self.state.is_none() {
92			self.state = Some(State::capture(
93				runtime,
94				model,
95				config,
96				inputs.clone(),
97				training,
98			)?);
99		}
100		let s = self.state.as_mut().expect("captured state");
101		let ids = model
102			.all_parameters()?
103			.iter()
104			.map(|p| p.data().value_id())
105			.collect::<Vec<_>>();
106		if ids != s.ids
107			|| config.horizon != s.config.horizon
108			|| config.environments != s.config.environments
109			|| config.observation_shape != s.config.observation_shape
110			|| config.update_minibatch_size != s.config.update_minibatch_size
111			|| config.loss != s.config.loss
112		{
113			return Err(Error::failed_precondition(
114				"compiled PPO model/geometry/loss changed",
115			));
116		}
117		for (old, new) in s.inputs.iter().zip(&inputs) {
118			if old.same_value_as(new) {
119				continue;
120			}
121			if old.same_value_as(&s.inputs[3]) {
122				s.normalize.bind_matrix_input(old, new)?;
123			} else {
124				for (_, plan) in &mut s.batches {
125					plan.bind_matrix_input(old, new)?;
126				}
127			}
128		}
129		// Whole-rollout advantages are normalized once, before any microbatch.
130		// Minibatch replays submit back-to-back and wait only for completion:
131		// queue order preserves the accumulator writes, and cursor uploads
132		// stage through the bounded input ring, so each in-flight submission
133		// always reads a distinct staged slot. No observations or gradients
134		// cross the host boundary.
135		let mut events = vec![submit(runtime, &s.normalize, config.enable_gpu_timing)?];
136		let mini = if config.update_minibatch_size == 0 {
137			batch
138		} else {
139			config.update_minibatch_size
140		};
141		for start in (0..batch).step_by(mini) {
142			let count = mini.min(batch - start);
143			let (_, plan) = s
144				.batches
145				.iter_mut()
146				.find(|(n, _)| *n == count)
147				.expect("compiled tail");
148			plan.upload_matrix_input(
149				&s.cursor,
150				&[
151					u32::try_from(start).map_err(|_| Error::resource_exhausted("PPO cursor overflow"))?,
152					u32::from(start == 0),
153				],
154			)?;
155			events.push(submit(runtime, plan, config.enable_gpu_timing)?);
156		}
157		let mut elapsed = Duration::ZERO;
158		if config.enable_gpu_timing {
159			for event in &events {
160				elapsed = elapsed
161					.checked_add(event.device_duration()?)
162					.ok_or_else(|| Error::resource_exhausted("PPO timing overflow"))?;
163			}
164		} else if let Some(event) = events.last() {
165			// Every plan uses the same queue. Completion of the last exact
166			// event covers all preceding submissions; retain their owners here.
167			event.wait()?;
168		}
169		let mut metrics = [0.0; 6];
170		for (out, value) in metrics.iter_mut().zip(&s.metrics) {
171			*out = value.read_f32()?[0];
172			if !out.is_finite() {
173				return Err(Error::failed_precondition("compiled PPO metric not finite"));
174			}
175		}
176		for (p, g) in s.parameters.iter().zip(&s.accumulators) {
177			p.restore_gradient(g.clone());
178		}
179		training.complete_compiled_update(&mut s.optimizer, elapsed)?;
180		s.epochs = s
181			.epochs
182			.checked_add(1)
183			.ok_or_else(|| Error::resource_exhausted("PPO replay count overflow"))?;
184		Ok(PpoTrainerMetrics {
185			rollout: training.rollout_index(),
186			update_epoch: training.update_epoch(),
187			total_loss: metrics[0],
188			policy_loss: metrics[1],
189			value_loss: metrics[2],
190			entropy: metrics[3],
191			approx_kl: metrics[4],
192			clip_fraction: metrics[5],
193		})
194	}
195}
196impl State {
197	fn capture(
198		runtime: &Runtime,
199		model: &dyn ActorCritic,
200		config: &PpoTrainerConfig,
201		inputs: [Matrix; 5],
202		training: &mut RolloutTraining<'_, '_>,
203	) -> Result<Self> {
204		let parameters = model.all_parameters()?;
205		let ids = parameters.iter().map(|p| p.data().value_id()).collect();
206		let accumulators = parameters
207			.iter()
208			.map(|p| {
209				let d = p.data();
210				Matrix::new_from_f32_on(runtime, d.shape().to_vec(), &vec![0.; d.num_elements()])
211			})
212			.collect::<Result<Vec<_>>>()?;
213		let metrics: [Result<Matrix>; 6] =
214			std::array::from_fn(|_| Matrix::new_from_f32_on(runtime, [], &[0.]));
215		let metrics: [Matrix; 6] = metrics
216			.into_iter()
217			.collect::<Result<Vec<_>>>()?
218			.try_into()
219			.map_err(|_| Error::internal("PPO metric count"))?;
220		let cursor = Matrix::new_from_slice_on(runtime, [2], &[0_u32, 1])?;
221		runtime.checkpoint()?.wait()?;
222		let normalized = Matrix::new_from_f32_on(
223			runtime,
224			inputs[3].shape().to_vec(),
225			&vec![0.; inputs[3].num_elements()],
226		)?;
227		let copy_cursor = Matrix::new_from_slice_on(runtime, [2], &[0_u32, 1])?;
228		let (normalize, ()) = runtime.capture_with_initialized_state(&[&normalized], || {
229			crate::ml::matrix::training_accumulate(
230				&normalized,
231				&advantage::normalize(&inputs[3], 1e-8)?,
232				&copy_cursor,
233				1.,
234			)
235		})?;
236		let batch = config.horizon * config.environments;
237		let mini = if config.update_minibatch_size == 0 {
238			batch
239		} else {
240			config.update_minibatch_size
241		};
242		let mut counts = vec![mini];
243		if !batch.is_multiple_of(mini) {
244			counts.push(batch % mini);
245		}
246		let mut batches = Vec::new();
247		for count in counts {
248			for p in &parameters {
249				p.clear_gradient();
250			}
251			let mutable = accumulators
252				.iter()
253				.chain(metrics.iter())
254				.collect::<Vec<_>>();
255			let (plan, ()) = runtime.capture_with_initialized_state(&mutable, || {
256				let [obs, actions, logs, adv, ret] = crate::ml::rollout::minibatch_cursor(
257					[&inputs[0], &inputs[1], &inputs[2], &normalized, &inputs[4]],
258					&cursor,
259					count,
260				)?;
261				let tape = GradientTape::new();
262				let net = model.evaluate(&obs)?;
263				let p = policy::evaluate_categorical(&net.logits, &actions, &net.value)?;
264				let l = loss::ppo(
265					&p.log_probability,
266					&logs,
267					&adv,
268					&p.value,
269					&ret,
270					&p.entropy,
271					config.loss,
272				)?;
273				let total = model.auxiliary_loss(&l.total_loss)?;
274				let weight = count as f32 / batch as f32;
275				tape.backward(&matrix::scale(&total, weight)?)?;
276				for (p, target) in parameters.iter().zip(&accumulators) {
277					let g = p
278						.gradient()
279						.ok_or_else(|| Error::failed_precondition("compiled PPO missing gradient"))?;
280					crate::ml::matrix::training_accumulate(target, &g, &cursor, 1.)?;
281				}
282				// Algorithm signals compose in-graph after the tape is consumed:
283				// K3 KL matches eager PPO (`mean(exp(r) - 1 - r)`), and strict-`>`
284				// clip fraction subtracts `== eps` from `>= eps` over `|ratio - 1|`.
285				let log_ratio = p.log_probability.sub(&logs)?;
286				let ratio = log_ratio.exp()?;
287				let approx_kl = matrix::reshape(&ratio.sub_scalar(1.0)?.sub(&log_ratio)?.mean(-1)?, [])?;
288				let deviation = ratio.sub_scalar(1.0)?.abs()?;
289				let eps = config.loss.clip_epsilon;
290				let clip_mask =
291					matrix::greater_equal(&deviation, eps)?.sub(&matrix::equal(&deviation, eps)?)?;
292				let clip_fraction = matrix::reshape(&clip_mask.mean(-1)?, [])?;
293				for (target, value) in metrics.iter().zip([
294					&total,
295					&l.policy_loss,
296					&l.value_loss,
297					&l.entropy,
298					&approx_kl,
299					&clip_fraction,
300				]) {
301					crate::ml::matrix::training_accumulate(target, value, &cursor, weight)?;
302				}
303				Ok(())
304			})?;
305			batches.push((count, plan));
306		}
307		let optimizer =
308			TrainingProgram::capture(runtime, training.update_loop_mut().adamw_mut()?, || {
309				for (p, g) in parameters.iter().zip(&accumulators) {
310					p.restore_gradient(g.clone());
311				}
312				matrix::scale(&metrics[0], 1.)
313			})?;
314		Ok(Self {
315			config: config.clone(),
316			parameters,
317			ids,
318			accumulators,
319			inputs,
320			normalize,
321			cursor,
322			metrics,
323			batches,
324			optimizer,
325			epochs: 0,
326		})
327	}
328}
329fn submit(runtime: &Runtime, plan: &ExecutionPlan, timed: bool) -> Result<Event> {
330	if timed {
331		runtime.submit_timed(plan)
332	} else {
333		runtime.submit(plan)
334	}
335}