Skip to main content

oa/ml/training/
rollout.rs

1//! Two-phase collection/update lifecycle for synchronous on-policy training.
2//!
3//! Port provenance: OA C++ `oa/ml/itRolloutTraining.{h,cpp}`. This coordinator
4//! composes one [`Training`] optimizer lifecycle and never owns environment
5//! execution or another runtime. The device-resident rollout storage it
6//! drives lives in [`crate::ml::rl::rollout`].
7
8use crate::{Error, Matrix, Result, Runtime};
9
10use super::{Optimizer, Training, TrainingConfig, TrainingSnapshot};
11pub use crate::ml::types::RolloutTrainingConfig;
12use crate::ml::{RolloutBuffer, advantage::GaeConfig};
13
14impl Default for RolloutTrainingConfig {
15	fn default() -> Self {
16		Self {
17			rollouts: 0,
18			horizon: 0,
19			environments: 0,
20			update_epochs: 0,
21			timer_name: "rl_update".into(),
22			enable_gpu_timing: false,
23		}
24	}
25}
26
27/// Current phase of one synchronous on-policy schedule.
28#[derive(Clone, Copy, Debug, PartialEq, Eq)]
29pub enum RolloutTrainingPhase {
30	/// Caller is collecting environment transitions.
31	Collect,
32	/// Caller is performing optimizer passes over the finalized rollout.
33	Update,
34	/// Every configured rollout/update pair has completed or stopped.
35	Complete,
36}
37
38/// Coordinator for alternating fixed-capacity collection and optimizer phases.
39#[must_use]
40pub struct RolloutTraining<'runtime, 'hooks> {
41	config: RolloutTrainingConfig,
42	updates: Training<'runtime, 'hooks>,
43	phase: RolloutTrainingPhase,
44	rollout_index: u64,
45	update_epoch: u64,
46	rollout_open: bool,
47	update_body_pending: bool,
48	active_rollout: Option<*const RolloutBuffer>,
49}
50
51impl<'runtime, 'hooks> RolloutTraining<'runtime, 'hooks> {
52	/// Construct a checked rollout lifecycle around one optimizer.
53	///
54	/// # Errors
55	///
56	/// Returns an error for zero schedule dimensions, count overflow, or
57	/// optimizer/runtime ownership mismatch.
58	pub fn new(
59		runtime: &'runtime Runtime,
60		optimizer: &'runtime mut dyn Optimizer,
61		config: RolloutTrainingConfig,
62	) -> Result<Self> {
63		let updates = Training::new_eager(runtime, optimizer, update_config(&config)?)?;
64		Ok(Self::new_with_updates(config, updates))
65	}
66	pub(super) fn new_compiled(
67		runtime: &'runtime Runtime,
68		optimizer: &'runtime mut super::AdamW,
69		config: RolloutTrainingConfig,
70	) -> Result<Self> {
71		let updates = Training::new(runtime, optimizer, update_config(&config)?)?;
72		Ok(Self::new_with_updates(config, updates))
73	}
74	fn new_with_updates(config: RolloutTrainingConfig, updates: Training<'runtime, 'hooks>) -> Self {
75		Self {
76			config,
77			updates,
78			phase: RolloutTrainingPhase::Collect,
79			rollout_index: 0,
80			update_epoch: 0,
81			rollout_open: false,
82			update_body_pending: false,
83			active_rollout: None,
84		}
85	}
86
87	/// Reset and open one matching rollout buffer for collection.
88	///
89	/// # Errors
90	///
91	/// Returns an error outside the idle Collect phase, for mismatched geometry,
92	/// or when device-side validity reset cannot be recorded.
93	pub fn begin_rollout(&mut self, rollout: &mut RolloutBuffer) -> Result<()> {
94		self.begin_rollout_impl(rollout, false)
95	}
96	pub(super) fn begin_replayed_rollout(&mut self, rollout: &mut RolloutBuffer) -> Result<()> {
97		self.begin_rollout_impl(rollout, true)
98	}
99	fn begin_rollout_impl(&mut self, rollout: &mut RolloutBuffer, replayed: bool) -> Result<()> {
100		if self.phase != RolloutTrainingPhase::Collect || self.rollout_open || self.update_body_pending
101		{
102			return Err(Error::failed_precondition(
103				"begin_rollout requires an idle Collect phase",
104			));
105		}
106		if rollout.config().time != self.config.horizon
107			|| rollout.config().environments != self.config.environments
108		{
109			return Err(Error::invalid_argument(
110				"rollout buffer geometry does not match training configuration",
111			));
112		}
113		if replayed {
114			rollout.reset_control();
115		} else {
116			rollout.reset()?;
117		}
118		self.rollout_open = true;
119		self.active_rollout = Some(std::ptr::from_ref(rollout));
120		Ok(())
121	}
122
123	/// Finalize the full active rollout with GAE and enter Update.
124	///
125	/// # Errors
126	///
127	/// Returns an error for the wrong phase/buffer, incomplete collection, or
128	/// GAE recording failure.
129	pub fn finalize_rollout(&mut self, rollout: &mut RolloutBuffer, config: GaeConfig) -> Result<()> {
130		if self.phase != RolloutTrainingPhase::Collect
131			|| !self.rollout_open
132			|| self.update_body_pending
133			|| !self.active_is(rollout)
134		{
135			return Err(Error::failed_precondition(
136				"finalize_rollout requires the active Collect buffer",
137			));
138		}
139		rollout.finalize(config)?;
140		self.rollout_open = false;
141		self.phase = RolloutTrainingPhase::Update;
142		self.update_epoch = 0;
143		Ok(())
144	}
145
146	/// Restore Collect control state after the enclosing command transaction aborts.
147	///
148	/// This is valid from `begin_rollout` through finalization until the first
149	/// update begins. It changes host visibility only; the caller must already
150	/// have rejected/aborted the unsubmitted Runtime recording.
151	///
152	/// # Errors
153	///
154	/// Returns an error for another buffer or after any update began.
155	pub fn abort_rollout(&mut self, rollout: &mut RolloutBuffer) -> Result<()> {
156		let open = self.phase == RolloutTrainingPhase::Collect && self.rollout_open;
157		let finalized =
158			self.phase == RolloutTrainingPhase::Update && !self.rollout_open && self.update_epoch == 0;
159		if (!open && !finalized) || self.update_body_pending || !self.active_is(rollout) {
160			return Err(Error::failed_precondition(
161				"abort_rollout requires an unsubmitted collection before its first update",
162			));
163		}
164		rollout.abort_unsubmitted();
165		self.rollout_open = false;
166		self.update_body_pending = false;
167		self.active_rollout = None;
168		self.phase = RolloutTrainingPhase::Collect;
169		self.update_epoch = 0;
170		Ok(())
171	}
172
173	/// Begin one optimizer epoch over the active finalized rollout.
174	///
175	/// Returns `false` for a stopped/paused/completed underlying iterator.
176	///
177	/// # Errors
178	///
179	/// Returns an error outside Update, for a duplicate begin, or from lifecycle
180	/// callbacks.
181	pub fn begin_update(&mut self) -> Result<bool> {
182		if self.phase != RolloutTrainingPhase::Update
183			|| self.update_body_pending
184			|| self.update_epoch >= self.config.update_epochs
185		{
186			return Err(Error::failed_precondition(
187				"begin_update requires an idle Update phase",
188			));
189		}
190		if !self.updates.begin_step()? {
191			if self.updates.stop_requested() {
192				self.phase = RolloutTrainingPhase::Complete;
193			}
194			return Ok(false);
195		}
196		self.update_body_pending = true;
197		self.active_rollout = None;
198		Ok(true)
199	}
200
201	/// Complete one previously begun update and advance the phase schedule.
202	///
203	/// # Errors
204	///
205	/// Returns an error without a matching begin or from optimizer, completion,
206	/// metric, callback, and loss validation.
207	pub fn complete_update(&mut self, loss: &Matrix) -> Result<()> {
208		self.complete_update_with_device_prefix(loss, std::time::Duration::ZERO)
209	}
210
211	pub(super) fn complete_update_with_device_prefix(
212		&mut self,
213		loss: &Matrix,
214		device_prefix: std::time::Duration,
215	) -> Result<()> {
216		if self.phase != RolloutTrainingPhase::Update || !self.update_body_pending {
217			return Err(Error::failed_precondition(
218				"complete_update requires a preceding begin_update",
219			));
220		}
221		if let Err(error) = self
222			.updates
223			.complete_step_with_device_prefix(loss, device_prefix)
224		{
225			self.update_body_pending = false;
226			self.phase = RolloutTrainingPhase::Complete;
227			return Err(error);
228		}
229		self.advance_update();
230		Ok(())
231	}
232
233	pub(super) fn complete_compiled_update(
234		&mut self,
235		program: &mut super::TrainingProgram,
236		prefix: std::time::Duration,
237	) -> Result<()> {
238		if !self.update_body_pending {
239			return Err(Error::failed_precondition(
240				"compiled update requires begin_update",
241			));
242		}
243		self
244			.updates
245			.complete_program_step_with_device_prefix(program, prefix)?;
246		self.advance_update();
247		Ok(())
248	}
249
250	fn advance_update(&mut self) {
251		self.update_body_pending = false;
252		self.update_epoch += 1;
253		if self.update_epoch == self.config.update_epochs {
254			self.rollout_index += 1;
255			self.phase = if self.rollout_index == self.config.rollouts {
256				RolloutTrainingPhase::Complete
257			} else {
258				RolloutTrainingPhase::Collect
259			};
260		}
261	}
262
263	pub(super) fn fail_update<T>(&mut self, error: Error) -> Result<T> {
264		if !self.update_body_pending {
265			return Err(error);
266		}
267		self.update_body_pending = false;
268		self.phase = RolloutTrainingPhase::Complete;
269		self.updates.fail_composed_step(error)
270	}
271
272	/// Return whether collection/update work has completed or stopped.
273	pub fn is_done(&self) -> bool {
274		self.phase == RolloutTrainingPhase::Complete || self.updates.stop_requested()
275	}
276
277	/// Return the current two-phase state.
278	pub const fn phase(&self) -> RolloutTrainingPhase {
279		self.phase
280	}
281
282	/// Return the number of fully updated rollouts.
283	pub const fn rollout_index(&self) -> u64 {
284		self.rollout_index
285	}
286
287	/// Return completed update epochs in the current rollout.
288	pub const fn update_epoch(&self) -> u64 {
289		self.update_epoch
290	}
291
292	/// Return the immutable schedule.
293	pub const fn config(&self) -> &RolloutTrainingConfig {
294		&self.config
295	}
296
297	/// Borrow the ordinary optimizer-update lifecycle.
298	pub const fn update_loop(&self) -> &Training<'runtime, 'hooks> {
299		&self.updates
300	}
301
302	/// Mutably borrow the ordinary optimizer-update lifecycle between steps.
303	pub fn update_loop_mut(&mut self) -> &mut Training<'runtime, 'hooks> {
304		&mut self.updates
305	}
306
307	/// Finish the completed two-phase lifecycle and fire terminal callbacks.
308	///
309	/// # Errors
310	///
311	/// Returns an error before completion or with a pending update body.
312	pub fn finish(self) -> Result<TrainingSnapshot> {
313		if !self.is_done() || self.update_body_pending {
314			return Err(Error::failed_precondition(
315				"rollout training finish requires the Complete phase",
316			));
317		}
318		self.updates.finish()
319	}
320
321	fn active_is(&self, rollout: &RolloutBuffer) -> bool {
322		self
323			.active_rollout
324			.is_some_and(|active| std::ptr::eq(active, std::ptr::from_ref(rollout)))
325	}
326}
327
328fn update_config(config: &RolloutTrainingConfig) -> Result<TrainingConfig> {
329	if config.rollouts == 0
330		|| config.horizon == 0
331		|| config.environments == 0
332		|| config.update_epochs == 0
333	{
334		return Err(Error::invalid_argument(
335			"rollout training requires nonzero dimensions",
336		));
337	}
338	let batch = config
339		.horizon
340		.checked_mul(config.environments)
341		.ok_or_else(|| Error::resource_exhausted("rollout training batch overflow"))?;
342	let total_steps = config
343		.rollouts
344		.checked_mul(config.update_epochs)
345		.ok_or_else(|| Error::resource_exhausted("rollout update count overflow"))?;
346	Ok(TrainingConfig {
347		total_steps,
348		steps_per_epoch: config.update_epochs,
349		batch_size: u64::try_from(batch)
350			.map_err(|_| Error::resource_exhausted("rollout batch exceeds u64"))?,
351		timer_name: config.timer_name.clone(),
352		enable_gpu_timing: config.enable_gpu_timing,
353		..TrainingConfig::default()
354	})
355}