use std::{
ffi::OsString,
fs,
io::Write,
path::{Path, PathBuf},
};
use crate::runtime::ComputeDispatch;
use crate::runtime::SemanticDispatch;
use crate::runtime::{BufferBinding, KernelId, PushConstant};
use crate::{DType, Error, Matrix, OpAttribute, Result, Runtime};
pub use crate::ml::types::ReplayConfig;
use crate::ml::validation::shader_u32;
#[derive(Clone)]
pub struct ReplayTransition {
observation: Matrix,
action: Matrix,
next_observation: Matrix,
reward: Matrix,
terminated: Matrix,
truncated: Matrix,
}
impl ReplayTransition {
pub fn new(
observation: Matrix,
action: Matrix,
next_observation: Matrix,
reward: Matrix,
terminated: Matrix,
truncated: Matrix,
) -> Self {
Self {
observation,
action,
next_observation,
reward,
terminated,
truncated,
}
}
pub const fn observation(&self) -> &Matrix {
&self.observation
}
pub const fn action(&self) -> &Matrix {
&self.action
}
pub const fn next_observation(&self) -> &Matrix {
&self.next_observation
}
pub const fn reward(&self) -> &Matrix {
&self.reward
}
pub const fn terminated(&self) -> &Matrix {
&self.terminated
}
pub const fn truncated(&self) -> &Matrix {
&self.truncated
}
}
pub struct ReplayBatch {
pub(crate) observation: Matrix,
pub(crate) action: Matrix,
pub(crate) next_observation: Matrix,
pub(crate) reward: Matrix,
pub(crate) terminated: Matrix,
pub(crate) truncated: Matrix,
pub(crate) index: Matrix,
}
impl ReplayBatch {
pub const fn observation(&self) -> &Matrix {
&self.observation
}
pub const fn action(&self) -> &Matrix {
&self.action
}
pub const fn next_observation(&self) -> &Matrix {
&self.next_observation
}
pub const fn reward(&self) -> &Matrix {
&self.reward
}
pub const fn terminated(&self) -> &Matrix {
&self.terminated
}
pub const fn truncated(&self) -> &Matrix {
&self.truncated
}
pub const fn index(&self) -> &Matrix {
&self.index
}
}
pub struct ReplayBuffer {
config: ReplayConfig,
storage: ReplayBatch,
observation_elements: u32,
action_elements: u32,
size: core::cell::Cell<usize>,
cursor: core::cell::Cell<usize>,
}
impl ReplayBuffer {
pub fn new(runtime: &Runtime, config: ReplayConfig) -> Result<Self> {
if config.capacity == 0 || !matches!(config.action_dtype, DType::F32 | DType::I32) {
return Err(Error::invalid_argument(
"ReplayBuffer requires positive capacity and F32 or I32 actions",
));
}
let observation_elements = field_elements(&config.observation_shape, false)?;
let action_elements = field_elements(&config.action_shape, true)?;
let observation_count = config
.capacity
.checked_mul(observation_elements)
.ok_or_else(|| Error::resource_exhausted("replay observation storage overflows usize"))?;
let action_count = config
.capacity
.checked_mul(action_elements)
.ok_or_else(|| Error::resource_exhausted("replay action storage overflows usize"))?;
for (label, count) in [
("capacity", config.capacity),
("observation storage", observation_count),
("action storage", action_count),
] {
u32::try_from(count).map_err(|_| {
Error::resource_exhausted(format!("replay {label} exceeds GPU u32 indexing"))
})?;
}
let observation_elements = u32::try_from(observation_elements)
.map_err(|_| Error::resource_exhausted("replay observation field exceeds u32"))?;
let action_elements = u32::try_from(action_elements)
.map_err(|_| Error::resource_exhausted("replay action field exceeds u32"))?;
let mut observation_shape = vec![config.capacity];
observation_shape.extend_from_slice(&config.observation_shape);
let mut action_shape = vec![config.capacity];
action_shape.extend_from_slice(&config.action_shape);
let handle = runtime.handle();
let storage = ReplayBatch {
observation: Matrix::allocate(
&handle,
observation_shape.clone(),
observation_count,
DType::F32,
)?,
action: Matrix::allocate(&handle, action_shape, action_count, config.action_dtype)?,
next_observation: Matrix::allocate(
&handle,
observation_shape,
observation_count,
DType::F32,
)?,
reward: Matrix::allocate(&handle, vec![config.capacity], config.capacity, DType::F32)?,
terminated: Matrix::allocate(&handle, vec![config.capacity], config.capacity, DType::U8)?,
truncated: Matrix::allocate(&handle, vec![config.capacity], config.capacity, DType::U8)?,
index: Matrix::allocate(&handle, vec![config.capacity], config.capacity, DType::U32)?,
};
Ok(Self {
config,
storage,
observation_elements,
action_elements,
size: core::cell::Cell::new(0),
cursor: core::cell::Cell::new(0),
})
}
pub fn append(&self, transition: &ReplayTransition) -> Result<()> {
let cursor = self.cursor.get();
let batch = append_dispatch(
transition,
&self.storage,
&self.config,
cursor,
self.observation_elements,
self.action_elements,
)?;
self.cursor.set((cursor + batch) % self.config.capacity);
self.size.set(
self
.config
.capacity
.min(self.size.get().saturating_add(batch)),
);
Ok(())
}
pub fn sample(&self, batch_size: usize, seed: u64) -> Result<ReplayBatch> {
if self.size.get() == 0 || batch_size == 0 {
return Err(Error::failed_precondition(
"ReplayBuffer sample requires nonempty storage and a positive batch size",
));
}
sample_dispatch(
&self.storage,
&self.config,
self.size.get(),
batch_size,
seed,
self.observation_elements,
self.action_elements,
)
}
pub fn reset(&self) {
self.size.set(0);
self.cursor.set(0);
}
pub fn is_full(&self) -> bool {
self.size.get() == self.config.capacity
}
pub fn len(&self) -> usize {
self.size.get()
}
pub const fn is_empty(&self) -> bool {
self.size.get() == 0
}
pub const fn capacity(&self) -> usize {
self.config.capacity
}
pub fn cursor(&self) -> usize {
self.cursor.get()
}
pub const fn config(&self) -> &ReplayConfig {
&self.config
}
pub fn capture_state(&self) -> Result<ReplayBufferState> {
let size = self.size.get();
let cursor = self.cursor.get();
let obs_count = size
.checked_mul(self.observation_elements as usize)
.ok_or_else(|| {
Error::resource_exhausted("replay capture observation size overflows usize")
})?;
let act_count = size
.checked_mul(self.action_elements as usize)
.ok_or_else(|| Error::resource_exhausted("replay capture action size overflows usize"))?;
if size == 0 {
return Ok(ReplayBufferState {
config: self.config.clone(),
size: 0,
cursor: 0,
observation: Vec::new(),
action_bytes: Vec::new(),
next_observation: Vec::new(),
reward: Vec::new(),
terminated: Vec::new(),
truncated: Vec::new(),
});
}
let mut observation = self.storage.observation().read_f32()?;
observation.truncate(obs_count);
let action_bytes = match self.config.action_dtype {
DType::F32 => {
let values = self.storage.action().read_f32()?;
let mut bytes = Vec::with_capacity(act_count * 4);
for &value in &values[..act_count] {
bytes.extend_from_slice(&value.to_le_bytes());
}
bytes
}
DType::I32 => {
let values = self.storage.action().read::<i32>()?;
let mut bytes = Vec::with_capacity(act_count * 4);
for &value in &values[..act_count] {
bytes.extend_from_slice(&value.to_le_bytes());
}
bytes
}
other => {
return Err(Error::invalid_argument(format!(
"unsupported replay action dtype {}",
other.token()
)));
}
};
let mut next_observation = self.storage.next_observation().read_f32()?;
next_observation.truncate(obs_count);
let mut reward = self.storage.reward().read_f32()?;
reward.truncate(size);
let mut terminated = self.storage.terminated().read::<u8>()?;
terminated.truncate(size);
let mut truncated = self.storage.truncated().read::<u8>()?;
truncated.truncate(size);
Ok(ReplayBufferState {
config: self.config.clone(),
size,
cursor,
observation,
action_bytes,
next_observation,
reward,
terminated,
truncated,
})
}
pub fn restore_state(&self, state: &ReplayBufferState) -> Result<()> {
state.validate()?;
if state.config != self.config {
return Err(Error::invalid_argument(
"replay snapshot configuration does not match destination ReplayBuffer",
));
}
if state.size == 0 {
self.size.set(0);
self.cursor.set(0);
return Ok(());
}
let runtime = self.storage.observation().runtime();
let obs_shape = prefixed_shape(state.size, &self.config.observation_shape);
let act_shape = prefixed_shape(state.size, &self.config.action_shape);
let vec_shape = vec![state.size];
let observation =
Matrix::new_from_slice_handle(runtime, obs_shape.clone(), &state.observation)?;
let action = match self.config.action_dtype {
DType::F32 => {
let values: Vec<f32> = state
.action_bytes
.as_chunks::<4>()
.0
.iter()
.copied()
.map(f32::from_le_bytes)
.collect();
Matrix::new_from_slice_handle(runtime, act_shape, &values)?
}
DType::I32 => {
let values: Vec<i32> = state
.action_bytes
.as_chunks::<4>()
.0
.iter()
.copied()
.map(i32::from_le_bytes)
.collect();
Matrix::new_from_slice_handle(runtime, act_shape, &values)?
}
other => {
return Err(Error::invalid_argument(format!(
"unsupported replay action dtype {}",
other.token()
)));
}
};
let next_observation =
Matrix::new_from_slice_handle(runtime, obs_shape, &state.next_observation)?;
let reward = Matrix::new_from_slice_handle(runtime, vec_shape.clone(), &state.reward)?;
let terminated = Matrix::new_from_slice_handle(runtime, vec_shape.clone(), &state.terminated)?;
let truncated = Matrix::new_from_slice_handle(runtime, vec_shape, &state.truncated)?;
let transition = ReplayTransition::new(
observation,
action,
next_observation,
reward,
terminated,
truncated,
);
append_dispatch(
&transition,
&self.storage,
&self.config,
0,
self.observation_elements,
self.action_elements,
)?;
runtime.checkpoint(false)?.wait()?;
self.size.set(state.size);
self.cursor.set(state.cursor);
Ok(())
}
pub fn save(&self, path: impl AsRef<Path>) -> Result<()> {
self.capture_state()?.save(path)
}
pub fn load_into(&self, path: impl AsRef<Path>) -> Result<()> {
let state = ReplayBufferState::load(path)?;
self.restore_state(&state)
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct ReplayBufferState {
config: ReplayConfig,
size: usize,
cursor: usize,
observation: Vec<f32>,
action_bytes: Vec<u8>,
next_observation: Vec<f32>,
reward: Vec<f32>,
terminated: Vec<u8>,
truncated: Vec<u8>,
}
const REPLAY_MAGIC: &[u8; 4] = b"OARP";
const REPLAY_VERSION: u32 = 1;
const REPLAY_FNV_OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
const REPLAY_FNV_PRIME: u64 = 0x0100_0000_01b3;
impl ReplayBufferState {
pub const fn config(&self) -> &ReplayConfig {
&self.config
}
pub const fn len(&self) -> usize {
self.size
}
pub const fn is_empty(&self) -> bool {
self.size == 0
}
pub const fn cursor(&self) -> usize {
self.cursor
}
pub fn encode(&self) -> Result<Vec<u8>> {
self.validate()?;
let mut bytes = Vec::new();
bytes.extend_from_slice(REPLAY_MAGIC);
bytes.extend_from_slice(&REPLAY_VERSION.to_le_bytes());
bytes.extend_from_slice(&(self.config.capacity as u64).to_le_bytes());
bytes.extend_from_slice(&(self.size as u64).to_le_bytes());
bytes.extend_from_slice(&(self.cursor as u64).to_le_bytes());
let dtype_tag: u8 = match self.config.action_dtype {
DType::F32 => 0,
DType::I32 => 1,
_ => {
return Err(Error::invalid_argument(
"replay snapshot only supports F32 or I32 actions",
));
}
};
bytes.push(dtype_tag);
bytes.extend_from_slice(&(self.config.observation_shape.len() as u32).to_le_bytes());
for &extent in &self.config.observation_shape {
bytes.extend_from_slice(&(extent as u64).to_le_bytes());
}
bytes.extend_from_slice(&(self.config.action_shape.len() as u32).to_le_bytes());
for &extent in &self.config.action_shape {
bytes.extend_from_slice(&(extent as u64).to_le_bytes());
}
for &value in &self.observation {
bytes.extend_from_slice(&value.to_le_bytes());
}
bytes.extend_from_slice(&self.action_bytes);
for &value in &self.next_observation {
bytes.extend_from_slice(&value.to_le_bytes());
}
for &value in &self.reward {
bytes.extend_from_slice(&value.to_le_bytes());
}
bytes.extend_from_slice(&self.terminated);
bytes.extend_from_slice(&self.truncated);
let checksum = replay_fnv64(&bytes);
bytes.extend_from_slice(&checksum.to_le_bytes());
Ok(bytes)
}
pub fn decode(bytes: &[u8]) -> Result<Self> {
if bytes.len() < 8 {
return Err(Error::checkpoint_corrupt("replay snapshot is truncated"));
}
let (body, tail) = bytes.split_at(bytes.len() - 8);
let expected_checksum = u64::from_le_bytes(tail.try_into().expect("8-byte tail"));
if replay_fnv64(body) != expected_checksum {
return Err(Error::checkpoint_corrupt(
"replay snapshot checksum verification failed",
));
}
let mut cursor_pos = 0_usize;
let magic = take_slice(body, &mut cursor_pos, 4)?;
if magic != REPLAY_MAGIC {
return Err(Error::checkpoint_corrupt(
"replay snapshot has invalid magic",
));
}
let version = take_u32(body, &mut cursor_pos)?;
if version != REPLAY_VERSION {
return Err(Error::checkpoint_corrupt(format!(
"unsupported replay snapshot version {version}"
)));
}
let capacity = usize::try_from(take_u64(body, &mut cursor_pos)?)
.map_err(|_| Error::checkpoint_corrupt("replay capacity exceeds usize"))?;
let size = usize::try_from(take_u64(body, &mut cursor_pos)?)
.map_err(|_| Error::checkpoint_corrupt("replay size exceeds usize"))?;
let write_cursor = usize::try_from(take_u64(body, &mut cursor_pos)?)
.map_err(|_| Error::checkpoint_corrupt("replay cursor exceeds usize"))?;
let dtype_tag = take_slice(body, &mut cursor_pos, 1)?[0];
let action_dtype = match dtype_tag {
0 => DType::F32,
1 => DType::I32,
_ => {
return Err(Error::checkpoint_corrupt(format!(
"unknown replay action dtype tag {dtype_tag}"
)));
}
};
let obs_rank = take_u32(body, &mut cursor_pos)? as usize;
if obs_rank == 0 || obs_rank > 7 {
return Err(Error::checkpoint_corrupt(
"replay observation rank out of range",
));
}
let mut observation_shape = Vec::with_capacity(obs_rank);
for _ in 0..obs_rank {
let extent = usize::try_from(take_u64(body, &mut cursor_pos)?)
.map_err(|_| Error::checkpoint_corrupt("replay observation extent exceeds usize"))?;
observation_shape.push(extent);
}
let act_rank = take_u32(body, &mut cursor_pos)? as usize;
if act_rank > 7 {
return Err(Error::checkpoint_corrupt("replay action rank out of range"));
}
let mut action_shape = Vec::with_capacity(act_rank);
for _ in 0..act_rank {
let extent = usize::try_from(take_u64(body, &mut cursor_pos)?)
.map_err(|_| Error::checkpoint_corrupt("replay action extent exceeds usize"))?;
action_shape.push(extent);
}
let config = ReplayConfig {
capacity,
observation_shape,
action_shape,
action_dtype,
};
let obs_elems = field_elements(&config.observation_shape, false)
.map_err(|_| Error::checkpoint_corrupt("invalid replay observation shape"))?;
let act_elems = field_elements(&config.action_shape, true)
.map_err(|_| Error::checkpoint_corrupt("invalid replay action shape"))?;
let obs_count = size
.checked_mul(obs_elems)
.ok_or_else(|| Error::checkpoint_corrupt("replay observation count overflow"))?;
let act_byte_count = size
.checked_mul(act_elems)
.and_then(|count| count.checked_mul(4))
.ok_or_else(|| Error::checkpoint_corrupt("replay action byte count overflow"))?;
let obs_bytes = obs_count
.checked_mul(4)
.ok_or_else(|| Error::checkpoint_corrupt("replay observation byte count overflow"))?;
let reward_bytes = size
.checked_mul(4)
.ok_or_else(|| Error::checkpoint_corrupt("replay reward byte count overflow"))?;
let observation = decode_f32_slice(take_slice(body, &mut cursor_pos, obs_bytes)?);
let action_bytes = take_slice(body, &mut cursor_pos, act_byte_count)?.to_vec();
let next_observation = decode_f32_slice(take_slice(body, &mut cursor_pos, obs_bytes)?);
let reward = decode_f32_slice(take_slice(body, &mut cursor_pos, reward_bytes)?);
let terminated = take_slice(body, &mut cursor_pos, size)?.to_vec();
let truncated = take_slice(body, &mut cursor_pos, size)?.to_vec();
if cursor_pos != body.len() {
return Err(Error::checkpoint_corrupt(
"replay snapshot has trailing bytes",
));
}
let state = Self {
config,
size,
cursor: write_cursor,
observation,
action_bytes,
next_observation,
reward,
terminated,
truncated,
};
state
.validate()
.map_err(|error| Error::checkpoint_corrupt(error.message()))?;
Ok(state)
}
pub fn save(&self, path: impl AsRef<Path>) -> Result<()> {
let path = path.as_ref();
let bytes = self.encode()?;
let mut tmp_os = OsString::from(path.as_os_str());
tmp_os.push(".tmp");
let temporary = PathBuf::from(tmp_os);
{
let mut file = fs::File::create(&temporary)
.map_err(|error| Error::io("create replay temporary", error))?;
file
.write_all(&bytes)
.map_err(|error| Error::io("write replay temporary", error))?;
file
.sync_all()
.map_err(|error| Error::io("flush replay temporary", error))?;
}
fs::rename(&temporary, path).map_err(|error| Error::io("commit replay snapshot", error))
}
pub fn load(path: impl AsRef<Path>) -> Result<Self> {
let path = path.as_ref();
let bytes = fs::read(path).map_err(|error| Error::io("read replay snapshot", error))?;
Self::decode(&bytes)
}
fn validate(&self) -> Result<()> {
if self.config.capacity == 0 || !matches!(self.config.action_dtype, DType::F32 | DType::I32) {
return Err(Error::invalid_argument(
"replay snapshot requires positive capacity and F32 or I32 actions",
));
}
let obs_elems = field_elements(&self.config.observation_shape, false)?;
let act_elems = field_elements(&self.config.action_shape, true)?;
if self.size > self.config.capacity || self.cursor >= self.config.capacity {
return Err(Error::invalid_argument(
"replay snapshot size or cursor exceeds configured capacity",
));
}
if self.size < self.config.capacity && self.cursor != self.size {
return Err(Error::invalid_argument(
"unwrapped replay snapshot cursor must equal size",
));
}
let expected_obs = self
.size
.checked_mul(obs_elems)
.ok_or_else(|| Error::resource_exhausted("replay snapshot observation count overflow"))?;
let expected_act_bytes = self
.size
.checked_mul(act_elems)
.and_then(|count| count.checked_mul(4))
.ok_or_else(|| Error::resource_exhausted("replay snapshot action byte count overflow"))?;
if self.observation.len() != expected_obs
|| self.next_observation.len() != expected_obs
|| self.action_bytes.len() != expected_act_bytes
|| self.reward.len() != self.size
|| self.terminated.len() != self.size
|| self.truncated.len() != self.size
{
return Err(Error::invalid_argument(
"replay snapshot payload lengths do not match schema and size",
));
}
Ok(())
}
}
fn replay_fnv64(bytes: &[u8]) -> u64 {
bytes.iter().fold(REPLAY_FNV_OFFSET, |hash, byte| {
(hash ^ u64::from(*byte)).wrapping_mul(REPLAY_FNV_PRIME)
})
}
fn take_slice<'a>(bytes: &'a [u8], pos: &mut usize, len: usize) -> Result<&'a [u8]> {
let end = pos
.checked_add(len)
.ok_or_else(|| Error::checkpoint_corrupt("replay snapshot offset overflow"))?;
if end > bytes.len() {
return Err(Error::checkpoint_corrupt("replay snapshot is truncated"));
}
let slice = &bytes[*pos..end];
*pos = end;
Ok(slice)
}
fn take_u32(bytes: &[u8], pos: &mut usize) -> Result<u32> {
let slice = take_slice(bytes, pos, 4)?;
Ok(u32::from_le_bytes([slice[0], slice[1], slice[2], slice[3]]))
}
fn take_u64(bytes: &[u8], pos: &mut usize) -> Result<u64> {
let slice = take_slice(bytes, pos, 8)?;
Ok(u64::from_le_bytes([
slice[0], slice[1], slice[2], slice[3], slice[4], slice[5], slice[6], slice[7],
]))
}
fn decode_f32_slice(bytes: &[u8]) -> Vec<f32> {
bytes
.as_chunks::<4>()
.0
.iter()
.copied()
.map(f32::from_le_bytes)
.collect()
}
fn append_dispatch(
transition: &ReplayTransition,
storage: &ReplayBatch,
config: &ReplayConfig,
cursor: usize,
observation_elements: u32,
action_elements: u32,
) -> Result<usize> {
const OPERATION: &str = "oa::ml::replay::append_batch";
if transition.reward().dtype() != DType::F32 || transition.reward().shape().len() != 1 {
return Err(Error::invalid_argument(format!(
"{OPERATION} requires F32 reward [batch]"
)));
}
let batch = transition.reward().shape()[0];
if batch == 0 || batch > config.capacity {
return Err(Error::invalid_argument(format!(
"{OPERATION} batch must be in 1..=capacity"
)));
}
let observation_shape = prefixed_shape(batch, &config.observation_shape);
let action_shape = prefixed_shape(batch, &config.action_shape);
let vector_shape = [batch];
let fields = [
(
transition.observation(),
DType::F32,
observation_shape.as_slice(),
),
(
transition.action(),
config.action_dtype,
action_shape.as_slice(),
),
(
transition.next_observation(),
DType::F32,
observation_shape.as_slice(),
),
(transition.reward(), DType::F32, vector_shape.as_slice()),
(transition.terminated(), DType::U8, vector_shape.as_slice()),
(transition.truncated(), DType::U8, vector_shape.as_slice()),
];
for (matrix, dtype, shape) in &fields {
if matrix.dtype() != *dtype || matrix.shape() != *shape {
return Err(Error::invalid_argument(format!(
"{OPERATION} transition does not match the configured replay schema"
)));
}
if !transition.observation().runtime().same_as(matrix.runtime()) {
return Err(Error::invalid_argument(format!(
"{OPERATION} transition fields must belong to one runtime"
)));
}
}
let destinations = storage_fields(storage);
for destination in destinations {
if !transition
.observation()
.runtime()
.same_as(destination.runtime())
{
return Err(Error::invalid_argument(format!(
"{OPERATION} transition and replay buffer must belong to one runtime"
)));
}
if fields
.iter()
.any(|(source, _, _)| source.storage().same_as(destination.storage()))
{
return Err(Error::invalid_argument(format!(
"{OPERATION} transition fields must not alias replay storage"
)));
}
}
let cursor = shader_u32(cursor, "cursor", OPERATION)?;
let capacity = shader_u32(config.capacity, "capacity", OPERATION)?;
let batch_u32 = shader_u32(batch, "batch", OPERATION)?;
let observation_count = batch_u32.checked_mul(observation_elements).ok_or_else(|| {
Error::resource_exhausted(format!("{OPERATION} observation count exceeds u32"))
})?;
let action_count = batch_u32
.checked_mul(action_elements)
.ok_or_else(|| Error::resource_exhausted(format!("{OPERATION} action count exceeds u32")))?;
let inputs = [
transition.observation(),
transition.action(),
transition.next_observation(),
transition.reward(),
transition.terminated(),
transition.truncated(),
storage.observation(),
storage.action(),
storage.next_observation(),
storage.reward(),
storage.terminated(),
storage.truncated(),
];
let outputs = storage_fields(storage);
let buffers = [
BufferBinding::read(transition.observation().storage()),
BufferBinding::read(transition.action().storage()),
BufferBinding::read(transition.next_observation().storage()),
BufferBinding::read(transition.reward().storage()),
BufferBinding::read(transition.terminated().storage()),
BufferBinding::read(transition.truncated().storage()),
BufferBinding::write(storage.observation().storage()),
BufferBinding::write(storage.action().storage()),
BufferBinding::write(storage.next_observation().storage()),
BufferBinding::write(storage.reward().storage()),
BufferBinding::write(storage.terminated().storage()),
BufferBinding::write(storage.truncated().storage()),
];
let push_constants = [
PushConstant::U32(cursor),
PushConstant::U32(capacity),
PushConstant::U32(batch_u32),
PushConstant::U32(observation_elements),
PushConstant::U32(action_elements),
];
let attributes = unsigned_attributes(&[
("cursor", cursor),
("capacity", capacity),
("batch", batch_u32),
("observation_elements", observation_elements),
("action_elements", action_elements),
]);
let kernel = KernelId::MlReplayAppendBatchF32;
{
let inputs: &[&Matrix] = &inputs;
let outputs: &[&Matrix] = &outputs;
let attributes: &[OpAttribute] = &attributes;
let dispatch = ComputeDispatch {
kernel,
buffers: &buffers,
push_constants: &push_constants,
workgroups: kernel.linear_workgroups(observation_count.max(action_count).max(batch_u32)),
indirect: None,
};
let contract = dispatch.kernel.semantic_contract().ok_or_else(|| {
Error::internal(format!(
"lowering-only kernel {} cannot own one semantic ML operation",
dispatch.kernel.report_name()
))
})?;
let runtime = inputs
.first()
.ok_or_else(|| Error::internal("semantic ML dispatch requires an input"))?
.runtime();
runtime.record_semantic(
dispatch,
SemanticDispatch {
contract,
inputs,
outputs,
attributes,
},
)
}?;
Ok(batch)
}
#[allow(
clippy::too_many_arguments,
reason = "replay sampling keeps capacity, sample geometry, seed, and field widths explicit"
)]
fn sample_dispatch(
storage: &ReplayBatch,
config: &ReplayConfig,
size: usize,
batch: usize,
seed: u64,
observation_elements: u32,
action_elements: u32,
) -> Result<ReplayBatch> {
const OPERATION: &str = "oa::ml::replay::sample";
let size = shader_u32(size, "size", OPERATION)?;
let batch_u32 = shader_u32(batch, "batch", OPERATION)?;
let observation_count = batch
.checked_mul(observation_elements as usize)
.ok_or_else(|| Error::resource_exhausted("replay sample observation size overflows usize"))?;
let action_count = batch
.checked_mul(action_elements as usize)
.ok_or_else(|| Error::resource_exhausted("replay sample action size overflows usize"))?;
let observation_count_u32 = shader_u32(observation_count, "observation count", OPERATION)?;
let action_count_u32 = shader_u32(action_count, "action count", OPERATION)?;
let mut observation_shape = vec![batch];
observation_shape.extend_from_slice(&config.observation_shape);
let mut action_shape = vec![batch];
action_shape.extend_from_slice(&config.action_shape);
let runtime = storage.observation().runtime();
let result = ReplayBatch {
observation: Matrix::allocate(
runtime,
observation_shape.clone(),
observation_count,
DType::F32,
)?,
action: Matrix::allocate(runtime, action_shape, action_count, config.action_dtype)?,
next_observation: Matrix::allocate(runtime, observation_shape, observation_count, DType::F32)?,
reward: Matrix::allocate(runtime, vec![batch], batch, DType::F32)?,
terminated: Matrix::allocate(runtime, vec![batch], batch, DType::U8)?,
truncated: Matrix::allocate(runtime, vec![batch], batch, DType::U8)?,
index: Matrix::allocate(runtime, vec![batch], batch, DType::U32)?,
};
let inputs = storage_fields(storage);
let outputs = [
result.observation(),
result.action(),
result.next_observation(),
result.reward(),
result.terminated(),
result.truncated(),
result.index(),
];
let buffers = [
BufferBinding::read(storage.observation().storage()),
BufferBinding::read(storage.action().storage()),
BufferBinding::read(storage.next_observation().storage()),
BufferBinding::read(storage.reward().storage()),
BufferBinding::read(storage.terminated().storage()),
BufferBinding::read(storage.truncated().storage()),
BufferBinding::write(result.observation().storage()),
BufferBinding::write(result.action().storage()),
BufferBinding::write(result.next_observation().storage()),
BufferBinding::write(result.reward().storage()),
BufferBinding::write(result.terminated().storage()),
BufferBinding::write(result.truncated().storage()),
BufferBinding::write(result.index().storage()),
];
let push_constants = [
PushConstant::U32(size),
PushConstant::U32(batch_u32),
PushConstant::U32(observation_elements),
PushConstant::U32(action_elements),
PushConstant::U32(seed as u32),
PushConstant::U32((seed >> 32) as u32),
];
let attributes = [
OpAttribute::UnsignedInteger {
name: "size".into(),
value: u64::from(size),
},
OpAttribute::UnsignedInteger {
name: "batch".into(),
value: u64::from(batch_u32),
},
OpAttribute::UnsignedInteger {
name: "observation_elements".into(),
value: u64::from(observation_elements),
},
OpAttribute::UnsignedInteger {
name: "action_elements".into(),
value: u64::from(action_elements),
},
OpAttribute::UnsignedInteger {
name: "seed".into(),
value: seed,
},
];
let kernel = KernelId::MlReplaySampleF32;
{
let inputs: &[&Matrix] = &inputs;
let outputs: &[&Matrix] = &outputs;
let attributes: &[OpAttribute] = &attributes;
let dispatch = ComputeDispatch {
kernel,
buffers: &buffers,
push_constants: &push_constants,
workgroups: kernel
.linear_workgroups(observation_count_u32.max(action_count_u32).max(batch_u32)),
indirect: None,
};
let contract = dispatch.kernel.semantic_contract().ok_or_else(|| {
Error::internal(format!(
"lowering-only kernel {} cannot own one semantic ML operation",
dispatch.kernel.report_name()
))
})?;
let runtime = inputs
.first()
.ok_or_else(|| Error::internal("semantic ML dispatch requires an input"))?
.runtime();
runtime.record_semantic(
dispatch,
SemanticDispatch {
contract,
inputs,
outputs,
attributes,
},
)
}?;
Ok(result)
}
fn storage_fields(batch: &ReplayBatch) -> [&Matrix; 6] {
[
batch.observation(),
batch.action(),
batch.next_observation(),
batch.reward(),
batch.terminated(),
batch.truncated(),
]
}
fn prefixed_shape(first: usize, suffix: &[usize]) -> Vec<usize> {
let mut shape = Vec::with_capacity(suffix.len() + 1);
shape.push(first);
shape.extend_from_slice(suffix);
shape
}
fn unsigned_attributes(values: &[(&'static str, u32)]) -> Vec<OpAttribute> {
values
.iter()
.map(|(name, value)| OpAttribute::UnsignedInteger {
name: (*name).into(),
value: u64::from(*value),
})
.collect()
}
fn field_elements(shape: &[usize], allow_scalar: bool) -> Result<usize> {
if (!allow_scalar && shape.is_empty()) || shape.len() > 7 || shape.contains(&0) {
return Err(Error::invalid_argument(
"replay fields require positive rank-1..=7 observations and rank-0..=7 actions",
));
}
shape.iter().try_fold(1_usize, |count, extent| {
count
.checked_mul(*extent)
.ok_or_else(|| Error::resource_exhausted("replay field size overflows usize"))
})
}