Sign in

Collectors

Rollout collectors and vectorized environments

Runs a policy in several copies of an environment at once and returns fixed-length rollouts or whole episodes, ready for a learner.

Overview

Learning needs data, and data comes from a loop: observe, act, receive a reward, observe again. A collector owns that loop so the learning code does not have to. Stepping several copies of the environment side by side gives a batch of transitions per step, and the copies are in different situations, which makes each batch more varied. When one copy finishes an episode it is reset on the spot, so the others never wait. The collector also keeps score: the return and length of every episode that ended along the way.

A short history

This is an engineering practice with no single inventor. Running many actors at once became common after A3C in 2016, which used parallel workers to decorrelate experience. OpenAI's Baselines library in 2017 popularised the vectorized environment, an interface that steps several copies of an environment as one batch, and later libraries such as Gym and Gymnasium made it standard. Since then, physics simulators that run thousands of copies on a GPU have pushed the same idea much further.

How it works

  1. VectorEnv builds n_envs copies from a list of factory functions and seeds copy ii with seed + i.
  2. VectorEnv.step gives each copy its own action. A copy whose episode ended is reset at once, and the last observation of the ended episode is kept in that copy's info under the key final_obs.
  3. RolloutCollector.collect calls the policy on the batch of observations, steps the copies, and repeats for n_steps.
  4. For every step it records obs, actions, rewards, dones, truncated and the true next_obs, each with leading shape (n_steps, n_envs).
  5. It keeps a running return, discounted return and length per copy, and reports them for each episode that finished during the call.
  6. The next collect call carries on from where this one stopped, so episodes longer than n_steps span several calls.
  7. collect_episodes is the simpler tool: it runs whole episodes in one environment and returns one trajectory per episode.

Watch out for

  • After an episode ends, the observation in obs belongs to the next episode. Bootstrapping from it mixes two episodes, so use next_obs, which holds the true final observation.
  • dones is true for both a real ending and a time-limit cut. Only a real ending means the future value is zero, so read truncated to tell them apart.
  • This vector environment is synchronous: copies are stepped one after another in one process. It makes batches more varied but it does not make a slow environment faster.
  • Episode statistics cover only episodes that finished during the call. Early in training, with long episodes, the list can be empty and a mean over it is undefined.
  • Copies of a deterministic environment under a deterministic policy produce identical data, so more copies add nothing unless the policy or the starts differ.

Use cases

When to use it

Use RolloutCollector as the data-gathering half of an on-policy agent such as A2C or PPO, which needs a fresh batch of n_envs times n_steps transitions per update. Use collect_episodes for evaluation or Monte Carlo methods.

In industry

Robotics
Thousands of simulated robots step together on a GPU so that a walking policy can gather years of experience in hours.
Games
Large self-play systems run many game instances in parallel and send their rollouts to a central learner.
Research and teaching
A handful of copies of a small environment give A2C or PPO a batch of decorrelated experience on a laptop.

Choosing it: what must hold

  • An environment that is cheap to copy and safe to run several times at once.
  • A policy that can act on a batch of observations in one forward pass.
  • Correct handling of episode ends, including automatic resets and the difference between a true ending and a time limit.

When to choose something else

IfUse instead
There is one physical system and no simulatorA single-environment loop with a replay buffer, as in SAC or DQN
Workers should update the model themselves without waitingA3C
Real steps are scarce and a model can generate extra dataDyna or MBPO

