relayrl_types
Core data types and encoding/decoding utilities for the RelayRL framework.
Features
RelayRLAction: Serializable action container (obs, act, mask, reward, data, done) with UUID agent trackingRelayRLTrajectory: In-memory trajectory buffer with metadata and provenance trackingRecords: Records for converting trajectories to and from CSV and Arrow files- Burn backend support: Compatible with both
burn-ndarray(CPU) andburn-tch(GPU) backends - Codec pipeline: Compression, encryption, integrity verification, and chunking
- Utilities: Metadata tracking, quantization, and network transport optimizations
Feature Flags
The crate's actual default set is ["ndarray-backend", "onnx-model"] — the CPU Burn
backend plus ONNX inference. Codec features (compression, encryption, integrity,
metadata, quantization, zerocopy) are not enabled by default; the codec examples
below require opting into them explicitly (individually, or via a bundle like
codec-full).
[]
= ["ndarray-backend", "onnx-model"]
# Backend selection
= ["burn-tch", "half"] # GPU (LibTorch) backend
= ["burn-ndarray", "half"] # CPU backend
# Inference model formats
= ["tch-model", "onnx-model"] # All inference models
= ["tch", "tokio", "tempfile"] # LibTorch inference
= ["ort", "tokio", "tempfile", "ndarray"] # ONNX inference
# Codec pipeline (opt-in)
= ["lz4_flex", "zstd", "bincode"] # LZ4/Zstd compression
= ["chacha20poly1305", "bincode"] # ChaCha20-Poly1305 AEAD
= ["blake3"] # BLAKE3 checksums
= ["bincode"] # `encode`/`decode`/`to_bytes`/`from_bytes`
= ["half"] # FP16/BF16 quantization
= ["bytes"] # Zerocopy data conversions
# Convenience bundles
= ["compression", "integrity", "zerocopy"]
= ["codec-basic", "encryption"]
= ["codec-secure", "metadata", "quantization"]
To run the codec examples below, add relayrl_types with features = ["codec-full"]
(or the specific features each example needs) in addition to the default backend.
Quick Start
Basic Usage
use RelayRLAction;
use RelayRLTrajectory;
use ;
use ConversionBurnTensor;
use Uuid;
use Arc;
use Tensor;
use NdArray; // enable feature: ndarray-backend
// Create a Burn tensor (NdArray backend) and store as RelayRL TensorData
let device = Cpu;
// 1) Burn → RelayRL: Convert any Burn tensor into TensorData with a target dtype/backend.
// `ConversionBurnTensor` wraps the tensor in an `Arc` (it may be shared across conversions).
let obs_burn = from_floats;
let obs_td: TensorData = ConversionBurnTensor .try_into?;
let act_burn = from_floats;
let act_td: TensorData = ConversionBurnTensor .try_into?;
// 2) RelayRL → Burn: Build Burn tensors from stored TensorData with a chosen backend/device
// Specify the backend type parameter; device is provided via DeviceType
let obs_tensor_any = ?; // Box<dyn Any>
let act_tensor_any = ?;
// 3) Create an action with tensors
let action = new;
// 4) Work with a trajectory
let mut trajectory = with_agent_id;
trajectory.add_action;
println!;
println!;
// Minimal action without tensors
trajectory.add_action;
Codec Functionality
1. Simple Serialization
use RelayRLAction;
let action = minimal;
// Simple serialization (requires the "metadata" feature).
// `from_bytes` returns `(Self, usize)`: the decoded value and the number of bytes consumed.
let bytes = action.to_bytes?;
let = from_bytes?;
assert_eq!;
2. Compression
use RelayRLTrajectory;
use CodecConfig;
use CompressionScheme;
let trajectory = new;
// ... add actions ...
// Configure codec with LZ4 compression (fast). Requires "compression", "integrity",
// and "metadata" features (e.g. via the "codec-full" bundle).
let config = CodecConfig ;
// Encode with compression
let encoded = trajectory.encode?;
println!;
// Decode. `RelayRLTrajectory::decode` returns `(Self, usize)`.
let = decode?;
3. Compression + Encryption
use ;
use CompressionScheme;
use generate_key;
let action = minimal;
// Generate encryption key (requires the "encryption" feature)
let key = generate_key;
// Configure codec with compression AND encryption.
// Requires "compression", "encryption", "integrity", and "metadata" features.
let config = CodecConfig ;
// Encode (compressed + encrypted)
let encoded = action.encode?;
// Decode (must use same key!). `RelayRLAction::decode` returns `Self` directly.
let decoded = decode?;
assert_eq!;
4. Full Pipeline with Integrity Verification
use ;
use RelayRLTrajectory;
use CompressionScheme;
use generate_key;
let mut trajectory = new;
for i in 0..50
// Full codec configuration. Requires "codec-full" (compression + encryption +
// integrity + metadata + quantization).
let key = generate_key;
let config = CodecConfig ;
// Encode: Serialize → Compress → Encrypt → Checksum
let encoded = trajectory.encode?;
// Integrity is automatically verified during decode.
// `RelayRLTrajectory::decode` returns `(Self, usize)`.
let = decode?;
println!;
println!;
5. Chunking for Large Data
use CodecConfig;
use RelayRLTrajectory;
let mut trajectory = new;
// ... add many actions ...
// `encode_chunked`/`decode_chunked` require the "metadata" and "integrity" features.
let config = default;
let chunk_size = 1024 * 1024; // 1MB chunks
// Encode and split into chunks for network transmission
let chunks = trajectory.encode_chunked?;
println!;
// ... transmit chunks over network ...
// Reassemble on the receiving end
let decoded = decode_chunked?;
6. Metadata Tracking
use RelayRLTrajectory;
use Uuid;
// Create trajectory with full metadata
let trajectory = with_metadata;
// Check age
println!;
// Access metadata
if let Some = trajectory.get_agent_id
Codec Pipeline
The encoding pipeline processes data in this order:
┌─────────────────┐
│ RelayRLAction │
│ RelayRLTraject. │
└────────┬────────┘
│
▼
┌──────────┐
│ Bincode │ Serialize to bytes
└────┬─────┘
│
▼
┌──────────┐
│ Compress │ LZ4 or Zstd (optional)
└────┬─────┘
│
▼
┌──────────┐
│ Encrypt │ ChaCha20-Poly1305 (optional)
└────┬─────┘
│
▼
┌──────────┐
│ Checksum │ BLAKE3 integrity (optional)
└────┬─────┘
│
▼
┌──────────┐
│ Output │ Final encoded bytes
└──────────┘
Decoding reverses this pipeline with automatic verification.
ONNX Model Ingestion
ModelModule::load_from_path / ModelModule::from_onnx_bytes accept any ONNX graph that
exposes exactly one tensor input and one tensor output — the graph is not required to name
its input "input" or its output "output". At load time, relayrl_types:
- Commits the graph with ONNX Runtime and introspects the real input/output names,
element types, and shapes directly from the loaded session (
Outlets), instead of assuming fixed names. - Validates the caller-supplied
ModelMetadataagainst that discovered signature:input_dtype/output_dtypemust map to the graph's actual ONNX element type exactly.input_shape/output_shapemust have the same rank as the graph's declared shape.- Every fixed graph dimension (i.e. not a dynamic/symbolic axis) must equal the corresponding metadata dimension; dynamic axes (e.g. a symbolic batch dimension) accept any concrete size at runtime.
- At inference time, binds the input tensor and reads the output tensor by their discovered names, and returns the model's actual ONNX Runtime output shape (important for graphs with a dynamic batch dimension), rather than a shape reconstructed from metadata.
Graphs with more than one input/output, or with non-tensor I/O (sequences, maps, optionals),
are rejected with a specific ModelError at construction time rather than failing later inside
Session::run.
metadata.json itself is unchanged and remains required — RelayRL still needs it for
shapes/dtypes/device defaults and as the cross-process wire contract used by the transport
layer (coordinator bundles, NATS ModelFilesBundle, and on-disk directories); it is now
validated against the graph instead of being trusted blindly. See
crates/relayrl_types/tests/onnx_ingestion.rs for worked examples,
including non-standard I/O names, dynamic batch dimensions, bool tensors, and each rejection
case.
Performance Tips
- LZ4: Best for real-time inference (3-4 GB/s decompression)
- Zstd: Best compression ratio for training data (5-10x reduction)
- Chunking: Use for trajectories > 10MB for network transmission
- Integrity: Minimal overhead (~50ns per MB with BLAKE3)
- Encryption: ~1 GB/s with ChaCha20-Poly1305
Examples
See the tests/ directory for more examples:
- Basic action/trajectory usage
- Compression benchmarks
- Encryption examples
- Chunked network transmission
License
Apache-2.0