1use super::PpoTrainerConfig;
9use crate::ml::environment::CompiledEnvironment;
10use crate::ml::{ActorCritic, RolloutBuffer, RolloutTransition, policy};
11use crate::runtime::{BufferBinding, ComputeDispatch, KernelId, PushConstant, SemanticDispatch};
12use crate::{
13 DType, Error, ExecutionPlan, ExecutionPlanDiagnostics, Matrix, OpAttribute, Result, Runtime,
14 matrix,
15};
16use std::time::Duration;
17
18#[derive(Clone, Copy, Debug, PartialEq)]
20pub struct CompiledCollectionOptions {
21 pub seed: u64,
23 pub check_every: u32,
25 pub shaping: f32,
27 pub continuing: bool,
29}
30
31pub struct CompiledRollout {
34 state: Option<State>,
35}
36
37#[derive(Clone, Copy, Debug)]
43pub struct CompiledRolloutDiagnostics {
44 reset: ExecutionPlanDiagnostics,
45 resume: Option<ExecutionPlanDiagnostics>,
46 step: ExecutionPlanDiagnostics,
47 gae: ExecutionPlanDiagnostics,
48}
49
50impl CompiledRolloutDiagnostics {
51 pub const fn reset(self) -> ExecutionPlanDiagnostics {
53 self.reset
54 }
55
56 pub const fn resume(self) -> Option<ExecutionPlanDiagnostics> {
58 self.resume
59 }
60
61 pub const fn step(self) -> ExecutionPlanDiagnostics {
63 self.step
64 }
65
66 pub const fn gae(self) -> ExecutionPlanDiagnostics {
68 self.gae
69 }
70}
71
72struct State {
73 env: Vec<u64>,
74 rollout: Vec<u64>,
75 parameters: Vec<u64>,
76 ppo: PpoTrainerConfig,
77 shaping: f32,
78 observation: Matrix,
79 cursor: Matrix,
80 reset: ExecutionPlan,
81 resume: Option<ExecutionPlan>,
82 step: ExecutionPlan,
83 gae: ExecutionPlan,
84 replays: u64,
85}
86
87impl CompiledRollout {
88 pub const fn new() -> Self {
90 Self { state: None }
91 }
92
93 pub fn replay_count(&self) -> u64 {
95 self.state.as_ref().map_or(0, |state| state.replays)
96 }
97
98 pub fn command_recording_count(&self) -> u64 {
100 self.state.as_ref().map_or(0, |s| {
101 s.reset.diagnostics().command_recording_count()
102 + s.step.diagnostics().command_recording_count()
103 + s.gae.diagnostics().command_recording_count()
104 + s
105 .resume
106 .as_ref()
107 .map_or(0, |p| p.diagnostics().command_recording_count())
108 })
109 }
110
111 pub fn diagnostics(&self) -> Option<CompiledRolloutDiagnostics> {
114 self.state.as_ref().map(|state| CompiledRolloutDiagnostics {
115 reset: state.reset.diagnostics(),
116 resume: state.resume.as_ref().map(|plan| plan.diagnostics()),
117 step: state.step.diagnostics(),
118 gae: state.gae.diagnostics(),
119 })
120 }
121
122 pub fn collect<E: CompiledEnvironment>(
133 &mut self,
134 runtime: &Runtime,
135 model: &dyn ActorCritic,
136 env: &mut E,
137 rollout: &mut RolloutBuffer,
138 ppo: &PpoTrainerConfig,
139 options: CompiledCollectionOptions,
140 ) -> Result<Duration> {
141 let CompiledCollectionOptions {
142 seed,
143 check_every,
144 shaping,
145 continuing,
146 } = options;
147 if !env.replay_valid()
148 || !shaping.is_finite()
149 || !runtime.owns_matrix(env.observation())
150 || env.environments() as usize != ppo.environments
151 {
152 return Err(Error::invalid_argument(
153 "compiled collection geometry/Runtime/shaping mismatch",
154 ));
155 }
156 runtime.checkpoint()?.wait()?;
157 let reset_environment = !continuing || !env.replay_initialized();
158 if self.state.is_none() {
159 self.state = Some(State::capture(
160 runtime, model, env, rollout, ppo, shaping, continuing,
161 )?);
162 }
163 let s = self.state.as_mut().expect("compiled collection state");
164 let parameters = model
165 .all_parameters()?
166 .iter()
167 .map(|p| p.data().value_id())
168 .collect::<Vec<_>>();
169 if rollout
170 .replay_slots()
171 .iter()
172 .map(|m| m.value_id())
173 .collect::<Vec<_>>()
174 != s.rollout
175 || env.replay_identity() != s.env
176 || parameters != s.parameters
177 || s.shaping != shaping
178 || s.resume.is_some() != continuing
179 || ppo.horizon != s.ppo.horizon
180 || ppo.environments != s.ppo.environments
181 || ppo.observation_shape != s.ppo.observation_shape
182 || ppo.gae != s.ppo.gae
183 {
184 return Err(Error::failed_precondition(
185 "compiled collection owner/recipe changed",
186 ));
187 }
188 ppo
189 .seed
190 .checked_add(ppo.horizon as u64)
191 .ok_or_else(|| Error::resource_exhausted("collection seed exhausted"))?;
192 let action_seed = ppo
193 .seed
194 .checked_add(1)
195 .ok_or_else(|| Error::resource_exhausted("collection seed exhausted"))?;
196 s.cursor.write_values(&[
197 0_u32,
198 action_seed as u32,
199 (action_seed >> 32) as u32,
200 seed as u32,
201 (seed >> 32) as u32,
202 u32::from(!continuing && ppo.horizon == 1),
203 0,
204 ])?;
205 let reset = if reset_environment {
206 &s.reset
207 } else {
208 s.resume.as_ref().expect("continuation reset plan")
209 };
210 let mut elapsed = submit(runtime, reset, ppo.enable_gpu_timing)?;
211 env.replay_observation(s.observation.clone());
212 let mut completed = 0_usize;
213 while completed < ppo.horizon {
214 let until_check = if check_every == 0 {
215 16
216 } else {
217 check_every as usize - completed % (check_every as usize)
218 };
219 let count = (ppo.horizon - completed).min(16).min(until_check);
220 let mut events = Vec::with_capacity(count);
221 for _ in 0..count {
222 events.push(if ppo.enable_gpu_timing {
223 runtime.submit_timed(&s.step)?
224 } else {
225 runtime.submit(&s.step)?
226 });
227 }
228 events.last().expect("nonempty replay batch").wait()?;
230 if ppo.enable_gpu_timing {
231 for event in events {
232 elapsed = elapsed
233 .checked_add(event.device_duration()?)
234 .ok_or_else(|| Error::resource_exhausted("collection GPU time overflow"))?;
235 }
236 }
237 completed += count;
238 s.replays = s
239 .replays
240 .checked_add(count as u64)
241 .ok_or_else(|| Error::resource_exhausted("collection replay exhausted"))?;
242 if check_every != 0 && completed.is_multiple_of(check_every as usize) {
243 env.check_status()?;
244 }
245 }
246 elapsed = elapsed
247 .checked_add(submit(runtime, &s.gae, ppo.enable_gpu_timing)?)
248 .ok_or_else(|| Error::resource_exhausted("collection GPU time overflow"))?;
249 env.check_status()?;
250 if s.cursor.read::<u32>()?[6] != ppo.horizon as u32 {
251 return Err(Error::failed_precondition(
252 "compiled rollout append cursor did not advance",
253 ));
254 }
255 rollout.finish_replayed_collection();
256 Ok(elapsed)
257 }
258}
259
260impl Default for CompiledRollout {
261 fn default() -> Self {
262 Self::new()
263 }
264}
265
266impl State {
267 fn capture<E: CompiledEnvironment>(
268 runtime: &Runtime,
269 model: &dyn ActorCritic,
270 env: &mut E,
271 rollout: &mut RolloutBuffer,
272 ppo: &PpoTrainerConfig,
273 shaping: f32,
274 continuing: bool,
275 ) -> Result<Self> {
276 rollout.initialize_replay_storage()?;
277 let cursor = Matrix::new_from_slice_on(runtime, [7], &[0_u32, 1, 0, 1, 0, 0, 0])?;
278 let copy_cursor = Matrix::new_from_slice_on(runtime, [2], &[0_u32, 1])?;
279 let observation = env.observation().clone();
280 let observation_elements = ppo
281 .observation_shape
282 .iter()
283 .try_fold(1_usize, |count, extent| count.checked_mul(*extent))
284 .ok_or_else(|| Error::resource_exhausted("rollout observation size overflows usize"))?;
285 let observation_count = ppo
286 .environments
287 .checked_mul(observation_elements)
288 .ok_or_else(|| Error::resource_exhausted("rollout observation count overflows usize"))?;
289 let next_observation_rows = ppo
293 .horizon
294 .checked_mul(ppo.environments)
295 .ok_or_else(|| Error::resource_exhausted("rollout rows overflow usize"))?;
296 let next_observations = Matrix::allocate(
297 &runtime.handle(),
298 vec![next_observation_rows, observation_elements],
299 next_observation_rows
300 .checked_mul(observation_elements)
301 .ok_or_else(|| {
302 Error::resource_exhausted("rollout next_observation storage overflows usize")
303 })?,
304 DType::F32,
305 )?;
306 let initialized = env
307 .replay_slots()
308 .into_iter()
309 .chain(rollout.replay_slots())
310 .chain(std::iter::once(&cursor))
311 .chain(std::iter::once(&next_observations))
312 .cloned()
313 .collect::<Vec<_>>();
314 let state = initialized.iter().collect::<Vec<_>>();
315 let (reset, ()) = runtime.capture_with_initialized_state(&state, || {
316 rollout.reset_replay_commands()?;
317 env.record_reset_replay(false, &cursor)
318 })?;
319 env.replay_observation(observation.clone());
320 let resume = if continuing {
321 Some(
322 runtime
323 .capture_with_initialized_state(&state, || rollout.reset_replay_commands())?
324 .0,
325 )
326 } else {
327 None
328 };
329 let (step, ()) = runtime.capture_with_initialized_state(&state, || {
330 let network = model.evaluate(&observation)?;
331 let action = crate::ml::matrix::sample_categorical_cursor(&network.logits, &cursor)?;
332 let policy = policy::evaluate_categorical(&network.logits, &action, &network.value)?;
333 let step = env.record_step_replay(&action, &cursor)?;
334 let reward = if shaping != 0. {
335 matrix::add_scalar(step.reward(), shaping)?
336 } else {
337 step.reward().clone()
338 };
339 rollout.append_replay(
343 &RolloutTransition::new(
344 step.observation().clone(),
345 action,
346 reward,
347 policy.value.clone(),
348 policy.value,
349 policy.log_probability,
350 step.terminated().clone(),
351 step.truncated().clone(),
352 ),
353 &cursor,
354 )?;
355 crate::ml::rollout::next_observation_append(
356 step.next_observation(),
357 &next_observations,
358 &cursor,
359 0,
360 observation_count,
361 )?;
362 env.record_reset_replay(true, &cursor)?;
363 crate::ml::matrix::training_accumulate(&observation, env.observation(), ©_cursor, 1.)?;
364 advance_cursor(runtime, &cursor, ppo.horizon as u32, continuing)
365 })?;
366 env.replay_observation(observation.clone());
367 let (gae, ()) = runtime.capture_with_initialized_state(&state, || {
368 let network = model.evaluate(&next_observations)?;
373 crate::ml::matrix::training_accumulate(
374 rollout.batch().next_value(),
375 &network
376 .value
377 .reshape_view(vec![ppo.horizon, ppo.environments])?,
378 ©_cursor,
379 1.,
380 )?;
381 rollout.finalize_replay_commands(ppo.gae)
382 })?;
383 Ok(Self {
384 env: env.replay_identity(),
385 rollout: rollout
386 .replay_slots()
387 .iter()
388 .map(|m| m.value_id())
389 .collect(),
390 parameters: model
391 .all_parameters()?
392 .iter()
393 .map(|p| p.data().value_id())
394 .collect(),
395 ppo: ppo.clone(),
396 shaping,
397 observation,
398 cursor,
399 reset,
400 resume,
401 step,
402 gae,
403 replays: 0,
404 })
405 }
406}
407
408fn submit(runtime: &Runtime, plan: &ExecutionPlan, timed: bool) -> Result<Duration> {
409 if timed {
410 runtime.submit_timed(plan)?.device_duration()
411 } else {
412 runtime.submit(plan)?.wait()?;
413 Ok(Duration::ZERO)
414 }
415}
416
417fn advance_cursor(
418 runtime: &Runtime,
419 cursor: &Matrix,
420 horizon: u32,
421 continuing: bool,
422) -> Result<()> {
423 runtime.handle().record_semantic(
426 ComputeDispatch {
427 kernel: KernelId::MlTradingCursorAdvanceU32,
428 buffers: &[BufferBinding::read_write(cursor.storage())],
429 push_constants: &[
430 PushConstant::U32(horizon),
431 PushConstant::U32(u32::from(continuing)),
432 ],
433 workgroups: [1, 1, 1],
434 indirect: None,
435 },
436 SemanticDispatch {
437 contract: crate::core::operation::ml::TRADING_CURSOR_ADVANCE,
438 inputs: &[cursor],
439 outputs: &[cursor],
440 attributes: &[
441 OpAttribute::UnsignedInteger {
442 name: "horizon".into(),
443 value: u64::from(horizon),
444 },
445 OpAttribute::Boolean {
446 name: "continuing".into(),
447 value: continuing,
448 },
449 ],
450 },
451 )
452}