1use std::{
4 ffi::OsString,
5 fs,
6 io::Write,
7 path::{Path, PathBuf},
8};
9
10use crate::runtime::ComputeDispatch;
11use crate::runtime::SemanticDispatch;
12use crate::runtime::{BufferBinding, KernelId, PushConstant};
13use crate::{DType, Error, Matrix, OpAttribute, Result, Runtime};
14
15pub use crate::ml::types::ReplayConfig;
16use crate::ml::validation::shader_u32;
17
18#[derive(Clone)]
20pub struct ReplayTransition {
21 observation: Matrix,
22 action: Matrix,
23 next_observation: Matrix,
24 reward: Matrix,
25 terminated: Matrix,
26 truncated: Matrix,
27}
28
29impl ReplayTransition {
30 pub fn new(
34 observation: Matrix,
35 action: Matrix,
36 next_observation: Matrix,
37 reward: Matrix,
38 terminated: Matrix,
39 truncated: Matrix,
40 ) -> Self {
41 Self {
42 observation,
43 action,
44 next_observation,
45 reward,
46 terminated,
47 truncated,
48 }
49 }
50
51 pub const fn observation(&self) -> &Matrix {
53 &self.observation
54 }
55
56 pub const fn action(&self) -> &Matrix {
58 &self.action
59 }
60
61 pub const fn next_observation(&self) -> &Matrix {
63 &self.next_observation
64 }
65
66 pub const fn reward(&self) -> &Matrix {
68 &self.reward
69 }
70
71 pub const fn terminated(&self) -> &Matrix {
73 &self.terminated
74 }
75
76 pub const fn truncated(&self) -> &Matrix {
78 &self.truncated
79 }
80}
81
82pub struct ReplayBatch {
84 pub(crate) observation: Matrix,
85 pub(crate) action: Matrix,
86 pub(crate) next_observation: Matrix,
87 pub(crate) reward: Matrix,
88 pub(crate) terminated: Matrix,
89 pub(crate) truncated: Matrix,
90 pub(crate) index: Matrix,
91}
92
93impl ReplayBatch {
94 pub const fn observation(&self) -> &Matrix {
96 &self.observation
97 }
98
99 pub const fn action(&self) -> &Matrix {
101 &self.action
102 }
103
104 pub const fn next_observation(&self) -> &Matrix {
106 &self.next_observation
107 }
108
109 pub const fn reward(&self) -> &Matrix {
111 &self.reward
112 }
113
114 pub const fn terminated(&self) -> &Matrix {
116 &self.terminated
117 }
118
119 pub const fn truncated(&self) -> &Matrix {
121 &self.truncated
122 }
123
124 pub const fn index(&self) -> &Matrix {
126 &self.index
127 }
128}
129
130pub struct ReplayBuffer {
136 config: ReplayConfig,
137 storage: ReplayBatch,
138 observation_elements: u32,
139 action_elements: u32,
140 size: core::cell::Cell<usize>,
141 cursor: core::cell::Cell<usize>,
142}
143
144impl ReplayBuffer {
145 pub fn new(runtime: &Runtime, config: ReplayConfig) -> Result<Self> {
152 if config.capacity == 0 || !matches!(config.action_dtype, DType::F32 | DType::I32) {
153 return Err(Error::invalid_argument(
154 "ReplayBuffer requires positive capacity and F32 or I32 actions",
155 ));
156 }
157 let observation_elements = field_elements(&config.observation_shape, false)?;
158 let action_elements = field_elements(&config.action_shape, true)?;
159 let observation_count = config
160 .capacity
161 .checked_mul(observation_elements)
162 .ok_or_else(|| Error::resource_exhausted("replay observation storage overflows usize"))?;
163 let action_count = config
164 .capacity
165 .checked_mul(action_elements)
166 .ok_or_else(|| Error::resource_exhausted("replay action storage overflows usize"))?;
167 for (label, count) in [
168 ("capacity", config.capacity),
169 ("observation storage", observation_count),
170 ("action storage", action_count),
171 ] {
172 u32::try_from(count).map_err(|_| {
173 Error::resource_exhausted(format!("replay {label} exceeds GPU u32 indexing"))
174 })?;
175 }
176 let observation_elements = u32::try_from(observation_elements)
177 .map_err(|_| Error::resource_exhausted("replay observation field exceeds u32"))?;
178 let action_elements = u32::try_from(action_elements)
179 .map_err(|_| Error::resource_exhausted("replay action field exceeds u32"))?;
180 let mut observation_shape = vec![config.capacity];
181 observation_shape.extend_from_slice(&config.observation_shape);
182 let mut action_shape = vec![config.capacity];
183 action_shape.extend_from_slice(&config.action_shape);
184 let handle = runtime.handle();
185 let storage = ReplayBatch {
186 observation: Matrix::allocate(
187 &handle,
188 observation_shape.clone(),
189 observation_count,
190 DType::F32,
191 )?,
192 action: Matrix::allocate(&handle, action_shape, action_count, config.action_dtype)?,
193 next_observation: Matrix::allocate(
194 &handle,
195 observation_shape,
196 observation_count,
197 DType::F32,
198 )?,
199 reward: Matrix::allocate(&handle, vec![config.capacity], config.capacity, DType::F32)?,
200 terminated: Matrix::allocate(&handle, vec![config.capacity], config.capacity, DType::U8)?,
201 truncated: Matrix::allocate(&handle, vec![config.capacity], config.capacity, DType::U8)?,
202 index: Matrix::allocate(&handle, vec![config.capacity], config.capacity, DType::U32)?,
203 };
204 Ok(Self {
205 config,
206 storage,
207 observation_elements,
208 action_elements,
209 size: core::cell::Cell::new(0),
210 cursor: core::cell::Cell::new(0),
211 })
212 }
213
214 pub fn append(&self, transition: &ReplayTransition) -> Result<()> {
222 let cursor = self.cursor.get();
223 let batch = append_dispatch(
224 transition,
225 &self.storage,
226 &self.config,
227 cursor,
228 self.observation_elements,
229 self.action_elements,
230 )?;
231 self.cursor.set((cursor + batch) % self.config.capacity);
232 self.size.set(
233 self
234 .config
235 .capacity
236 .min(self.size.get().saturating_add(batch)),
237 );
238 Ok(())
239 }
240
241 pub fn sample(&self, batch_size: usize, seed: u64) -> Result<ReplayBatch> {
251 if self.size.get() == 0 || batch_size == 0 {
252 return Err(Error::failed_precondition(
253 "ReplayBuffer sample requires nonempty storage and a positive batch size",
254 ));
255 }
256 sample_dispatch(
257 &self.storage,
258 &self.config,
259 self.size.get(),
260 batch_size,
261 seed,
262 self.observation_elements,
263 self.action_elements,
264 )
265 }
266
267 pub fn reset(&self) {
271 self.size.set(0);
272 self.cursor.set(0);
273 }
274
275 pub fn is_full(&self) -> bool {
277 self.size.get() == self.config.capacity
278 }
279
280 pub fn len(&self) -> usize {
282 self.size.get()
283 }
284
285 pub const fn is_empty(&self) -> bool {
287 self.size.get() == 0
288 }
289
290 pub const fn capacity(&self) -> usize {
292 self.config.capacity
293 }
294
295 pub fn cursor(&self) -> usize {
297 self.cursor.get()
298 }
299
300 pub const fn config(&self) -> &ReplayConfig {
302 &self.config
303 }
304
305 pub fn capture_state(&self) -> Result<ReplayBufferState> {
317 let size = self.size.get();
318 let cursor = self.cursor.get();
319 let obs_count = size
320 .checked_mul(self.observation_elements as usize)
321 .ok_or_else(|| {
322 Error::resource_exhausted("replay capture observation size overflows usize")
323 })?;
324 let act_count = size
325 .checked_mul(self.action_elements as usize)
326 .ok_or_else(|| Error::resource_exhausted("replay capture action size overflows usize"))?;
327 if size == 0 {
328 return Ok(ReplayBufferState {
329 config: self.config.clone(),
330 size: 0,
331 cursor: 0,
332 observation: Vec::new(),
333 action_bytes: Vec::new(),
334 next_observation: Vec::new(),
335 reward: Vec::new(),
336 terminated: Vec::new(),
337 truncated: Vec::new(),
338 });
339 }
340 let mut observation = self.storage.observation().read_f32()?;
341 observation.truncate(obs_count);
342 let action_bytes = match self.config.action_dtype {
343 DType::F32 => {
344 let values = self.storage.action().read_f32()?;
345 let mut bytes = Vec::with_capacity(act_count * 4);
346 for &value in &values[..act_count] {
347 bytes.extend_from_slice(&value.to_le_bytes());
348 }
349 bytes
350 }
351 DType::I32 => {
352 let values = self.storage.action().read::<i32>()?;
353 let mut bytes = Vec::with_capacity(act_count * 4);
354 for &value in &values[..act_count] {
355 bytes.extend_from_slice(&value.to_le_bytes());
356 }
357 bytes
358 }
359 other => {
360 return Err(Error::invalid_argument(format!(
361 "unsupported replay action dtype {}",
362 other.token()
363 )));
364 }
365 };
366 let mut next_observation = self.storage.next_observation().read_f32()?;
367 next_observation.truncate(obs_count);
368 let mut reward = self.storage.reward().read_f32()?;
369 reward.truncate(size);
370 let mut terminated = self.storage.terminated().read::<u8>()?;
371 terminated.truncate(size);
372 let mut truncated = self.storage.truncated().read::<u8>()?;
373 truncated.truncate(size);
374 Ok(ReplayBufferState {
375 config: self.config.clone(),
376 size,
377 cursor,
378 observation,
379 action_bytes,
380 next_observation,
381 reward,
382 terminated,
383 truncated,
384 })
385 }
386
387 pub fn restore_state(&self, state: &ReplayBufferState) -> Result<()> {
398 state.validate()?;
399 if state.config != self.config {
400 return Err(Error::invalid_argument(
401 "replay snapshot configuration does not match destination ReplayBuffer",
402 ));
403 }
404 if state.size == 0 {
405 self.size.set(0);
406 self.cursor.set(0);
407 return Ok(());
408 }
409 let runtime = self.storage.observation().runtime();
410 let obs_shape = prefixed_shape(state.size, &self.config.observation_shape);
411 let act_shape = prefixed_shape(state.size, &self.config.action_shape);
412 let vec_shape = vec![state.size];
413 let observation =
414 Matrix::new_from_slice_handle(runtime, obs_shape.clone(), &state.observation)?;
415 let action = match self.config.action_dtype {
416 DType::F32 => {
417 let values: Vec<f32> = state
418 .action_bytes
419 .as_chunks::<4>()
420 .0
421 .iter()
422 .copied()
423 .map(f32::from_le_bytes)
424 .collect();
425 Matrix::new_from_slice_handle(runtime, act_shape, &values)?
426 }
427 DType::I32 => {
428 let values: Vec<i32> = state
429 .action_bytes
430 .as_chunks::<4>()
431 .0
432 .iter()
433 .copied()
434 .map(i32::from_le_bytes)
435 .collect();
436 Matrix::new_from_slice_handle(runtime, act_shape, &values)?
437 }
438 other => {
439 return Err(Error::invalid_argument(format!(
440 "unsupported replay action dtype {}",
441 other.token()
442 )));
443 }
444 };
445 let next_observation =
446 Matrix::new_from_slice_handle(runtime, obs_shape, &state.next_observation)?;
447 let reward = Matrix::new_from_slice_handle(runtime, vec_shape.clone(), &state.reward)?;
448 let terminated = Matrix::new_from_slice_handle(runtime, vec_shape.clone(), &state.terminated)?;
449 let truncated = Matrix::new_from_slice_handle(runtime, vec_shape, &state.truncated)?;
450 let transition = ReplayTransition::new(
451 observation,
452 action,
453 next_observation,
454 reward,
455 terminated,
456 truncated,
457 );
458 append_dispatch(
459 &transition,
460 &self.storage,
461 &self.config,
462 0,
463 self.observation_elements,
464 self.action_elements,
465 )?;
466 runtime.checkpoint(false)?.wait()?;
467 self.size.set(state.size);
468 self.cursor.set(state.cursor);
469 Ok(())
470 }
471
472 pub fn save(&self, path: impl AsRef<Path>) -> Result<()> {
479 self.capture_state()?.save(path)
480 }
481
482 pub fn load_into(&self, path: impl AsRef<Path>) -> Result<()> {
490 let state = ReplayBufferState::load(path)?;
491 self.restore_state(&state)
492 }
493}
494
495#[derive(Clone, Debug, PartialEq)]
498pub struct ReplayBufferState {
499 config: ReplayConfig,
500 size: usize,
501 cursor: usize,
502 observation: Vec<f32>,
503 action_bytes: Vec<u8>,
504 next_observation: Vec<f32>,
505 reward: Vec<f32>,
506 terminated: Vec<u8>,
507 truncated: Vec<u8>,
508}
509
510const REPLAY_MAGIC: &[u8; 4] = b"OARP";
511const REPLAY_VERSION: u32 = 1;
512const REPLAY_FNV_OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
513const REPLAY_FNV_PRIME: u64 = 0x0100_0000_01b3;
514
515impl ReplayBufferState {
516 pub const fn config(&self) -> &ReplayConfig {
518 &self.config
519 }
520
521 pub const fn len(&self) -> usize {
523 self.size
524 }
525
526 pub const fn is_empty(&self) -> bool {
528 self.size == 0
529 }
530
531 pub const fn cursor(&self) -> usize {
533 self.cursor
534 }
535
536 pub fn encode(&self) -> Result<Vec<u8>> {
543 self.validate()?;
544 let mut bytes = Vec::new();
545 bytes.extend_from_slice(REPLAY_MAGIC);
546 bytes.extend_from_slice(&REPLAY_VERSION.to_le_bytes());
547 bytes.extend_from_slice(&(self.config.capacity as u64).to_le_bytes());
548 bytes.extend_from_slice(&(self.size as u64).to_le_bytes());
549 bytes.extend_from_slice(&(self.cursor as u64).to_le_bytes());
550 let dtype_tag: u8 = match self.config.action_dtype {
551 DType::F32 => 0,
552 DType::I32 => 1,
553 _ => {
554 return Err(Error::invalid_argument(
555 "replay snapshot only supports F32 or I32 actions",
556 ));
557 }
558 };
559 bytes.push(dtype_tag);
560 bytes.extend_from_slice(&(self.config.observation_shape.len() as u32).to_le_bytes());
561 for &extent in &self.config.observation_shape {
562 bytes.extend_from_slice(&(extent as u64).to_le_bytes());
563 }
564 bytes.extend_from_slice(&(self.config.action_shape.len() as u32).to_le_bytes());
565 for &extent in &self.config.action_shape {
566 bytes.extend_from_slice(&(extent as u64).to_le_bytes());
567 }
568 for &value in &self.observation {
569 bytes.extend_from_slice(&value.to_le_bytes());
570 }
571 bytes.extend_from_slice(&self.action_bytes);
572 for &value in &self.next_observation {
573 bytes.extend_from_slice(&value.to_le_bytes());
574 }
575 for &value in &self.reward {
576 bytes.extend_from_slice(&value.to_le_bytes());
577 }
578 bytes.extend_from_slice(&self.terminated);
579 bytes.extend_from_slice(&self.truncated);
580 let checksum = replay_fnv64(&bytes);
581 bytes.extend_from_slice(&checksum.to_le_bytes());
582 Ok(bytes)
583 }
584
585 pub fn decode(bytes: &[u8]) -> Result<Self> {
593 if bytes.len() < 8 {
594 return Err(Error::checkpoint_corrupt("replay snapshot is truncated"));
595 }
596 let (body, tail) = bytes.split_at(bytes.len() - 8);
597 let expected_checksum = u64::from_le_bytes(tail.try_into().expect("8-byte tail"));
598 if replay_fnv64(body) != expected_checksum {
599 return Err(Error::checkpoint_corrupt(
600 "replay snapshot checksum verification failed",
601 ));
602 }
603 let mut cursor_pos = 0_usize;
604 let magic = take_slice(body, &mut cursor_pos, 4)?;
605 if magic != REPLAY_MAGIC {
606 return Err(Error::checkpoint_corrupt(
607 "replay snapshot has invalid magic",
608 ));
609 }
610 let version = take_u32(body, &mut cursor_pos)?;
611 if version != REPLAY_VERSION {
612 return Err(Error::checkpoint_corrupt(format!(
613 "unsupported replay snapshot version {version}"
614 )));
615 }
616 let capacity = usize::try_from(take_u64(body, &mut cursor_pos)?)
617 .map_err(|_| Error::checkpoint_corrupt("replay capacity exceeds usize"))?;
618 let size = usize::try_from(take_u64(body, &mut cursor_pos)?)
619 .map_err(|_| Error::checkpoint_corrupt("replay size exceeds usize"))?;
620 let write_cursor = usize::try_from(take_u64(body, &mut cursor_pos)?)
621 .map_err(|_| Error::checkpoint_corrupt("replay cursor exceeds usize"))?;
622 let dtype_tag = take_slice(body, &mut cursor_pos, 1)?[0];
623 let action_dtype = match dtype_tag {
624 0 => DType::F32,
625 1 => DType::I32,
626 _ => {
627 return Err(Error::checkpoint_corrupt(format!(
628 "unknown replay action dtype tag {dtype_tag}"
629 )));
630 }
631 };
632 let obs_rank = take_u32(body, &mut cursor_pos)? as usize;
633 if obs_rank == 0 || obs_rank > 7 {
634 return Err(Error::checkpoint_corrupt(
635 "replay observation rank out of range",
636 ));
637 }
638 let mut observation_shape = Vec::with_capacity(obs_rank);
639 for _ in 0..obs_rank {
640 let extent = usize::try_from(take_u64(body, &mut cursor_pos)?)
641 .map_err(|_| Error::checkpoint_corrupt("replay observation extent exceeds usize"))?;
642 observation_shape.push(extent);
643 }
644 let act_rank = take_u32(body, &mut cursor_pos)? as usize;
645 if act_rank > 7 {
646 return Err(Error::checkpoint_corrupt("replay action rank out of range"));
647 }
648 let mut action_shape = Vec::with_capacity(act_rank);
649 for _ in 0..act_rank {
650 let extent = usize::try_from(take_u64(body, &mut cursor_pos)?)
651 .map_err(|_| Error::checkpoint_corrupt("replay action extent exceeds usize"))?;
652 action_shape.push(extent);
653 }
654 let config = ReplayConfig {
655 capacity,
656 observation_shape,
657 action_shape,
658 action_dtype,
659 };
660 let obs_elems = field_elements(&config.observation_shape, false)
661 .map_err(|_| Error::checkpoint_corrupt("invalid replay observation shape"))?;
662 let act_elems = field_elements(&config.action_shape, true)
663 .map_err(|_| Error::checkpoint_corrupt("invalid replay action shape"))?;
664 let obs_count = size
665 .checked_mul(obs_elems)
666 .ok_or_else(|| Error::checkpoint_corrupt("replay observation count overflow"))?;
667 let act_byte_count = size
668 .checked_mul(act_elems)
669 .and_then(|count| count.checked_mul(4))
670 .ok_or_else(|| Error::checkpoint_corrupt("replay action byte count overflow"))?;
671 let obs_bytes = obs_count
672 .checked_mul(4)
673 .ok_or_else(|| Error::checkpoint_corrupt("replay observation byte count overflow"))?;
674 let reward_bytes = size
675 .checked_mul(4)
676 .ok_or_else(|| Error::checkpoint_corrupt("replay reward byte count overflow"))?;
677 let observation = decode_f32_slice(take_slice(body, &mut cursor_pos, obs_bytes)?);
678 let action_bytes = take_slice(body, &mut cursor_pos, act_byte_count)?.to_vec();
679 let next_observation = decode_f32_slice(take_slice(body, &mut cursor_pos, obs_bytes)?);
680 let reward = decode_f32_slice(take_slice(body, &mut cursor_pos, reward_bytes)?);
681 let terminated = take_slice(body, &mut cursor_pos, size)?.to_vec();
682 let truncated = take_slice(body, &mut cursor_pos, size)?.to_vec();
683 if cursor_pos != body.len() {
684 return Err(Error::checkpoint_corrupt(
685 "replay snapshot has trailing bytes",
686 ));
687 }
688 let state = Self {
689 config,
690 size,
691 cursor: write_cursor,
692 observation,
693 action_bytes,
694 next_observation,
695 reward,
696 terminated,
697 truncated,
698 };
699 state
700 .validate()
701 .map_err(|error| Error::checkpoint_corrupt(error.message()))?;
702 Ok(state)
703 }
704
705 pub fn save(&self, path: impl AsRef<Path>) -> Result<()> {
711 let path = path.as_ref();
712 let bytes = self.encode()?;
713 let mut tmp_os = OsString::from(path.as_os_str());
714 tmp_os.push(".tmp");
715 let temporary = PathBuf::from(tmp_os);
716 {
717 let mut file = fs::File::create(&temporary)
718 .map_err(|error| Error::io("create replay temporary", error))?;
719 file
720 .write_all(&bytes)
721 .map_err(|error| Error::io("write replay temporary", error))?;
722 file
723 .sync_all()
724 .map_err(|error| Error::io("flush replay temporary", error))?;
725 }
726 fs::rename(&temporary, path).map_err(|error| Error::io("commit replay snapshot", error))
727 }
728
729 pub fn load(path: impl AsRef<Path>) -> Result<Self> {
736 let path = path.as_ref();
737 let bytes = fs::read(path).map_err(|error| Error::io("read replay snapshot", error))?;
738 Self::decode(&bytes)
739 }
740
741 fn validate(&self) -> Result<()> {
742 if self.config.capacity == 0 || !matches!(self.config.action_dtype, DType::F32 | DType::I32) {
743 return Err(Error::invalid_argument(
744 "replay snapshot requires positive capacity and F32 or I32 actions",
745 ));
746 }
747 let obs_elems = field_elements(&self.config.observation_shape, false)?;
748 let act_elems = field_elements(&self.config.action_shape, true)?;
749 if self.size > self.config.capacity || self.cursor >= self.config.capacity {
750 return Err(Error::invalid_argument(
751 "replay snapshot size or cursor exceeds configured capacity",
752 ));
753 }
754 if self.size < self.config.capacity && self.cursor != self.size {
755 return Err(Error::invalid_argument(
756 "unwrapped replay snapshot cursor must equal size",
757 ));
758 }
759 let expected_obs = self
760 .size
761 .checked_mul(obs_elems)
762 .ok_or_else(|| Error::resource_exhausted("replay snapshot observation count overflow"))?;
763 let expected_act_bytes = self
764 .size
765 .checked_mul(act_elems)
766 .and_then(|count| count.checked_mul(4))
767 .ok_or_else(|| Error::resource_exhausted("replay snapshot action byte count overflow"))?;
768 if self.observation.len() != expected_obs
769 || self.next_observation.len() != expected_obs
770 || self.action_bytes.len() != expected_act_bytes
771 || self.reward.len() != self.size
772 || self.terminated.len() != self.size
773 || self.truncated.len() != self.size
774 {
775 return Err(Error::invalid_argument(
776 "replay snapshot payload lengths do not match schema and size",
777 ));
778 }
779 Ok(())
780 }
781}
782
783fn replay_fnv64(bytes: &[u8]) -> u64 {
784 bytes.iter().fold(REPLAY_FNV_OFFSET, |hash, byte| {
785 (hash ^ u64::from(*byte)).wrapping_mul(REPLAY_FNV_PRIME)
786 })
787}
788
789fn take_slice<'a>(bytes: &'a [u8], pos: &mut usize, len: usize) -> Result<&'a [u8]> {
790 let end = pos
791 .checked_add(len)
792 .ok_or_else(|| Error::checkpoint_corrupt("replay snapshot offset overflow"))?;
793 if end > bytes.len() {
794 return Err(Error::checkpoint_corrupt("replay snapshot is truncated"));
795 }
796 let slice = &bytes[*pos..end];
797 *pos = end;
798 Ok(slice)
799}
800
801fn take_u32(bytes: &[u8], pos: &mut usize) -> Result<u32> {
802 let slice = take_slice(bytes, pos, 4)?;
803 Ok(u32::from_le_bytes([slice[0], slice[1], slice[2], slice[3]]))
804}
805
806fn take_u64(bytes: &[u8], pos: &mut usize) -> Result<u64> {
807 let slice = take_slice(bytes, pos, 8)?;
808 Ok(u64::from_le_bytes([
809 slice[0], slice[1], slice[2], slice[3], slice[4], slice[5], slice[6], slice[7],
810 ]))
811}
812
813fn decode_f32_slice(bytes: &[u8]) -> Vec<f32> {
814 bytes
815 .as_chunks::<4>()
816 .0
817 .iter()
818 .copied()
819 .map(f32::from_le_bytes)
820 .collect()
821}
822
823fn append_dispatch(
828 transition: &ReplayTransition,
829 storage: &ReplayBatch,
830 config: &ReplayConfig,
831 cursor: usize,
832 observation_elements: u32,
833 action_elements: u32,
834) -> Result<usize> {
835 const OPERATION: &str = "oa::ml::replay::append_batch";
836 if transition.reward().dtype() != DType::F32 || transition.reward().shape().len() != 1 {
837 return Err(Error::invalid_argument(format!(
838 "{OPERATION} requires F32 reward [batch]"
839 )));
840 }
841 let batch = transition.reward().shape()[0];
842 if batch == 0 || batch > config.capacity {
843 return Err(Error::invalid_argument(format!(
844 "{OPERATION} batch must be in 1..=capacity"
845 )));
846 }
847 let observation_shape = prefixed_shape(batch, &config.observation_shape);
848 let action_shape = prefixed_shape(batch, &config.action_shape);
849 let vector_shape = [batch];
850 let fields = [
851 (
852 transition.observation(),
853 DType::F32,
854 observation_shape.as_slice(),
855 ),
856 (
857 transition.action(),
858 config.action_dtype,
859 action_shape.as_slice(),
860 ),
861 (
862 transition.next_observation(),
863 DType::F32,
864 observation_shape.as_slice(),
865 ),
866 (transition.reward(), DType::F32, vector_shape.as_slice()),
867 (transition.terminated(), DType::U8, vector_shape.as_slice()),
868 (transition.truncated(), DType::U8, vector_shape.as_slice()),
869 ];
870 for (matrix, dtype, shape) in &fields {
871 if matrix.dtype() != *dtype || matrix.shape() != *shape {
872 return Err(Error::invalid_argument(format!(
873 "{OPERATION} transition does not match the configured replay schema"
874 )));
875 }
876 if !transition.observation().runtime().same_as(matrix.runtime()) {
877 return Err(Error::invalid_argument(format!(
878 "{OPERATION} transition fields must belong to one runtime"
879 )));
880 }
881 }
882 let destinations = storage_fields(storage);
883 for destination in destinations {
884 if !transition
885 .observation()
886 .runtime()
887 .same_as(destination.runtime())
888 {
889 return Err(Error::invalid_argument(format!(
890 "{OPERATION} transition and replay buffer must belong to one runtime"
891 )));
892 }
893 if fields
894 .iter()
895 .any(|(source, _, _)| source.storage().same_as(destination.storage()))
896 {
897 return Err(Error::invalid_argument(format!(
898 "{OPERATION} transition fields must not alias replay storage"
899 )));
900 }
901 }
902 let cursor = shader_u32(cursor, "cursor", OPERATION)?;
903 let capacity = shader_u32(config.capacity, "capacity", OPERATION)?;
904 let batch_u32 = shader_u32(batch, "batch", OPERATION)?;
905 let observation_count = batch_u32.checked_mul(observation_elements).ok_or_else(|| {
906 Error::resource_exhausted(format!("{OPERATION} observation count exceeds u32"))
907 })?;
908 let action_count = batch_u32
909 .checked_mul(action_elements)
910 .ok_or_else(|| Error::resource_exhausted(format!("{OPERATION} action count exceeds u32")))?;
911 let inputs = [
912 transition.observation(),
913 transition.action(),
914 transition.next_observation(),
915 transition.reward(),
916 transition.terminated(),
917 transition.truncated(),
918 storage.observation(),
919 storage.action(),
920 storage.next_observation(),
921 storage.reward(),
922 storage.terminated(),
923 storage.truncated(),
924 ];
925 let outputs = storage_fields(storage);
926 let buffers = [
927 BufferBinding::read(transition.observation().storage()),
928 BufferBinding::read(transition.action().storage()),
929 BufferBinding::read(transition.next_observation().storage()),
930 BufferBinding::read(transition.reward().storage()),
931 BufferBinding::read(transition.terminated().storage()),
932 BufferBinding::read(transition.truncated().storage()),
933 BufferBinding::write(storage.observation().storage()),
934 BufferBinding::write(storage.action().storage()),
935 BufferBinding::write(storage.next_observation().storage()),
936 BufferBinding::write(storage.reward().storage()),
937 BufferBinding::write(storage.terminated().storage()),
938 BufferBinding::write(storage.truncated().storage()),
939 ];
940 let push_constants = [
941 PushConstant::U32(cursor),
942 PushConstant::U32(capacity),
943 PushConstant::U32(batch_u32),
944 PushConstant::U32(observation_elements),
945 PushConstant::U32(action_elements),
946 ];
947 let attributes = unsigned_attributes(&[
948 ("cursor", cursor),
949 ("capacity", capacity),
950 ("batch", batch_u32),
951 ("observation_elements", observation_elements),
952 ("action_elements", action_elements),
953 ]);
954 let kernel = KernelId::MlReplayAppendBatchF32;
955 {
956 let inputs: &[&Matrix] = &inputs;
957 let outputs: &[&Matrix] = &outputs;
958 let attributes: &[OpAttribute] = &attributes;
959 let dispatch = ComputeDispatch {
960 kernel,
961 buffers: &buffers,
962 push_constants: &push_constants,
963 workgroups: kernel.linear_workgroups(observation_count.max(action_count).max(batch_u32)),
964 indirect: None,
965 };
966 let contract = dispatch.kernel.semantic_contract().ok_or_else(|| {
967 Error::internal(format!(
968 "lowering-only kernel {} cannot own one semantic ML operation",
969 dispatch.kernel.report_name()
970 ))
971 })?;
972 let runtime = inputs
973 .first()
974 .ok_or_else(|| Error::internal("semantic ML dispatch requires an input"))?
975 .runtime();
976 runtime.record_semantic(
977 dispatch,
978 SemanticDispatch {
979 contract,
980 inputs,
981 outputs,
982 attributes,
983 },
984 )
985 }?;
986 Ok(batch)
987}
988
989#[allow(
990 clippy::too_many_arguments,
991 reason = "replay sampling keeps capacity, sample geometry, seed, and field widths explicit"
992)]
993fn sample_dispatch(
994 storage: &ReplayBatch,
995 config: &ReplayConfig,
996 size: usize,
997 batch: usize,
998 seed: u64,
999 observation_elements: u32,
1000 action_elements: u32,
1001) -> Result<ReplayBatch> {
1002 const OPERATION: &str = "oa::ml::replay::sample";
1003 let size = shader_u32(size, "size", OPERATION)?;
1004 let batch_u32 = shader_u32(batch, "batch", OPERATION)?;
1005 let observation_count = batch
1006 .checked_mul(observation_elements as usize)
1007 .ok_or_else(|| Error::resource_exhausted("replay sample observation size overflows usize"))?;
1008 let action_count = batch
1009 .checked_mul(action_elements as usize)
1010 .ok_or_else(|| Error::resource_exhausted("replay sample action size overflows usize"))?;
1011 let observation_count_u32 = shader_u32(observation_count, "observation count", OPERATION)?;
1012 let action_count_u32 = shader_u32(action_count, "action count", OPERATION)?;
1013 let mut observation_shape = vec![batch];
1014 observation_shape.extend_from_slice(&config.observation_shape);
1015 let mut action_shape = vec![batch];
1016 action_shape.extend_from_slice(&config.action_shape);
1017 let runtime = storage.observation().runtime();
1018 let result = ReplayBatch {
1019 observation: Matrix::allocate(
1020 runtime,
1021 observation_shape.clone(),
1022 observation_count,
1023 DType::F32,
1024 )?,
1025 action: Matrix::allocate(runtime, action_shape, action_count, config.action_dtype)?,
1026 next_observation: Matrix::allocate(runtime, observation_shape, observation_count, DType::F32)?,
1027 reward: Matrix::allocate(runtime, vec![batch], batch, DType::F32)?,
1028 terminated: Matrix::allocate(runtime, vec![batch], batch, DType::U8)?,
1029 truncated: Matrix::allocate(runtime, vec![batch], batch, DType::U8)?,
1030 index: Matrix::allocate(runtime, vec![batch], batch, DType::U32)?,
1031 };
1032 let inputs = storage_fields(storage);
1033 let outputs = [
1034 result.observation(),
1035 result.action(),
1036 result.next_observation(),
1037 result.reward(),
1038 result.terminated(),
1039 result.truncated(),
1040 result.index(),
1041 ];
1042 let buffers = [
1043 BufferBinding::read(storage.observation().storage()),
1044 BufferBinding::read(storage.action().storage()),
1045 BufferBinding::read(storage.next_observation().storage()),
1046 BufferBinding::read(storage.reward().storage()),
1047 BufferBinding::read(storage.terminated().storage()),
1048 BufferBinding::read(storage.truncated().storage()),
1049 BufferBinding::write(result.observation().storage()),
1050 BufferBinding::write(result.action().storage()),
1051 BufferBinding::write(result.next_observation().storage()),
1052 BufferBinding::write(result.reward().storage()),
1053 BufferBinding::write(result.terminated().storage()),
1054 BufferBinding::write(result.truncated().storage()),
1055 BufferBinding::write(result.index().storage()),
1056 ];
1057 let push_constants = [
1058 PushConstant::U32(size),
1059 PushConstant::U32(batch_u32),
1060 PushConstant::U32(observation_elements),
1061 PushConstant::U32(action_elements),
1062 PushConstant::U32(seed as u32),
1063 PushConstant::U32((seed >> 32) as u32),
1064 ];
1065 let attributes = [
1066 OpAttribute::UnsignedInteger {
1067 name: "size".into(),
1068 value: u64::from(size),
1069 },
1070 OpAttribute::UnsignedInteger {
1071 name: "batch".into(),
1072 value: u64::from(batch_u32),
1073 },
1074 OpAttribute::UnsignedInteger {
1075 name: "observation_elements".into(),
1076 value: u64::from(observation_elements),
1077 },
1078 OpAttribute::UnsignedInteger {
1079 name: "action_elements".into(),
1080 value: u64::from(action_elements),
1081 },
1082 OpAttribute::UnsignedInteger {
1083 name: "seed".into(),
1084 value: seed,
1085 },
1086 ];
1087 let kernel = KernelId::MlReplaySampleF32;
1088 {
1089 let inputs: &[&Matrix] = &inputs;
1090 let outputs: &[&Matrix] = &outputs;
1091 let attributes: &[OpAttribute] = &attributes;
1092 let dispatch = ComputeDispatch {
1093 kernel,
1094 buffers: &buffers,
1095 push_constants: &push_constants,
1096 workgroups: kernel
1097 .linear_workgroups(observation_count_u32.max(action_count_u32).max(batch_u32)),
1098 indirect: None,
1099 };
1100 let contract = dispatch.kernel.semantic_contract().ok_or_else(|| {
1101 Error::internal(format!(
1102 "lowering-only kernel {} cannot own one semantic ML operation",
1103 dispatch.kernel.report_name()
1104 ))
1105 })?;
1106 let runtime = inputs
1107 .first()
1108 .ok_or_else(|| Error::internal("semantic ML dispatch requires an input"))?
1109 .runtime();
1110 runtime.record_semantic(
1111 dispatch,
1112 SemanticDispatch {
1113 contract,
1114 inputs,
1115 outputs,
1116 attributes,
1117 },
1118 )
1119 }?;
1120 Ok(result)
1121}
1122
1123fn storage_fields(batch: &ReplayBatch) -> [&Matrix; 6] {
1128 [
1129 batch.observation(),
1130 batch.action(),
1131 batch.next_observation(),
1132 batch.reward(),
1133 batch.terminated(),
1134 batch.truncated(),
1135 ]
1136}
1137
1138fn prefixed_shape(first: usize, suffix: &[usize]) -> Vec<usize> {
1139 let mut shape = Vec::with_capacity(suffix.len() + 1);
1140 shape.push(first);
1141 shape.extend_from_slice(suffix);
1142 shape
1143}
1144
1145fn unsigned_attributes(values: &[(&'static str, u32)]) -> Vec<OpAttribute> {
1146 values
1147 .iter()
1148 .map(|(name, value)| OpAttribute::UnsignedInteger {
1149 name: (*name).into(),
1150 value: u64::from(*value),
1151 })
1152 .collect()
1153}
1154
1155fn field_elements(shape: &[usize], allow_scalar: bool) -> Result<usize> {
1156 if (!allow_scalar && shape.is_empty()) || shape.len() > 7 || shape.contains(&0) {
1157 return Err(Error::invalid_argument(
1158 "replay fields require positive rank-1..=7 observations and rank-0..=7 actions",
1159 ));
1160 }
1161 shape.iter().try_fold(1_usize, |count, extent| {
1162 count
1163 .checked_mul(*extent)
1164 .ok_or_else(|| Error::resource_exhausted("replay field size overflows usize"))
1165 })
1166}