1use 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
29pub enum RolloutTrainingPhase {
30 Collect,
32 Update,
34 Complete,
36}
37
38#[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 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 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 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 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 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 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 pub fn is_done(&self) -> bool {
274 self.phase == RolloutTrainingPhase::Complete || self.updates.stop_requested()
275 }
276
277 pub const fn phase(&self) -> RolloutTrainingPhase {
279 self.phase
280 }
281
282 pub const fn rollout_index(&self) -> u64 {
284 self.rollout_index
285 }
286
287 pub const fn update_epoch(&self) -> u64 {
289 self.update_epoch
290 }
291
292 pub const fn config(&self) -> &RolloutTrainingConfig {
294 &self.config
295 }
296
297 pub const fn update_loop(&self) -> &Training<'runtime, 'hooks> {
299 &self.updates
300 }
301
302 pub fn update_loop_mut(&mut self) -> &mut Training<'runtime, 'hooks> {
304 &mut self.updates
305 }
306
307 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}