1use super::PpoTrainerConfig;
4use crate::ml::environment::{Environment, TradingConfig, TradingEnvironment};
5use crate::ml::{ActorCritic, RolloutBuffer, RolloutTransition, policy};
6use crate::runtime::{BufferBinding, ComputeDispatch, KernelId, PushConstant, SemanticDispatch};
7use crate::{DType, Error, ExecutionPlan, Matrix, OpAttribute, Result, Runtime, matrix};
8use std::time::Duration;
9
10#[derive(Default)]
15pub struct TradingRolloutProgram {
16 state: Option<State>,
17}
18pub(super) struct CollectionOptions {
19 pub seed: u64,
20 pub check_every: u32,
21 pub shaping: f32,
22 pub continuing: bool,
23}
24struct State {
25 env: Vec<u64>,
26 rollout: Vec<u64>,
27 parameters: Vec<u64>,
28 config: TradingConfig,
29 ppo: PpoTrainerConfig,
30 shaping: f32,
31 observation: Matrix,
32 cursor: Matrix,
33 reset: ExecutionPlan,
34 resume: Option<ExecutionPlan>,
35 step: ExecutionPlan,
36 gae: ExecutionPlan,
37 replays: u64,
38}
39impl TradingRolloutProgram {
40 #[inline]
42 #[must_use]
43 pub fn new() -> Self {
44 Self::default()
45 }
46
47 pub fn replay_count(&self) -> u64 {
49 self.state.as_ref().map_or(0, |s| s.replays)
50 }
51 pub fn command_recording_count(&self) -> u64 {
53 self.state.as_ref().map_or(0, |s| {
54 s.reset.diagnostics().command_recording_count()
55 + s.step.diagnostics().command_recording_count()
56 + s.gae.diagnostics().command_recording_count()
57 + s
58 .resume
59 .as_ref()
60 .map_or(0, |p| p.diagnostics().command_recording_count())
61 })
62 }
63 pub(super) fn collect(
64 &mut self,
65 runtime: &Runtime,
66 model: &dyn ActorCritic,
67 env: &mut TradingEnvironment<'_>,
68 rollout: &mut RolloutBuffer,
69 ppo: &PpoTrainerConfig,
70 options: CollectionOptions,
71 ) -> Result<Duration> {
72 let CollectionOptions {
73 seed,
74 check_every,
75 shaping,
76 continuing,
77 } = options;
78 if !env.replay_tables_valid()
79 || !shaping.is_finite()
80 || !runtime.owns_matrix(env.observation())
81 || env.environments() as usize != ppo.environments
82 {
83 return Err(Error::invalid_argument(
84 "compiled trading collection geometry/Runtime/shaping mismatch",
85 ));
86 }
87 runtime.checkpoint()?.wait()?;
88 let reset_environment = !continuing || !env.replay_initialized();
89 if self.state.is_none() {
90 self.state = Some(State::capture(
91 runtime, model, env, rollout, ppo, shaping, continuing,
92 )?);
93 }
94 let s = self.state.as_mut().expect("compiled trading collection");
95 let mut config = env.replay_config();
96 config.seed = 0;
97 let parameters = model
98 .all_parameters()?
99 .iter()
100 .map(|p| p.data().value_id())
101 .collect::<Vec<_>>();
102 if rollout
103 .replay_slots()
104 .iter()
105 .map(|m| m.value_id())
106 .collect::<Vec<_>>()
107 != s.rollout
108 || env.replay_identity() != s.env
109 || parameters != s.parameters
110 || config != s.config
111 || s.shaping != shaping
112 || s.resume.is_some() != continuing
113 || ppo.horizon != s.ppo.horizon
114 || ppo.environments != s.ppo.environments
115 || ppo.observation_shape != s.ppo.observation_shape
116 || ppo.gae != s.ppo.gae
117 {
118 return Err(Error::failed_precondition(
119 "compiled trading collection owner/recipe changed",
120 ));
121 }
122 ppo
123 .seed
124 .checked_add(ppo.horizon as u64)
125 .ok_or_else(|| Error::resource_exhausted("collection seed exhausted"))?;
126 let action_seed = ppo
127 .seed
128 .checked_add(1)
129 .ok_or_else(|| Error::resource_exhausted("collection seed exhausted"))?;
130 s.cursor.write_values(&[
131 0_u32,
132 action_seed as u32,
133 (action_seed >> 32) as u32,
134 seed as u32,
135 (seed >> 32) as u32,
136 u32::from(!continuing && ppo.horizon == 1),
137 0,
138 ])?;
139 let reset = if reset_environment {
140 &s.reset
141 } else {
142 s.resume.as_ref().expect("continuation reset plan")
143 };
144 let mut elapsed = submit(runtime, reset, ppo.enable_gpu_timing)?;
145 env.replay_observation(s.observation.clone());
146 let mut completed = 0_usize;
147 while completed < ppo.horizon {
148 let until_check = if check_every == 0 {
149 16
150 } else {
151 check_every as usize - completed % (check_every as usize)
152 };
153 let count = (ppo.horizon - completed).min(16).min(until_check);
154 let mut events = Vec::with_capacity(count);
155 for _ in 0..count {
156 events.push(if ppo.enable_gpu_timing {
157 runtime.submit_timed(&s.step)?
158 } else {
159 runtime.submit(&s.step)?
160 });
161 }
162 events.last().expect("nonempty replay batch").wait()?;
164 if ppo.enable_gpu_timing {
165 for event in events {
166 elapsed = elapsed
167 .checked_add(event.device_duration()?)
168 .ok_or_else(|| Error::resource_exhausted("collection GPU time overflow"))?;
169 }
170 }
171 completed += count;
172 s.replays = s
173 .replays
174 .checked_add(count as u64)
175 .ok_or_else(|| Error::resource_exhausted("collection replay exhausted"))?;
176 if check_every != 0 && completed.is_multiple_of(check_every as usize) {
177 env.check_status()?;
178 }
179 }
180 elapsed = elapsed
181 .checked_add(submit(runtime, &s.gae, ppo.enable_gpu_timing)?)
182 .ok_or_else(|| Error::resource_exhausted("collection GPU time overflow"))?;
183 env.check_status()?;
184 if s.cursor.read::<u32>()?[6] != ppo.horizon as u32 {
185 return Err(Error::failed_precondition(
186 "compiled rollout append cursor did not advance",
187 ));
188 }
189 rollout.finish_replayed_collection();
190 Ok(elapsed)
191 }
192}
193impl State {
194 fn capture(
195 runtime: &Runtime,
196 model: &dyn ActorCritic,
197 env: &mut TradingEnvironment<'_>,
198 rollout: &mut RolloutBuffer,
199 ppo: &PpoTrainerConfig,
200 shaping: f32,
201 continuing: bool,
202 ) -> Result<Self> {
203 rollout.initialize_replay_storage()?;
204 let cursor = Matrix::new_from_slice_on(runtime, [7], &[0_u32, 1, 0, 1, 0, 0, 0])?;
205 let copy_cursor = Matrix::new_from_slice_on(runtime, [2], &[0_u32, 1])?;
206 let observation = env.observation().clone();
207 let observation_elements = ppo
208 .observation_shape
209 .iter()
210 .try_fold(1_usize, |count, extent| count.checked_mul(*extent))
211 .ok_or_else(|| Error::resource_exhausted("rollout observation size overflows usize"))?;
212 let observation_count = ppo
213 .environments
214 .checked_mul(observation_elements)
215 .ok_or_else(|| Error::resource_exhausted("rollout observation count overflows usize"))?;
216 let next_observation_rows = ppo
220 .horizon
221 .checked_mul(ppo.environments)
222 .ok_or_else(|| Error::resource_exhausted("rollout rows overflow usize"))?;
223 let next_observations = Matrix::allocate(
224 &runtime.handle(),
225 vec![next_observation_rows, observation_elements],
226 next_observation_rows
227 .checked_mul(observation_elements)
228 .ok_or_else(|| {
229 Error::resource_exhausted("rollout next_observation storage overflows usize")
230 })?,
231 DType::F32,
232 )?;
233 let initialized = env
234 .replay_slots()
235 .into_iter()
236 .chain(rollout.replay_slots())
237 .chain(std::iter::once(&cursor))
238 .chain(std::iter::once(&next_observations))
239 .cloned()
240 .collect::<Vec<_>>();
241 let state = initialized.iter().collect::<Vec<_>>();
242 let (reset, ()) = runtime.capture_with_initialized_state(&state, || {
243 rollout.reset_replay_commands()?;
244 env.reset_replay_commands(false, &cursor)
245 })?;
246 env.replay_observation(observation.clone());
247 let resume = if continuing {
248 Some(
249 runtime
250 .capture_with_initialized_state(&state, || rollout.reset_replay_commands())?
251 .0,
252 )
253 } else {
254 None
255 };
256 let (step, ()) = runtime.capture_with_initialized_state(&state, || {
257 let network = model.evaluate(&observation)?;
258 let action = crate::ml::matrix::sample_categorical_cursor(&network.logits, &cursor)?;
259 let policy = policy::evaluate_categorical(&network.logits, &action, &network.value)?;
260 let step = env.step_replay_commands(&action, &cursor)?;
261 let reward = if shaping != 0. {
262 matrix::add_scalar(step.reward(), shaping)?
263 } else {
264 step.reward().clone()
265 };
266 rollout.append_replay(
270 &RolloutTransition::new(
271 step.observation().clone(),
272 action,
273 reward,
274 policy.value.clone(),
275 policy.value,
276 policy.log_probability,
277 step.terminated().clone(),
278 step.truncated().clone(),
279 ),
280 &cursor,
281 )?;
282 crate::ml::rollout::next_observation_append(
283 step.next_observation(),
284 &next_observations,
285 &cursor,
286 0,
287 observation_count,
288 )?;
289 env.reset_replay_commands(true, &cursor)?;
290 crate::ml::matrix::training_accumulate(&observation, env.observation(), ©_cursor, 1.)?;
291 advance_cursor(runtime, &cursor, ppo.horizon as u32, continuing)
292 })?;
293 env.replay_observation(observation.clone());
294 let (gae, ()) = runtime.capture_with_initialized_state(&state, || {
295 let network = model.evaluate(&next_observations)?;
300 crate::ml::matrix::training_accumulate(
301 rollout.batch().next_value(),
302 &network
303 .value
304 .reshape_view(vec![ppo.horizon, ppo.environments])?,
305 ©_cursor,
306 1.,
307 )?;
308 rollout.finalize_replay_commands(ppo.gae)
309 })?;
310 let mut config = env.replay_config();
311 config.seed = 0;
312 Ok(Self {
313 env: env.replay_identity(),
314 rollout: rollout
315 .replay_slots()
316 .iter()
317 .map(|m| m.value_id())
318 .collect(),
319 parameters: model
320 .all_parameters()?
321 .iter()
322 .map(|p| p.data().value_id())
323 .collect(),
324 config,
325 ppo: ppo.clone(),
326 shaping,
327 observation,
328 cursor,
329 reset,
330 resume,
331 step,
332 gae,
333 replays: 0,
334 })
335 }
336}
337fn submit(runtime: &Runtime, plan: &ExecutionPlan, timed: bool) -> Result<Duration> {
338 if timed {
339 runtime.submit_timed(plan)?.device_duration()
340 } else {
341 runtime.submit(plan)?.wait()?;
342 Ok(Duration::ZERO)
343 }
344}
345
346fn advance_cursor(
347 runtime: &Runtime,
348 cursor: &Matrix,
349 horizon: u32,
350 continuing: bool,
351) -> Result<()> {
352 runtime.handle().record_semantic(
353 ComputeDispatch {
354 kernel: KernelId::MlTradingCursorAdvanceU32,
355 buffers: &[BufferBinding::read_write(cursor.storage())],
356 push_constants: &[
357 PushConstant::U32(horizon),
358 PushConstant::U32(u32::from(continuing)),
359 ],
360 workgroups: [1, 1, 1],
361 indirect: None,
362 },
363 SemanticDispatch {
364 contract: crate::core::operation::ml::TRADING_CURSOR_ADVANCE,
365 inputs: &[cursor],
366 outputs: &[cursor],
367 attributes: &[
368 OpAttribute::UnsignedInteger {
369 name: "horizon".into(),
370 value: u64::from(horizon),
371 },
372 OpAttribute::Boolean {
373 name: "continuing".into(),
374 value: continuing,
375 },
376 ],
377 },
378 )
379}