Skip to main content

oa/ml/rl/
rollout.rs

1//! Fixed-capacity device-resident on-policy rollout storage.
2//!
3//! This is the storage primitive. The two-phase collect/update lifecycle
4//! coordinator that fills it lives in [`crate::ml::training::RolloutTraining`].
5
6use crate::runtime::ComputeDispatch;
7use crate::runtime::SemanticDispatch;
8use crate::runtime::{BufferBinding, KernelId, PushConstant};
9use crate::{DType, Error, Matrix, OpAttribute, Result, Runtime};
10
11use super::advantage;
12pub use crate::ml::types::RolloutConfig;
13use crate::ml::validation::shader_u32;
14
15/// One vector-environment transition whose values remain device-resident.
16#[derive(Clone)]
17pub struct RolloutTransition {
18	observation: Matrix,
19	action: Matrix,
20	reward: Matrix,
21	value: Matrix,
22	next_value: Matrix,
23	log_probability: Matrix,
24	terminated: Matrix,
25	truncated: Matrix,
26}
27
28impl RolloutTransition {
29	/// Construct one categorical vector-environment transition.
30	///
31	/// Shape, dtype, and runtime compatibility are checked by
32	/// [`RolloutBuffer::append`] against that buffer's configuration.
33	#[allow(
34		clippy::too_many_arguments,
35		reason = "the transition carrier keeps all eight donor rollout fields explicit"
36	)]
37	pub fn new(
38		observation: Matrix,
39		action: Matrix,
40		reward: Matrix,
41		value: Matrix,
42		next_value: Matrix,
43		log_probability: Matrix,
44		terminated: Matrix,
45		truncated: Matrix,
46	) -> Self {
47		Self {
48			observation,
49			action,
50			reward,
51			value,
52			next_value,
53			log_probability,
54			terminated,
55			truncated,
56		}
57	}
58
59	/// Return the batched observation.
60	pub const fn observation(&self) -> &Matrix {
61		&self.observation
62	}
63
64	/// Return the categorical action indices.
65	pub const fn action(&self) -> &Matrix {
66		&self.action
67	}
68
69	/// Return the rewards.
70	pub const fn reward(&self) -> &Matrix {
71		&self.reward
72	}
73
74	/// Return the estimated values.
75	pub const fn value(&self) -> &Matrix {
76		&self.value
77	}
78
79	/// Return the estimated values after each transition.
80	pub const fn next_value(&self) -> &Matrix {
81		&self.next_value
82	}
83
84	/// Return the action log probabilities under the collecting policy.
85	pub const fn log_probability(&self) -> &Matrix {
86		&self.log_probability
87	}
88
89	/// Return the environment termination mask.
90	pub const fn terminated(&self) -> &Matrix {
91		&self.terminated
92	}
93
94	/// Return the environment truncation mask.
95	pub const fn truncated(&self) -> &Matrix {
96		&self.truncated
97	}
98}
99
100/// Time-major matrices retained by one [`RolloutBuffer`].
101pub struct RolloutBatch {
102	observation: Matrix,
103	action: Matrix,
104	reward: Matrix,
105	value: Matrix,
106	next_value: Matrix,
107	old_log_probability: Matrix,
108	terminated: Matrix,
109	truncated: Matrix,
110	valid: Matrix,
111	advantage: Matrix,
112	returns: Matrix,
113}
114
115impl RolloutBatch {
116	/// Return observations shaped `[time, environments, ...observation_shape]`.
117	pub const fn observation(&self) -> &Matrix {
118		&self.observation
119	}
120
121	/// Return categorical actions shaped `[time, environments]`.
122	pub const fn action(&self) -> &Matrix {
123		&self.action
124	}
125
126	/// Return rewards shaped `[time, environments]`.
127	pub const fn reward(&self) -> &Matrix {
128		&self.reward
129	}
130
131	/// Return values shaped `[time, environments]`.
132	pub const fn value(&self) -> &Matrix {
133		&self.value
134	}
135
136	/// Return next values shaped `[time, environments]`.
137	pub const fn next_value(&self) -> &Matrix {
138		&self.next_value
139	}
140
141	/// Return collection-policy log probabilities shaped `[time, environments]`.
142	pub const fn old_log_probability(&self) -> &Matrix {
143		&self.old_log_probability
144	}
145
146	/// Return termination flags shaped `[time, environments]`.
147	pub const fn terminated(&self) -> &Matrix {
148		&self.terminated
149	}
150
151	/// Return truncation flags shaped `[time, environments]`.
152	pub const fn truncated(&self) -> &Matrix {
153		&self.truncated
154	}
155
156	/// Return the slot-validity mask shaped `[time, environments]`.
157	pub const fn valid(&self) -> &Matrix {
158		&self.valid
159	}
160
161	/// Return generalized advantages shaped `[time, environments]`.
162	pub const fn advantage(&self) -> &Matrix {
163		&self.advantage
164	}
165
166	/// Return value targets shaped `[time, environments]`.
167	pub const fn returns(&self) -> &Matrix {
168		&self.returns
169	}
170}
171
172/// Stateful fixed-capacity owner for one categorical on-policy rollout.
173///
174/// Appends, validity reset, and final GAE are recorded on the owning runtime;
175/// host observation remains the explicit submit-and-wait boundary. Storage is
176/// allocated once and overwritten in place across completed collection cycles.
177pub struct RolloutBuffer {
178	config: RolloutConfig,
179	batch: RolloutBatch,
180	observation_elements: u32,
181	size: usize,
182	finalized: bool,
183}
184
185impl RolloutBuffer {
186	/// Allocate one empty fixed-capacity rollout on `runtime`.
187	///
188	/// # Errors
189	///
190	/// Returns an error unless time and environment counts are nonzero, the
191	/// observation rank is in `1..=6`, every observation extent is positive,
192	/// all GPU-indexed counts fit `u32`, and every matrix allocation succeeds.
193	pub fn new(runtime: &Runtime, config: RolloutConfig) -> Result<Self> {
194		if config.time == 0
195			|| config.environments == 0
196			|| !(1..=6).contains(&config.observation_shape.len())
197			|| config.observation_shape.contains(&0)
198		{
199			return Err(Error::invalid_argument(
200				"RolloutBuffer requires nonzero time/environments and a positive observation rank in 1..=6",
201			));
202		}
203		let observation_elements = config
204			.observation_shape
205			.iter()
206			.try_fold(1_usize, |count, extent| count.checked_mul(*extent))
207			.ok_or_else(|| Error::resource_exhausted("rollout observation size overflows usize"))?;
208		let rollout_elements = config
209			.time
210			.checked_mul(config.environments)
211			.ok_or_else(|| Error::resource_exhausted("rollout size overflows usize"))?;
212		let observation_count = rollout_elements
213			.checked_mul(observation_elements)
214			.ok_or_else(|| Error::resource_exhausted("rollout observation storage overflows usize"))?;
215		let observation_elements = u32::try_from(observation_elements).map_err(|_| {
216			Error::resource_exhausted("rollout observation size exceeds GPU u32 indexing")
217		})?;
218		u32::try_from(rollout_elements)
219			.map_err(|_| Error::resource_exhausted("rollout size exceeds GPU u32 indexing"))?;
220		u32::try_from(observation_count).map_err(|_| {
221			Error::resource_exhausted("rollout observation storage exceeds GPU u32 indexing")
222		})?;
223
224		let scalar_shape = vec![config.time, config.environments];
225		let mut observation_shape = scalar_shape.clone();
226		observation_shape.extend_from_slice(&config.observation_shape);
227		let handle = runtime.handle();
228		let allocate =
229			|shape: Vec<usize>, count: usize, dtype| Matrix::allocate(&handle, shape, count, dtype);
230		let batch = RolloutBatch {
231			observation: allocate(observation_shape, observation_count, DType::F32)?,
232			action: allocate(scalar_shape.clone(), rollout_elements, DType::I32)?,
233			reward: allocate(scalar_shape.clone(), rollout_elements, DType::F32)?,
234			value: allocate(scalar_shape.clone(), rollout_elements, DType::F32)?,
235			next_value: allocate(scalar_shape.clone(), rollout_elements, DType::F32)?,
236			old_log_probability: allocate(scalar_shape.clone(), rollout_elements, DType::F32)?,
237			terminated: allocate(scalar_shape.clone(), rollout_elements, DType::U8)?,
238			truncated: allocate(scalar_shape.clone(), rollout_elements, DType::U8)?,
239			valid: allocate(scalar_shape.clone(), rollout_elements, DType::U8)?,
240			advantage: allocate(scalar_shape.clone(), rollout_elements, DType::F32)?,
241			returns: allocate(scalar_shape, rollout_elements, DType::F32)?,
242		};
243		Ok(Self {
244			config,
245			batch,
246			observation_elements,
247			size: 0,
248			finalized: false,
249		})
250	}
251
252	/// Record one fused device-side append into the current time step.
253	///
254	/// # Errors
255	///
256	/// Returns an error after finalization, at capacity, when any transition
257	/// field violates the configured shape/dtype/runtime contract or aliases
258	/// retained rollout storage, or when GPU recording fails.
259	pub fn append(&mut self, transition: &RolloutTransition) -> Result<()> {
260		if self.finalized {
261			return Err(Error::failed_precondition(
262				"RolloutBuffer append requires reset after finalize",
263			));
264		}
265		if self.size == self.config.time {
266			return Err(Error::resource_exhausted(
267				"RolloutBuffer append exceeds rollout capacity",
268			));
269		}
270		append_dispatch(
271			transition,
272			&self.batch,
273			self.size,
274			self.config.environments,
275			&self.config.observation_shape,
276			self.observation_elements,
277			None,
278		)?;
279		self.size += 1;
280		Ok(())
281	}
282
283	pub(in crate::ml) fn initialize_replay_storage(&self) -> Result<()> {
284		for value in self.replay_slots() {
285			match value.dtype() {
286				DType::F32 => value.write_values(&vec![0_f32; value.num_elements()])?,
287				DType::I32 => value.write_values(&vec![0_i32; value.num_elements()])?,
288				DType::U8 => value.write_values(&vec![0_u8; value.num_elements()])?,
289				_ => return Err(Error::internal("unexpected rollout dtype")),
290			}
291		}
292		Ok(())
293	}
294	pub(in crate::ml) fn replay_slots(&self) -> Vec<&Matrix> {
295		let mut slots = batch_destinations(&self.batch).to_vec();
296		slots.push(self.batch.advantage());
297		slots.push(self.batch.returns());
298		slots
299	}
300
301	pub(in crate::ml) fn append_replay(
302		&self,
303		transition: &RolloutTransition,
304		cursor: &Matrix,
305	) -> Result<()> {
306		append_dispatch(
307			transition,
308			&self.batch,
309			0,
310			self.config.environments,
311			&self.config.observation_shape,
312			self.observation_elements,
313			Some(cursor),
314		)
315	}
316	pub(in crate::ml) fn reset_control(&mut self) {
317		self.size = 0;
318		self.finalized = false;
319	}
320	pub(in crate::ml) fn reset_replay_commands(&self) -> Result<()> {
321		reset_dispatch(&self.batch.valid)
322	}
323	pub(in crate::ml) fn finish_replayed_collection(&mut self) {
324		self.size = self.config.time;
325		self.finalized = true;
326	}
327	pub(in crate::ml) fn finalize_replay_commands(
328		&mut self,
329		config: advantage::GaeConfig,
330	) -> Result<()> {
331		advantage::gae_into(
332			&self.batch.reward,
333			&self.batch.value,
334			&self.batch.next_value,
335			&self.batch.terminated,
336			&self.batch.truncated,
337			&mut self.batch.advantage,
338			&mut self.batch.returns,
339			config,
340		)
341	}
342
343	/// Record generalized advantage estimation into the retained batch.
344	///
345	/// Calling this again after successful finalization is an idempotent no-op.
346	///
347	/// # Errors
348	///
349	/// Returns an error until the rollout is full or when GAE validation or GPU
350	/// recording fails.
351	pub fn finalize(&mut self, config: advantage::GaeConfig) -> Result<()> {
352		if self.finalized {
353			return Ok(());
354		}
355		if self.size != self.config.time {
356			return Err(Error::failed_precondition(
357				"RolloutBuffer finalize requires a complete rollout",
358			));
359		}
360		advantage::gae_into(
361			&self.batch.reward,
362			&self.batch.value,
363			&self.batch.next_value,
364			&self.batch.terminated,
365			&self.batch.truncated,
366			&mut self.batch.advantage,
367			&mut self.batch.returns,
368			config,
369		)?;
370		self.finalized = true;
371		Ok(())
372	}
373
374	/// Begin a new collection cycle and clear the validity mask on the device.
375	///
376	/// Previously allocated matrices are retained and overwritten by later
377	/// appends. Pending work remains ordered by the runtime's execution session.
378	///
379	/// # Errors
380	///
381	/// Returns an error when GPU recording fails.
382	pub fn reset(&mut self) -> Result<()> {
383		reset_dispatch(&self.batch.valid)?;
384		self.size = 0;
385		self.finalized = false;
386		Ok(())
387	}
388
389	/// Return whether all configured time steps have been appended.
390	pub fn is_full(&self) -> bool {
391		self.size == self.config.time
392	}
393
394	/// Return whether final GAE has been recorded for this cycle.
395	pub const fn is_finalized(&self) -> bool {
396		self.finalized
397	}
398
399	/// Return the number of appended time steps.
400	pub const fn len(&self) -> usize {
401		self.size
402	}
403
404	/// Return whether no time steps have been appended.
405	pub const fn is_empty(&self) -> bool {
406		self.size == 0
407	}
408
409	/// Return the fixed time-step capacity.
410	pub const fn capacity(&self) -> usize {
411		self.config.time
412	}
413
414	/// Return the validated rollout configuration.
415	pub const fn config(&self) -> &RolloutConfig {
416		&self.config
417	}
418
419	/// Return the retained time-major batch matrices.
420	pub const fn batch(&self) -> &RolloutBatch {
421		&self.batch
422	}
423
424	pub(crate) fn abort_unsubmitted(&mut self) {
425		self.size = 0;
426		self.finalized = false;
427	}
428}
429
430// ---------------------------------------------------------------------------
431// Private dispatch helpers
432// ---------------------------------------------------------------------------
433
434fn append_dispatch(
435	transition: &RolloutTransition,
436	batch: &RolloutBatch,
437	step: usize,
438	environments: usize,
439	observation_shape: &[usize],
440	observation_elements: u32,
441	cursor: Option<&Matrix>,
442) -> Result<()> {
443	const OPERATION: &str = "oa::ml::rollout::append";
444	let mut expected_observation_shape = Vec::with_capacity(observation_shape.len() + 1);
445	expected_observation_shape.push(environments);
446	expected_observation_shape.extend_from_slice(observation_shape);
447	let vector_shape = [environments];
448	let fields = [
449		(
450			transition.observation(),
451			DType::F32,
452			expected_observation_shape.as_slice(),
453		),
454		(transition.action(), DType::I32, vector_shape.as_slice()),
455		(transition.reward(), DType::F32, vector_shape.as_slice()),
456		(transition.value(), DType::F32, vector_shape.as_slice()),
457		(transition.next_value(), DType::F32, vector_shape.as_slice()),
458		(
459			transition.log_probability(),
460			DType::F32,
461			vector_shape.as_slice(),
462		),
463		(transition.terminated(), DType::U8, vector_shape.as_slice()),
464		(transition.truncated(), DType::U8, vector_shape.as_slice()),
465	];
466	for (matrix, dtype, shape) in &fields {
467		if matrix.dtype() != *dtype || matrix.shape() != *shape {
468			return Err(Error::invalid_argument(format!(
469				"{OPERATION} transition does not match the configured categorical shape/dtype contract"
470			)));
471		}
472		if !transition.observation().runtime().same_as(matrix.runtime()) {
473			return Err(Error::invalid_argument(format!(
474				"{OPERATION} transition fields must belong to one runtime"
475			)));
476		}
477	}
478	let destinations = batch_destinations(batch);
479	for destination in destinations {
480		if !transition
481			.observation()
482			.runtime()
483			.same_as(destination.runtime())
484		{
485			return Err(Error::invalid_argument(format!(
486				"{OPERATION} transition and rollout buffer must belong to one runtime"
487			)));
488		}
489		if fields
490			.iter()
491			.any(|(source, _, _)| source.storage().same_as(destination.storage()))
492		{
493			return Err(Error::invalid_argument(format!(
494				"{OPERATION} transition fields must not alias retained rollout storage"
495			)));
496		}
497	}
498
499	let step = shader_u32(step, "step", OPERATION)?;
500	let environments = shader_u32(environments, "environment count", OPERATION)?;
501	let observation_count = environments
502		.checked_mul(observation_elements)
503		.ok_or_else(|| {
504			Error::resource_exhausted(format!("{OPERATION} observation count exceeds u32"))
505		})?;
506	let work_items = observation_count.max(environments);
507	let mut inputs = vec![
508		transition.observation(),
509		transition.action(),
510		transition.reward(),
511		transition.value(),
512		transition.next_value(),
513		transition.log_probability(),
514		transition.terminated(),
515		transition.truncated(),
516		batch.observation(),
517		batch.action(),
518		batch.reward(),
519		batch.value(),
520		batch.next_value(),
521		batch.old_log_probability(),
522		batch.terminated(),
523		batch.truncated(),
524		batch.valid(),
525	];
526	let mut outputs = batch_destinations(batch).to_vec();
527	let mut buffers = vec![
528		BufferBinding::read(transition.observation().storage()),
529		BufferBinding::read(transition.action().storage()),
530		BufferBinding::read(transition.reward().storage()),
531		BufferBinding::read(transition.value().storage()),
532		BufferBinding::read(transition.next_value().storage()),
533		BufferBinding::read(transition.log_probability().storage()),
534		BufferBinding::read(transition.terminated().storage()),
535		BufferBinding::read(transition.truncated().storage()),
536		BufferBinding::write(batch.observation().storage()),
537		BufferBinding::write(batch.action().storage()),
538		BufferBinding::write(batch.reward().storage()),
539		BufferBinding::write(batch.value().storage()),
540		BufferBinding::write(batch.next_value().storage()),
541		BufferBinding::write(batch.old_log_probability().storage()),
542		BufferBinding::write(batch.terminated().storage()),
543		BufferBinding::write(batch.truncated().storage()),
544		BufferBinding::write(batch.valid().storage()),
545	];
546	if let Some(cursor) = cursor {
547		inputs.push(cursor);
548		outputs.push(cursor);
549		buffers.push(BufferBinding::read_write(cursor.storage()));
550	}
551
552	let push_constants = [
553		PushConstant::U32(step),
554		PushConstant::U32(environments),
555		PushConstant::U32(observation_elements),
556	];
557	let attributes = [
558		OpAttribute::UnsignedInteger {
559			name: "step".into(),
560			value: u64::from(step),
561		},
562		OpAttribute::UnsignedInteger {
563			name: "environments".into(),
564			value: u64::from(environments),
565		},
566		OpAttribute::UnsignedInteger {
567			name: "observation_elements".into(),
568			value: u64::from(observation_elements),
569		},
570	];
571	let kernel = if cursor.is_some() {
572		KernelId::MlRolloutAppendCursorF32
573	} else {
574		KernelId::MlRolloutAppendF32
575	};
576	{
577		let inputs: &[&Matrix] = &inputs;
578		let outputs: &[&Matrix] = &outputs;
579		let attributes: &[OpAttribute] = &attributes;
580		let dispatch = ComputeDispatch {
581			kernel,
582			buffers: &buffers,
583			push_constants: &push_constants,
584			workgroups: kernel.linear_workgroups(work_items),
585			indirect: None,
586		};
587		let contract = dispatch.kernel.semantic_contract().ok_or_else(|| {
588			Error::internal(format!(
589				"lowering-only kernel {} cannot own one semantic ML operation",
590				dispatch.kernel.report_name()
591			))
592		})?;
593		let runtime = inputs
594			.first()
595			.ok_or_else(|| Error::internal("semantic ML dispatch requires an input"))?
596			.runtime();
597		runtime.record_semantic(
598			dispatch,
599			SemanticDispatch {
600				contract,
601				inputs,
602				outputs,
603				attributes,
604			},
605		)
606	}
607}
608
609// Retained successor observations are program-owned scratch rather than
610// RolloutBatch fields: the compiled trading program is the only collector that
611// defers next_value to a single batched GAE-time evaluation.
612pub(in crate::ml) fn next_observation_append(
613	next_observation: &Matrix,
614	retained: &Matrix,
615	cursor: &Matrix,
616	step: usize,
617	observation_count: usize,
618) -> Result<()> {
619	const OPERATION: &str = "oa::ml::rollout::next_observation_append";
620	if next_observation.dtype() != DType::F32
621		|| retained.dtype() != DType::F32
622		|| cursor.dtype() != DType::U32
623		|| next_observation.num_elements() != observation_count
624		|| observation_count == 0
625		|| !retained.num_elements().is_multiple_of(observation_count)
626		|| !next_observation.runtime().same_as(retained.runtime())
627		|| !next_observation.runtime().same_as(cursor.runtime())
628	{
629		return Err(Error::invalid_argument(format!(
630			"{OPERATION} source/retained/cursor shape/dtype/Runtime mismatch"
631		)));
632	}
633	if next_observation.storage().same_as(retained.storage()) {
634		return Err(Error::invalid_argument(format!(
635			"{OPERATION} source must not alias retained rollout storage"
636		)));
637	}
638	if step >= retained.num_elements() / observation_count {
639		return Err(Error::resource_exhausted(format!(
640			"{OPERATION} step exceeds retained rollout rows"
641		)));
642	}
643	let step = shader_u32(step, "step", OPERATION)?;
644	let observation_count = shader_u32(observation_count, "observation count", OPERATION)?;
645	let buffers = [
646		BufferBinding::read_write(retained.storage()),
647		BufferBinding::read(next_observation.storage()),
648		BufferBinding::read(cursor.storage()),
649	];
650	let push_constants = [
651		PushConstant::U32(step),
652		PushConstant::U32(observation_count),
653	];
654	let kernel = KernelId::MlRolloutNextObservationAppendF32;
655	{
656		let inputs: &[&Matrix] = &[retained, next_observation, cursor];
657		let outputs: &[&Matrix] = &[retained];
658		let attributes = [
659			OpAttribute::UnsignedInteger {
660				name: "step".into(),
661				value: u64::from(step),
662			},
663			OpAttribute::UnsignedInteger {
664				name: "observation_count".into(),
665				value: u64::from(observation_count),
666			},
667		];
668		let dispatch = ComputeDispatch {
669			kernel,
670			buffers: &buffers,
671			push_constants: &push_constants,
672			workgroups: kernel.linear_workgroups(observation_count),
673			indirect: None,
674		};
675		let contract = dispatch.kernel.semantic_contract().ok_or_else(|| {
676			Error::internal(format!(
677				"lowering-only kernel {} cannot own one semantic ML operation",
678				dispatch.kernel.report_name()
679			))
680		})?;
681		let runtime = inputs
682			.first()
683			.ok_or_else(|| Error::internal("semantic ML dispatch requires an input"))?
684			.runtime();
685		runtime.record_semantic(
686			dispatch,
687			SemanticDispatch {
688				contract,
689				inputs,
690				outputs,
691				attributes: &attributes,
692			},
693		)
694	}
695}
696
697fn reset_dispatch(valid: &Matrix) -> Result<()> {
698	const OPERATION: &str = "oa::ml::rollout::reset";
699	if valid.dtype() != DType::U8 || valid.shape().len() != 2 {
700		return Err(Error::invalid_argument(format!(
701			"{OPERATION} requires a rank-two U8 validity mask"
702		)));
703	}
704	let count = shader_u32(valid.num_elements(), "element count", OPERATION)?;
705	let buffers = [BufferBinding::write(valid.storage())];
706	let push_constants = [PushConstant::U32(count)];
707	let kernel = KernelId::MlRolloutResetU8;
708	{
709		let inputs: &[&Matrix] = &[valid];
710		let outputs: &[&Matrix] = &[valid];
711		let attributes: &[OpAttribute] = &[];
712		let dispatch = ComputeDispatch {
713			kernel,
714			buffers: &buffers,
715			push_constants: &push_constants,
716			workgroups: kernel.linear_workgroups(count),
717			indirect: None,
718		};
719		let contract = dispatch.kernel.semantic_contract().ok_or_else(|| {
720			Error::internal(format!(
721				"lowering-only kernel {} cannot own one semantic ML operation",
722				dispatch.kernel.report_name()
723			))
724		})?;
725		let runtime = inputs
726			.first()
727			.ok_or_else(|| Error::internal("semantic ML dispatch requires an input"))?
728			.runtime();
729		runtime.record_semantic(
730			dispatch,
731			SemanticDispatch {
732				contract,
733				inputs,
734				outputs,
735				attributes,
736			},
737		)
738	}
739}
740
741// ---------------------------------------------------------------------------
742// Helpers
743// ---------------------------------------------------------------------------
744
745fn batch_destinations(batch: &RolloutBatch) -> [&Matrix; 9] {
746	[
747		batch.observation(),
748		batch.action(),
749		batch.reward(),
750		batch.value(),
751		batch.next_value(),
752		batch.old_log_probability(),
753		batch.terminated(),
754		batch.truncated(),
755		batch.valid(),
756	]
757}
758
759// Aligned detached inputs for a contiguous PPO update tape. The rollout's I32
760// actions never pass through F32 or host readback; generic Slice is F32-only.
761pub(in crate::ml) fn minibatch(
762	inputs: [&Matrix; 5],
763	start: usize,
764	count: usize,
765) -> Result<[Matrix; 5]> {
766	let [batch, width] = inputs[0].shape() else {
767		return Err(Error::invalid_argument(
768			"PPO minibatch observations must be [batch,width]",
769		));
770	};
771	if *width == 0 || count == 0 || start.checked_add(count).is_none_or(|end| end > *batch) {
772		return Err(Error::invalid_argument(
773			"PPO minibatch range is outside the rollout",
774		));
775	}
776	for (index, input) in inputs.iter().enumerate() {
777		let dtype = if index == 1 { DType::I32 } else { DType::F32 };
778		if input.dtype() != dtype
779			|| !input.runtime().same_as(inputs[0].runtime())
780			|| (index > 0 && input.shape() != [*batch])
781		{
782			return Err(Error::invalid_argument(
783				"PPO minibatch shape/dtype/Runtime mismatch",
784			));
785		}
786	}
787	const OP: &str = "oa::ml::rollout::minibatch";
788	shader_u32(inputs[0].element_count(), "source observation elements", OP)?;
789	let elements = count
790		.checked_mul(*width)
791		.ok_or_else(|| Error::resource_exhausted("PPO minibatch observation extent overflows"))?;
792	let items = shader_u32(elements, "output observation elements", OP)?;
793	let runtime = inputs[0].runtime();
794	let allocate = |shape, count, dtype| Matrix::allocate(runtime, shape, count, dtype);
795	let outputs = [
796		allocate(vec![count, *width], elements, DType::F32)?,
797		allocate(vec![count], count, DType::I32)?,
798		allocate(vec![count], count, DType::F32)?,
799		allocate(vec![count], count, DType::F32)?,
800		allocate(vec![count], count, DType::F32)?,
801	];
802	let buffers = [
803		BufferBinding::read(inputs[0].storage()),
804		BufferBinding::read(inputs[1].storage()),
805		BufferBinding::read(inputs[2].storage()),
806		BufferBinding::read(inputs[3].storage()),
807		BufferBinding::read(inputs[4].storage()),
808		BufferBinding::write(outputs[0].storage()),
809		BufferBinding::write(outputs[1].storage()),
810		BufferBinding::write(outputs[2].storage()),
811		BufferBinding::write(outputs[3].storage()),
812		BufferBinding::write(outputs[4].storage()),
813	];
814	let start = shader_u32(start, "start", OP)?;
815	let count = shader_u32(count, "count", OP)?;
816	let push = [
817		PushConstant::U32(start),
818		PushConstant::U32(count),
819		PushConstant::U32(shader_u32(*width, "observation width", OP)?),
820	];
821	let attributes = [
822		OpAttribute::UnsignedInteger {
823			name: "start".into(),
824			value: u64::from(start),
825		},
826		OpAttribute::UnsignedInteger {
827			name: "count".into(),
828			value: u64::from(count),
829		},
830	];
831	runtime.record_semantic(
832		ComputeDispatch {
833			kernel: KernelId::MlRolloutMinibatchF32,
834			buffers: &buffers,
835			push_constants: &push,
836			workgroups: KernelId::MlRolloutMinibatchF32.linear_workgroups(items),
837			indirect: None,
838		},
839		SemanticDispatch {
840			contract: crate::core::operation::ml::MINIBATCH,
841			inputs: &inputs,
842			outputs: &[
843				&outputs[0],
844				&outputs[1],
845				&outputs[2],
846				&outputs[3],
847				&outputs[4],
848			],
849			attributes: &attributes,
850		},
851	)?;
852	Ok(outputs)
853}
854
855// Cursor bounds are checked by PpoUpdateProgram before each replay.
856pub(in crate::ml) fn minibatch_cursor(
857	inputs: [&Matrix; 5],
858	cursor: &Matrix,
859	count: usize,
860) -> Result<[Matrix; 5]> {
861	let [batch, width] = inputs[0].shape() else {
862		return Err(Error::invalid_argument(
863			"PPO minibatch observations must be [batch,width]",
864		));
865	};
866	if *width == 0 || count == 0 || count > *batch {
867		return Err(Error::invalid_argument(
868			"PPO minibatch range is outside the rollout",
869		));
870	}
871	for (index, input) in inputs.iter().enumerate() {
872		let dtype = if index == 1 { DType::I32 } else { DType::F32 };
873		if input.dtype() != dtype
874			|| !input.runtime().same_as(inputs[0].runtime())
875			|| (index > 0 && input.shape() != [*batch])
876		{
877			return Err(Error::invalid_argument(
878				"PPO minibatch shape/dtype/Runtime mismatch",
879			));
880		}
881	}
882	if cursor.dtype() != DType::U32
883		|| cursor.shape() != [2]
884		|| !cursor.runtime().same_as(inputs[0].runtime())
885	{
886		return Err(Error::invalid_argument(
887			"PPO cursor must be same-runtime U32 [2]",
888		));
889	}
890	const OP: &str = "oa::ml::rollout::minibatch";
891	shader_u32(inputs[0].element_count(), "source observation elements", OP)?;
892	let elements = count
893		.checked_mul(*width)
894		.ok_or_else(|| Error::resource_exhausted("PPO minibatch observation extent overflows"))?;
895	let items = shader_u32(elements, "output observation elements", OP)?;
896	let runtime = inputs[0].runtime();
897	let allocate = |shape, count, dtype| Matrix::allocate(runtime, shape, count, dtype);
898	let outputs = [
899		allocate(vec![count, *width], elements, DType::F32)?,
900		allocate(vec![count], count, DType::I32)?,
901		allocate(vec![count], count, DType::F32)?,
902		allocate(vec![count], count, DType::F32)?,
903		allocate(vec![count], count, DType::F32)?,
904	];
905	let buffers = [
906		BufferBinding::read(inputs[0].storage()),
907		BufferBinding::read(inputs[1].storage()),
908		BufferBinding::read(inputs[2].storage()),
909		BufferBinding::read(inputs[3].storage()),
910		BufferBinding::read(inputs[4].storage()),
911		BufferBinding::write(outputs[0].storage()),
912		BufferBinding::write(outputs[1].storage()),
913		BufferBinding::write(outputs[2].storage()),
914		BufferBinding::write(outputs[3].storage()),
915		BufferBinding::write(outputs[4].storage()),
916		BufferBinding::read(cursor.storage()),
917	];
918	let count = shader_u32(count, "count", OP)?;
919	let push = [
920		PushConstant::U32(count),
921		PushConstant::U32(shader_u32(*width, "observation width", OP)?),
922	];
923	let attributes = [OpAttribute::UnsignedInteger {
924		name: "count".into(),
925		value: u64::from(count),
926	}];
927	runtime.record_semantic(
928		ComputeDispatch {
929			kernel: KernelId::MlRolloutMinibatchCursorF32,
930			buffers: &buffers,
931			push_constants: &push,
932			workgroups: KernelId::MlRolloutMinibatchCursorF32.linear_workgroups(items),
933			indirect: None,
934		},
935		SemanticDispatch {
936			contract: crate::core::operation::ml::MINIBATCH_CURSOR,
937			inputs: &[
938				inputs[0], inputs[1], inputs[2], inputs[3], inputs[4], cursor,
939			],
940			outputs: &[
941				&outputs[0],
942				&outputs[1],
943				&outputs[2],
944				&outputs[3],
945				&outputs[4],
946			],
947			attributes: &attributes,
948		},
949	)?;
950	Ok(outputs)
951}