Skip to main content

RolloutBuffer

Struct RolloutBuffer 

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

Rollout buffer for storing trajectories

Stores trajectories collected from environment interactions and computes advantages using Generalized Advantage Estimation (GAE).

§Buffer Layout

The buffer uses a [num_steps, num_envs] layout where:

  • num_steps: Number of timesteps per rollout (typically 128-2048)
  • num_envs: Number of parallel environments

This layout provides good cache locality for forward passes and efficient computation of advantages.

Implementations§

Source§

impl RolloutBuffer

Source

pub fn new(num_steps: usize, num_envs: usize, obs_dim: usize) -> Self

Create a new rollout buffer

§Arguments
  • num_steps - Number of timesteps per rollout
  • num_envs - Number of parallel environments
  • obs_dim - Dimensionality of observations
Source

pub fn add( &mut self, step: usize, env_id: usize, observation: &[f32], action: i64, reward: f32, value: f32, log_prob: f32, terminated: bool, truncated: bool, )

Add a transition to the buffer

§Arguments
  • step - Timestep within the rollout (0 to num_steps-1)
  • env_id - Environment ID (0 to num_envs-1)
  • observation - Current observation
  • action - Action taken
  • reward - Reward received
  • value - Value estimate for current state
  • log_prob - Log probability of the action
  • terminated - Whether the episode terminated
  • truncated - Whether the episode was truncated
Source

pub fn reset(&mut self)

Reset the buffer for a new rollout

Source

pub fn shape(&self) -> (usize, usize, usize)

Get buffer shape (num_steps, num_envs, obs_dim)

Source

pub fn len(&self) -> usize

Get total number of transitions in buffer

Source

pub fn is_empty(&self) -> bool

Check if buffer is empty

Source

pub fn obs_shape(&self) -> (usize, usize)

Get observations tensor shape for neural network input

Source

pub fn observations(&self) -> &[Vec<Vec<f32>>]

Borrow the per-step observations, indexed [step][env] and then by observation dimension (final inner Vec<f32> is one observation vector of length obs_dim).

Source

pub fn actions(&self) -> &[Vec<i64>]

Borrow the per-step discrete actions, indexed [step][env].

Source

pub fn rewards(&self) -> &[Vec<f32>]

Borrow the per-step rewards (raw, un-discounted), indexed [step][env].

Source

pub fn values(&self) -> &[Vec<f32>]

Borrow the per-step bootstrap value estimates V(s_t) produced by the policy at collection time, indexed [step][env]. Used by compute_advantages as the value baseline.

Source

pub fn log_probs(&self) -> &[Vec<f32>]

Borrow the per-step action log-probabilities under the behavior policy at collection time, indexed [step][env]. PPO uses these as the denominator of the importance-sampling ratio.

Source

pub fn terminated(&self) -> &[Vec<bool>]

Borrow the per-step terminal-state flags (true on episode end), indexed [step][env]. GAE zeroes the bootstrap across terminal transitions but keeps the realized reward.

Source

pub fn truncated(&self) -> &[Vec<bool>]

Borrow the per-step truncation flags (true on time-limit / external reset that is not a terminal state), indexed [step][env]. GAE retains the bootstrap value across truncated transitions because the trajectory is still “alive” in the value-function sense.

Source

pub fn advantages(&self) -> &[Vec<f32>]

Borrow the per-step GAE advantages computed by compute_advantages, indexed [step][env]. Zero-initialized until GAE has run.

Source

pub fn returns(&self) -> &[Vec<f32>]

Borrow the per-step value-function targets (advantages + values), indexed [step][env]. Zero-initialized until GAE has run.

Source

pub fn advantages_mut(&mut self) -> &mut [Vec<f32>]

Mutable view of the advantages buffer, indexed [step][env]. Used when in-place normalizing advantages or applying a custom advantage estimator that does not touch returns; use Self::advantages_and_returns_mut when both must be borrowed at the same time (e.g. inside compute_advantages).

Source

pub fn returns_mut(&mut self) -> &mut [Vec<f32>]

Mutable view of the returns / value-target buffer, indexed [step][env]. Use Self::advantages_and_returns_mut instead when both must be borrowed at the same time.

Source

pub fn advantages_and_returns_mut( &mut self, ) -> (&mut [Vec<f32>], &mut [Vec<f32>])

Get mutable references to both advantages and returns This is needed to avoid double mutable borrow in GAE computation

Source§

impl RolloutBuffer

Source

pub fn compute_advantages( &mut self, last_values: &[f32], gamma: f32, gae_lambda: f32, )

Compute advantages using Generalized Advantage Estimation

This is a convenience method that calls the module-level function. Iterates the full [num_steps, num_envs] capacity; use Self::compute_advantages_partial when the buffer is only partially filled.

§Arguments
  • last_values - Value estimates for the final states [num_envs]
  • gamma - Discount factor
  • gae_lambda - GAE lambda parameter
Source

pub fn compute_advantages_partial( &mut self, valid_steps: usize, last_values: &[f32], gamma: f32, gae_lambda: f32, )

Compute advantages over the first valid_steps rows only.

Convenience wrapper around the module-level compute_advantages_partial. Use this when the rollout buffer has been partially filled (valid_steps < num_steps) to prevent zero-padded tail rows from contaminating GAE on the real prefix.

§Arguments
  • valid_steps - Number of filled rows at the start of the buffer
  • last_values - Bootstrap V(s_{T+1}) for the state after row valid_steps - 1, per environment [num_envs]
  • gamma - Discount factor
  • gae_lambda - GAE lambda parameter
Source

pub fn compute_vtrace_advantages( &mut self, target_log_probs: &[Vec<f32>], last_values: &[f32], gamma: f32, rho_bar: f32, c_bar: f32, )

Compute V-trace targets and advantages (Espeholt et al. 2018) for off-policy correction.

Convenience wrapper around the module-level compute_vtrace_advantages. The buffer’s stored log_probs are treated as the behavior-policy log-probs; target_log_probs ([num_steps][num_envs]) are the current target policy’s log-probs reevaluated over the stored observations/actions. Results are written into advantages/returns exactly like Self::compute_advantages, so get_batch() works as usual.

§Arguments
  • target_log_probs - Target-policy log-probs [num_steps][num_envs]
  • last_values - Bootstrap V(s_{T+1}) per environment [num_envs]
  • gamma - Discount factor
  • rho_bar - IS ratio clip for the TD target (typically 1.0)
  • c_bar - IS ratio clip for the trace coefficient (typically 1.0)
Source

pub fn get_batch(&self) -> RolloutBatch

Get a batch of all data from the buffer

This is a convenience method that calls the module-level function. Returns the full [num_steps, num_envs] capacity, including any zero-padded unwritten tail; use Self::get_filled_batch when the buffer is only partially filled.

Source

pub fn get_filled_batch(&self, valid_steps: usize) -> RolloutBatch

Get a batch covering only the first valid_steps rows.

Use this when the buffer was filled with fewer than num_steps transitions (e.g. an early-terminating rollout). It prevents the zero-initialized tail of the buffer from being handed to PPO as fake training data.

§Panics

Panics if valid_steps > self.shape().0.

Trait Implementations§

Source§

impl Clone for RolloutBuffer

Source§

fn clone(&self) -> RolloutBuffer

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 RolloutBuffer

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