replay_buffer
replay_buffer
¶
ReplayBuffer
¶
Manages a replay buffer dataset in Zarr or NumPy format for storing episodes of data.
The buffer organizes data into 'data' (arrays for observations, actions, etc.) and 'meta' (episode_ends array tracking cumulative step counts per episode). Supports creation from scratch, loading from paths/stores, copying with optional rechunking/recompression, saving, adding/dropping episodes, slicing, and backend-agnostic access (Zarr for disk, NumPy for in-memory). Ensures data consistency across keys. Uses cached properties for efficiency. Supports custom chunks and compressors per array key.
Attributes:
| Name | Type | Description |
|---|---|---|
root |
Union[zarr.Group, Dict] holding 'data' and 'meta' groups/dicts. |
Methods:
| Name | Description |
|---|---|
create_empty_zarr |
Classmethod to create an empty Zarr-based buffer. |
create_empty_numpy |
Classmethod to create an empty NumPy-based buffer. |
create_from_group |
Classmethod to create from existing Zarr group. |
create_from_path |
Classmethod to load from Zarr file path. |
copy_from_store |
Classmethod to copy from source store with optional modifications. |
copy_from_path |
Classmethod to copy from Zarr path. |
save_to_store |
Save buffer to a store with optional rechunk/recompress. |
save_to_path |
Save to a file path. |
resolve_compressor |
Staticmethod to get Blosc compressor by name. |
_resolve_array_compressor |
Classmethod to resolve compressor for a key. |
_resolve_array_chunks |
Classmethod to resolve chunks for a key. |
data |
Cached property for data group/dict. |
meta |
Cached property for meta group/dict. |
update_meta |
Update meta with new key-value pairs as arrays. |
episode_ends |
Property for episode_ends array. |
get_episode_idxs |
Get array mapping steps to episode indices (Numba-optimized). |
backend |
Property detecting 'zarr' or 'numpy'. |
__repr__ |
String representation (Zarr tree or default). |
keys/values/items/__getitem__/__contains__ |
Dict-like access to data. |
n_steps |
Total number of steps. |
n_episodes |
Number of episodes. |
chunk_size |
First chunk size if Zarr. |
episode_lengths |
Array of episode lengths. |
add_episode |
Append a new episode (dict of arrays). |
drop_episode |
Remove the last episode. |
pop_episode |
Get and remove the last episode. |
extend |
Alias for add_episode. |
get_episode |
Get episode by index as dict of arrays. |
get_episode_slice |
Get slice for an episode. |
get_steps_slice |
Get sliced data dict for step range. |
get_chunks |
Get current chunks dict (Zarr only). |
set_chunks |
Set new chunks per key (Zarr only). |
get_compressors |
Get current compressors dict (Zarr only). |
set_compressors |
Set new compressors per key (Zarr only). |
Initializes the ReplayBuffer with a root group or dict.
Validates presence of 'data', 'meta', 'episode_ends', and shape consistency across data arrays.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
root
|
Group | dict[str, dict]
|
Zarr Group or dict with 'data' and 'meta' substructures. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If root is missing required keys or data shapes are inconsistent. |
Source code in src/versatil/data/preprocessing/replay_buffer.py
create_empty_zarr
classmethod
¶
Creates an empty Zarr-based ReplayBuffer.
Initializes 'data' and 'meta' groups, with 'episode_ends' as an empty int64 array.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
storage
|
LocalStore | MemoryStore | None
|
Optional Zarr store (defaults to MemoryStore). |
None
|
root
|
Group | None
|
Optional existing Zarr group to use. |
None
|
Returns:
| Type | Description |
|---|---|
ReplayBuffer
|
ReplayBuffer instance. |
Source code in src/versatil/data/preprocessing/replay_buffer.py
create_empty_numpy
classmethod
¶
Creates an empty NumPy-based ReplayBuffer.
Initializes root as dict with empty 'data' dict and 'meta' with zero-length episode_ends array.
Returns:
| Type | Description |
|---|---|
ReplayBuffer
|
ReplayBuffer instance. |
Source code in src/versatil/data/preprocessing/replay_buffer.py
create_from_group
classmethod
¶
Creates ReplayBuffer from an existing Zarr group.
If 'data' missing, creates empty; else loads existing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
group
|
Group
|
Zarr group. |
required |
Returns:
| Type | Description |
|---|---|
ReplayBuffer
|
ReplayBuffer instance. |
Source code in src/versatil/data/preprocessing/replay_buffer.py
create_from_path
classmethod
¶
Loads ReplayBuffer from a Zarr file path in read mode.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
zarr_path
|
str
|
Path to Zarr directory. |
required |
Returns:
| Type | Description |
|---|---|
ReplayBuffer
|
ReplayBuffer instance. |
Source code in src/versatil/data/preprocessing/replay_buffer.py
copy_from_store
classmethod
¶
copy_from_store(src_store, store=None, keys=None, chunks=None, compressors=None, if_exists='replace', **kwargs)
Copies a ReplayBuffer from source store to new store or NumPy dict.
If store None, copies to NumPy dict; else to Zarr store. Selectively copies keys, applying custom chunks/compressors if specified, otherwise preserves or defaults.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
src_store
|
LocalStore | MemoryStore
|
Source Zarr store. |
required |
store
|
LocalStore | MemoryStore | None
|
Optional destination store (None for NumPy). |
None
|
keys
|
list[str] | None
|
Optional list of data keys to copy (all if None). |
None
|
chunks
|
dict[str, tuple] | None
|
Dict of key to chunks tuple, or fallback to source/optimal. |
None
|
compressors
|
dict | str | BloscCodec | None
|
Dict or single compressor, resolved per key. |
None
|
if_exists
|
str
|
Zarr copy behavior ('replace', etc.). |
'replace'
|
**kwargs
|
Any
|
Unused. |
{}
|
Returns:
| Type | Description |
|---|---|
ReplayBuffer
|
ReplayBuffer instance from copied data. |
Source code in src/versatil/data/preprocessing/replay_buffer.py
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 | |
copy_from_path
classmethod
¶
copy_from_path(zarr_path, backend=None, store=None, keys=None, chunks=None, compressors=None, if_exists='replace', **kwargs)
Copies ReplayBuffer from Zarr path, optionally to store or NumPy.
Warns if backend specified (deprecated). Expands user path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
zarr_path
|
str
|
Source Zarr directory path. |
required |
backend
|
str | None
|
Deprecated; use store=None for NumPy. |
None
|
store
|
LocalStore | MemoryStore | None
|
Destination store (None for NumPy). |
None
|
keys
|
list[str] | None
|
Optional list of data keys to copy (all if None). |
None
|
chunks
|
dict[str, tuple] | None
|
Dict of key to chunks tuple, or fallback to source/optimal. |
None
|
compressors
|
dict | str | BloscCodec | None
|
Dict or single compressor, resolved per key. |
None
|
if_exists
|
str
|
Zarr copy behavior ('replace', etc.). |
'replace'
|
**kwargs
|
Any
|
Passed to copy_from_store. |
{}
|
Returns:
| Type | Description |
|---|---|
ReplayBuffer
|
ReplayBuffer instance. |
Source code in src/versatil/data/preprocessing/replay_buffer.py
save_to_store
¶
Write the replay buffer into a Zarr store with optional chunking and codecs.
Source code in src/versatil/data/preprocessing/replay_buffer.py
save_to_path
¶
Saves to a local Zarr path using LocalStore.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
zarr_path
|
str
|
Destination path. |
required |
chunks
|
dict[str, tuple] | None
|
Per-key chunks for arrays. |
None
|
compressors
|
str | BloscCodec | dict | None
|
Per-key or global compressor. |
None
|
if_exists
|
str
|
Zarr write mode ('replace', etc.). |
'replace'
|
**kwargs
|
Any
|
Passed to save_to_store. |
{}
|
Returns:
| Type | Description |
|---|---|
LocalStore
|
The store. |
Source code in src/versatil/data/preprocessing/replay_buffer.py
resolve_compressor
staticmethod
¶
Resolves compressor string to BloscCodec instance.
'default': lz4 level 5, no shuffle. 'disk': zstd level 5, bitshuffle.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
compressor
|
str | BloscCodec
|
'default', 'disk', or BloscCodec instance. |
'default'
|
Returns:
| Type | Description |
|---|---|
BloscCodec
|
BloscCodec. |
Source code in src/versatil/data/preprocessing/replay_buffer.py
update_meta
¶
Updates meta with new key-value pairs as NumPy arrays.
Converts values to arrays if needed, overwrites existing keys. For Zarr, creates arrays with no compression; for NumPy, dict update.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
dict[str, ndarray | list | int | float]
|
Dict of key to value (scalar/list/array). |
required |
Returns:
| Type | Description |
|---|---|
Group | dict[str, ndarray]
|
Updated meta group/dict. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If value can't be converted to non-object array. |
Source code in src/versatil/data/preprocessing/replay_buffer.py
get_episode_idxs
¶
Computes array mapping each step to its episode index.
Uses Numba-jitted function for efficiency.
Returns:
| Type | Description |
|---|---|
ndarray
|
NumPy array of episode indices per step. |
Source code in src/versatil/data/preprocessing/replay_buffer.py
__repr__
¶
String representation: Zarr tree or default repr.
Source code in src/versatil/data/preprocessing/replay_buffer.py
keys
¶
values
¶
items
¶
__getitem__
¶
__contains__
¶
add_episode
¶
Adds an episode as dict of arrays, resizing all data arrays.
Creates new keys if needed with resolved chunks/compressors. Appends to episode_ends, rechunks if grown significantly (Zarr).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
dict[str, ndarray]
|
Dict of key to NumPy array (consistent lengths). |
required |
chunks
|
dict[str, tuple] | None
|
Per-key chunks for new arrays. |
None
|
compressors
|
str | BloscCodec | dict | None
|
Per-key or global for new arrays. |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If empty data, inconsistent lengths, or mismatched shapes. |
Source code in src/versatil/data/preprocessing/replay_buffer.py
813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 | |
drop_episode
¶
Drops the last episode by resizing arrays backward.
Raises:
| Type | Description |
|---|---|
ValueError
|
If no episodes to drop. |
Source code in src/versatil/data/preprocessing/replay_buffer.py
pop_episode
¶
Gets the last episode and drops it.
Returns:
| Type | Description |
|---|---|
dict[str, ndarray]
|
Dict of arrays for the episode. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no episodes to pop. |
Source code in src/versatil/data/preprocessing/replay_buffer.py
extend
¶
Alias for add_episode.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
dict[str, ndarray]
|
As in add_episode. |
required |
get_episode
¶
Gets an episode by index as dict of sliced arrays.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
idx
|
int
|
Episode index (handles negative via list). |
required |
copy
|
bool
|
If True, copy NumPy arrays. |
False
|
Returns:
| Type | Description |
|---|---|
dict[str, ndarray]
|
Dict of key to array slice. |
Source code in src/versatil/data/preprocessing/replay_buffer.py
get_episode_slice
¶
Gets the slice object for an episode's steps.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
idx
|
int
|
Episode index. |
required |
Returns:
| Type | Description |
|---|---|
slice
|
slice(start, end) |
Source code in src/versatil/data/preprocessing/replay_buffer.py
get_steps_slice
¶
Gets dict of sliced arrays for a step range.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
start
|
int
|
Start step index. |
required |
stop
|
int
|
Stop step index. |
required |
step
|
int | None
|
Step size for slicing. |
None
|
copy
|
bool
|
Copy if NumPy backend. |
False
|
Returns:
| Type | Description |
|---|---|
dict[str, ndarray]
|
Dict of key to sliced array. |
Source code in src/versatil/data/preprocessing/replay_buffer.py
get_chunks
¶
Gets current chunks per data key (Zarr only).
Returns:
| Type | Description |
|---|---|
dict[str, tuple[int, ...]]
|
Dict of key to chunks tuple. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If not Zarr backend. |
Source code in src/versatil/data/preprocessing/replay_buffer.py
set_chunks
¶
Sets new chunks per data key if changed (Zarr only).
Uses rechunk_recompress_array.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
chunks
|
dict[str, tuple[int, ...]]
|
Dict of key to new chunks tuple. |
required |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If not Zarr backend. |
Source code in src/versatil/data/preprocessing/replay_buffer.py
get_compressors
¶
Gets current codec per data key (Zarr only).
Returns BloscCodec for numerically compressed arrays, WebPCodec for image arrays using WebP serialization, or None if uncompressed.
Returns:
| Type | Description |
|---|---|
dict[str, BloscCodec | WebPCodec | None]
|
Dict mapping key to BloscCodec, WebPCodec, or None. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If not Zarr backend. |
Source code in src/versatil/data/preprocessing/replay_buffer.py
set_compressors
¶
Sets new compressor per data key if changed (Zarr only).
Resolves strings, uses rechunk_recompress_array.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
compressors
|
dict[str, str | BloscCodec | WebPCodec]
|
Dict of key to compressor/str. |
required |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If not Zarr backend. |
Source code in src/versatil/data/preprocessing/replay_buffer.py
check_chunks_compatible
¶
Checks if given chunks are compatible with the array shape.
Ensures that chunks and shape have the same dimensionality, each chunk size is a positive integer, and implicitly that chunks do not exceed shape dimensions (though not explicitly checked here).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
chunks
|
tuple[int, ...]
|
Tuple of chunk sizes for each dimension. |
required |
shape
|
tuple[int, ...]
|
Tuple of array shape dimensions. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If lengths differ or chunks are not positive. |
TypeError
|
If chunks are not integral. |
Source code in src/versatil/data/preprocessing/replay_buffer.py
rechunk_recompress_array
¶
rechunk_recompress_array(group, name, chunks=None, chunk_length=None, compressor=None, tmp_key='_temp')
Rechunk and/or recompress an existing zarr array.
Preserves the original codec (BloscCodec or WebPCodec) if no explicit compressor is provided. For WebPCodec arrays the codec is read from the array's metadata codec pipeline since it is a serializer, not a compressor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
group
|
Group
|
Zarr group containing the array. |
required |
name
|
str
|
Name of the array to rechunk/recompress. |
required |
chunks
|
tuple | None
|
New chunk sizes. Defaults to existing chunks. |
None
|
chunk_length
|
int | None
|
Shorthand to override only the first chunk dimension. |
None
|
compressor
|
BloscCodec | WebPCodec | None
|
New codec. Defaults to the array's existing codec. |
None
|
tmp_key
|
str
|
Temporary key used during rechunking (unused, kept for API). |
'_temp'
|
Source code in src/versatil/data/preprocessing/replay_buffer.py
get_optimal_chunks
¶
Computes optimal chunk sizes for an array to target a specific chunk byte size.
Reverses shape to prioritize inner dimensions, caps outer dimension if max_chunk_length given. Finds the split point where adding another dimension exceeds target bytes, then adjusts the last chunk to meet the target. Pads with 1s if needed for dimensionality.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
shape
|
tuple[int, ...]
|
Tuple of array dimensions. |
required |
dtype
|
dtype | type
|
NumPy dtype of the array. |
required |
target_chunk_bytes
|
float
|
Desired approximate bytes per chunk (default 2MB). |
2000000.0
|
max_chunk_length
|
int | None
|
Optional cap on the outermost chunk size. |
None
|
Returns:
| Type | Description |
|---|---|
tuple[int, ...]
|
Tuple of optimal chunk sizes. |