Skip to main content

PrioritizedReplayBuffer

Struct PrioritizedReplayBuffer 

Source
pub struct PrioritizedReplayBuffer { /* private fields */ }
Expand description

Fixed-capacity prioritized replay buffer.

Stores (obs, action, reward, next_obs, done) transitions in a ring buffer (same FIFO eviction as super::ReplayBuffer), plus a per-transition priority in a SumTree for O(log N) proportional sampling.

New transitions are pushed with the maximum existing priority (or 1.0 for an empty buffer), guaranteeing each fresh transition is sampled at least once before its priority can be updated by a TD error.

Implementations§

Source§

impl PrioritizedReplayBuffer

Source

pub fn new(capacity: usize, obs_dim: usize, alpha: f32, epsilon: f32) -> Self

Create a new prioritized replay buffer.

§Arguments
  • capacity - Maximum number of transitions stored. Must be > 0.
  • obs_dim - Length of one observation vector. Must be > 0.
  • alpha - Priority exponent α ∈ [0, 1]. 0 recovers uniform sampling; 1 is fully proportional. Typical value 0.6.
  • epsilon - Tiny constant added to |TD error| before raising to α, so transitions with zero TD error still have a tiny chance of being resampled. Typical value 1e-6.
§Panics

Panics if capacity == 0, obs_dim == 0, alpha is outside [0, 1], or epsilon < 0.

Source

pub fn push( &mut self, obs: &[f32], action: i64, reward: f32, next_obs: &[f32], done: bool, )

Push a single transition into the buffer with the current maximum priority (or 1.0 if the buffer is empty).

When the buffer is at capacity, this overwrites the oldest transition (FIFO eviction); the corresponding leaf in the sum-tree is overwritten with the new priority.

Source

pub fn len(&self) -> usize

Number of transitions currently in the buffer.

Source

pub fn is_empty(&self) -> bool

true if the buffer holds no transitions.

Source

pub fn capacity(&self) -> usize

Maximum number of transitions the buffer can hold.

Source

pub fn obs_dim(&self) -> usize

Observation dimension (length of one obs slice).

Source

pub fn alpha(&self) -> f32

Priority exponent α.

Source

pub fn epsilon(&self) -> f32

Priority floor ε.

Source

pub fn max_priority(&self) -> f32

Maximum leaf priority currently in the tree.

Useful for diagnostics; the buffer also tracks this internally so push can hand fresh transitions a max-priority slot.

Source

pub fn is_ready(&self, min_size: usize) -> bool

true if the buffer holds at least min_size transitions.

Source

pub fn sample<R: Rng>( &self, batch_size: usize, beta: f32, rng: &mut R, ) -> PrioritizedBatch

Sample a minibatch using stratified proportional sampling.

Divides [0, total_priority] into batch_size equal segments and draws one uniform p from each, then walks the sum-tree to find the leaf whose cumulative-priority interval contains p. Stratification reduces variance vs. drawing batch_size independent uniforms from [0, total] (Schaul §3.3).

Importance-sampling weights are computed as wᵢ = (1 / (N · P(i)))^β and then normalized by max(wⱼ) so the largest weight is exactly 1.0.

§Arguments
  • batch_size - Number of transitions to draw. Must be > 0.
  • beta - IS-weight exponent. Caller anneals from a small value (e.g. 0.4) to 1.0 over training.
  • rng - source of randomness.
§Panics

Panics if self.is_empty(), batch_size == 0, or the tree’s total priority is zero (all leaves were explicitly set to zero — shouldn’t happen in normal use because push always uses max_priority ≥ ε^α > 0).

Source

pub fn update_priorities(&mut self, indices: &[usize], td_errors: &[f32])

Update the priorities of a set of leaf indices with new TD errors.

For each (idx, td_err) pair, the stored priority becomes (|td_err| + ε)^α. The max_priority tracker is bumped so future Self::push calls inherit at least this value.

§Panics

Panics if indices and td_errors have different lengths or if any index is out of range.

Source

pub fn tree(&self) -> &SumTree

Borrow the underlying sum-tree (useful for tests / diagnostics).

Trait Implementations§

Source§

impl Clone for PrioritizedReplayBuffer

Source§

fn clone(&self) -> PrioritizedReplayBuffer

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for PrioritizedReplayBuffer

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more