Math foundations

  1. Batch size of one collection

    B=nenvs×nstepsB = n_{\text{envs}} \times n_{\text{steps}}

    Each collect call returns this many transitions. More copies give a wider, more varied batch. More steps give longer stretches of one trajectory, which advantage estimates need.

  2. Return of an episode

    G=∑t=0T−1γt rtG = \sum_{t=0}^{T-1} \gamma^{t} \, r_t

    The collector reports this discounted sum for every finished episode, and the plain sum (the same with γ=1\gamma = 1) alongside it. The plain sum is what you usually plot. The discounted one is what the agent optimizes.

  3. Bootstrap target at an episode boundary

    yt=rt+γ (1−terminatedt) V(st′)y_t = r_t + \gamma \, \big(1 - \text{terminated}_t\big) \, V(s'_t)

    This is why the collector stores next_obs and truncated separately. After a real ending the future is worth zero. After a time-limit cut the future still has value, estimated from the true next observation st′s'_t.

Symbols

nenvsn_{\text{envs}}
number of environment copies stepped together
nstepsn_{\text{steps}}
steps taken in every copy by one collect call
BB
transitions returned by one collect call
rtr_t
reward at step t of an episode
TT
length of the episode in steps
γ\gamma
discount factor
GG
return of one episode
st′s'_t
the true next observation after step t
V(s)V(s)
a learner's value estimate for observation s
terminatedt\text{terminated}_t
1 if the environment reached a real ending at step t

Worked by hand

Four copies of the built-in ChainEnv with 6 states, a policy that always moves right, and one collect call of 16 steps. The goal is 5 moves from the start and pays reward 1. Use γ=0.99\gamma = 0.99.

B=4×16=64 transitionsB = 4 \times 16 = 64 \text{ transitions}
episodes per copy=⌊16/5⌋=3,4×3=12 episodes\text{episodes per copy} = \lfloor 16 / 5 \rfloor = 3, \qquad 4 \times 3 = 12 \text{ episodes}
Gγ=1=0+0+0+0+1=1G_{\gamma = 1} = 0 + 0 + 0 + 0 + 1 = 1
Gγ=0.99=0.994×1=0.9606G_{\gamma = 0.99} = 0.99^{4} \times 1 = 0.9606

The call returns 64 transitions and reports 12 finished episodes, each of length 5 with return 1 and discounted return 0.9606. Each copy is one step into its fourth episode when the call ends.

Visual example

Loading the example.

Try this

  • Keep the defaults and check the worked example: 64 transitions, 12 episodes, discounted return 0.9606.
  • Press Collect again and see each copy carry on from where the last call stopped.
  • Lower the chance of moving right to 0.6 and the time limit to 8, then click a cell with an orange outline to read its target.

Code sample

import numpy as np
from impl import ChainEnv, RolloutCollector, VectorEnv
from config import CollectorsConfig

cfg = CollectorsConfig(n_envs=4, n_steps=16)
envs = VectorEnv([lambda: ChainEnv(cfg) for _ in range(cfg.n_envs)], seed=cfg.seed)
collector = RolloutCollector(envs, cfg)
policy = lambda obs: np.ones(len(obs), dtype=int)      # obs (n_envs, obs_dim) -> actions (n_envs,), always "right"
batch = collector.collect(policy)
print(batch["rewards"].shape, batch["episode_returns"])  # (16, 4) and the returns of finished episodes
Read the implementation (172 lines)
"""Rollout collectors: a synchronous vector environment, a fixed-length rollout collector and an episode collector.

NumPy only. `ChainEnv` is a small built-in environment so the folder runs on its own; any environment with the
same `reset` / `step` methods can be used instead.
"""
from __future__ import annotations

from typing import Callable

import numpy as np

try:
    from .config import CollectorsConfig
except ImportError:  # run from the template's own folder
    from config import CollectorsConfig


class ChainEnv:
    """Walk on a chain of `chain_length` states. Action 0 moves left, action 1 moves right.

    The episode starts in state 0 and terminates with reward 1 on reaching the last state. Every other step gives
    reward 0. After `max_episode_steps` steps the episode is truncated. The observation is a one-hot vector of
    the state, shape (chain_length,).
    """

    n_actions = 2

    def __init__(self, config: CollectorsConfig | None = None) -> None:
        self.config = config or CollectorsConfig()
        self.obs_dim = self.config.chain_length
        self.state = 0
        self.steps = 0
        self.rng = np.random.default_rng(self.config.seed)

    def _obs(self) -> np.ndarray:
        obs = np.zeros(self.obs_dim)
        obs[self.state] = 1.0
        return obs

    def reset(self, seed: int | None = None) -> np.ndarray:
        """Start a new episode and return the first observation. `seed` reseeds the environment when given."""
        if seed is not None:
            self.rng = np.random.default_rng(seed)
        self.state = 0
        self.steps = 0
        return self._obs()

    def step(self, action: int):
        """Apply one action. Returns (obs, reward, terminated, truncated, info)."""
        self.state = max(0, self.state - 1) if int(action) == 0 else self.state + 1
        self.steps += 1
        terminated = self.state == self.config.chain_length - 1
        truncated = (not terminated) and self.steps >= self.config.max_episode_steps
        return self._obs(), float(terminated), terminated, truncated, {}


class VectorEnv:
    """Several environment copies stepped together, each reset automatically when its episode ends."""

    def __init__(self, env_fns: list[Callable[[], object]], seed: int = 0) -> None:
        """env_fns: one zero-argument function per copy that builds an environment. Copy i is seeded seed + i."""
        if not env_fns:
            raise ValueError("env_fns must hold at least one environment factory")
        self.envs = [fn() for fn in env_fns]
        self.n_envs = len(self.envs)
        self.seed = seed

    def reset(self) -> np.ndarray:
        """Reset every copy. Returns observations of shape (n_envs, obs_dim)."""
        return np.stack([env.reset(seed=self.seed + i) for i, env in enumerate(self.envs)])

    def step(self, actions):
        """Step every copy with its own action.

        actions: shape (n_envs,) or (n_envs, action_dim).
        Returns (obs, rewards, terminated, truncated, infos). obs has shape (n_envs, obs_dim); where an episode
        ended, obs holds the first observation of the next episode and infos[i]["final_obs"] the last one of the
        ended episode.
        """
        obs, rewards, terms, truncs, infos = [], [], [], [], []
        for env, action in zip(self.envs, actions):
            o, r, term, trunc, info = env.step(action)
            info = dict(info)
            if term or trunc:
                info["final_obs"] = o
                o = env.reset()
            obs.append(o)
            rewards.append(r)
            terms.append(term)
            truncs.append(trunc)
            infos.append(info)
        return np.stack(obs), np.array(rewards, dtype=float), np.array(terms), np.array(truncs), infos


class RolloutCollector:
    """Runs a policy in a `VectorEnv` and returns fixed-length rollouts, keeping its place between calls."""

    def __init__(self, envs: VectorEnv, config: CollectorsConfig | None = None) -> None:
        self.envs = envs
        self.config = config or CollectorsConfig()
        self.obs = envs.reset()
        self._returns = np.zeros(envs.n_envs)  # running undiscounted return of each copy's current episode
        self._discounted = np.zeros(envs.n_envs)
        self._lengths = np.zeros(envs.n_envs, dtype=int)
        self.total_steps = 0

    def collect(self, policy: Callable[[np.ndarray], np.ndarray], n_steps: int | None = None) -> dict:
        """Run `policy` for `n_steps` steps in every copy.

        policy: maps observations (n_envs, obs_dim) to actions (n_envs,) or (n_envs, action_dim).
        Returns a dict with time-major arrays of leading shape (n_steps, n_envs): obs, actions, rewards, dones
        (terminated or truncated), truncated, next_obs (the true next observation, also at episode ends); plus
        last_obs (n_envs, obs_dim), and episode_returns, episode_discounted_returns, episode_lengths: one entry
        per episode that finished during this call.
        """
        t_max = n_steps or self.config.n_steps
        keys = ("obs", "actions", "rewards", "dones", "truncated", "next_obs")
        data: dict = {k: [] for k in keys}
        ep_returns, ep_discounted, ep_lengths = [], [], []
        for _ in range(t_max):
            actions = np.asarray(policy(self.obs))
            next_obs, rewards, terms, truncs, infos = self.envs.step(actions)
            dones = terms | truncs
            true_next = next_obs.copy()
            for i in np.flatnonzero(dones):
                true_next[i] = infos[i]["final_obs"]
            self._discounted += self.config.gamma**self._lengths * rewards
            self._returns += rewards
            self._lengths += 1
            for i in np.flatnonzero(dones):
                ep_returns.append(self._returns[i])
                ep_discounted.append(self._discounted[i])
                ep_lengths.append(self._lengths[i])
                self._returns[i] = self._discounted[i] = 0.0
                self._lengths[i] = 0
            for k, v in zip(keys, (self.obs, actions, rewards, dones, truncs, true_next)):
                data[k].append(v)
            self.obs = next_obs
            self.total_steps += self.envs.n_envs
        out = {k: np.stack(v) for k, v in data.items()}
        out["last_obs"] = self.obs.copy()
        out["episode_returns"] = np.array(ep_returns, dtype=float)
        out["episode_discounted_returns"] = np.array(ep_discounted, dtype=float)
        out["episode_lengths"] = np.array(ep_lengths, dtype=int)
        return out


def collect_episodes(env, policy: Callable[[np.ndarray], object], n_episodes: int, seed: int | None = None) -> list[dict]:
    """Run `n_episodes` whole episodes in one environment.

    policy: maps a single observation (obs_dim,) to one action. seed: seeds the first reset when given.
    Returns one dict per episode with obs (T, obs_dim), actions (T, ...), rewards (T,), the undiscounted `return`
    and `terminated` (False when the episode was cut by the step limit).
    """
    episodes = []
    for ep in range(n_episodes):
        obs = env.reset(seed=seed if ep == 0 else None)
        traj: dict = {"obs": [], "actions": [], "rewards": []}
        while True:
            action = policy(obs)
            next_obs, reward, terminated, truncated, _ = env.step(action)
            traj["obs"].append(obs)
            traj["actions"].append(action)
            traj["rewards"].append(reward)
            obs = next_obs
            if terminated or truncated:
                break
        out = {k: np.array(v) for k, v in traj.items()}
        out["return"] = float(out["rewards"].sum())
        out["terminated"] = bool(terminated)
        episodes.append(out)
    return episodes
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
9, run with python3 -m unittest -v

Practice

Build VectorEnv([lambda: ChainEnv(cfg) for _ in range(cfg.n_envs)], seed=cfg.seed) and a RolloutCollector with CollectorsConfig(n_envs=4, n_steps=16). Collect once with a policy that always moves right and check the numbers in the worked example. Then collect with a uniformly random policy and compare episode_lengths, and find a row where obs at the next step differs from next_obs.

Check on learning

  1. You have a fixed budget of 1024 transitions per update. How would learning differ between 64 copies for 16 steps and 4 copies for 256 steps?
    A way to think about it

    Consider how many different situations are in the batch, how long a stretch of consecutive rewards each advantage estimate can use, and how old the policy is when the last step is taken.

  2. An agent trained on a task with a 50-step limit learns to waste time near the end of episodes. Which field of the collector's output would you check first, and why?
    A way to think about it

    Think about what the learner believes the value of a state is just before the cut, if every cut is treated as a real ending.

  3. With a random policy on a long chain, almost no episode reaches the goal within the step limit. What do the reported episode returns tell you, and what do they hide?
    A way to think about it

    Returns are all zero whether the agent got one step from the goal or never left the start. Ask what other quantity you could log to see progress.

  4. Why does the collector reset a finished copy immediately instead of waiting until all copies have finished their episodes?
    A way to think about it

    Picture one copy with a very long episode and three with short ones. Count how many steps would be wasted, and which kind of episode would then be over-represented in the data.