Foundations to Frontier
Tests

Gymnasium

Gymnasium, the maintained successor of OpenAI Gym, defines the standard interface between reinforcement learning agents and environments: reset, step, observation and action spaces, wrappers and vector environments. This page rebuilds that interface from scratch, then measures the most consequential detail of the modern API: the split of 'done' into terminated and truncated. Treating a time limit as the end of the task, or bootstrapping from the observation that starts the next episode, biases value estimates, and the shorter the time limit, the larger the error.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

A common plug for every game

Imagine every video game had its own controller with a different shape. A player trained on one could not even hold another. Gymnasium is the common plug of reinforcement learning: every environment, from a balancing pole to a robot simulator to an Atari game, offers the same two buttons, reset and step, and describes what it shows and what it accepts in the same way. Any learning algorithm written for that plug works with any environment that offers it.

RL libraries lab
012345678grey: true value; blue: TD estimate; states 0–8 (start 5, goal 9)
Eight copies of a 10-state random walk run in a vector environment with a time limit of 5 steps, and TD(0) estimates each state's value (γ = 0.95) over 15,000 steps. Handling: truncation as termination. Mean error over states 3–8: 1.916; start state estimate 2.506 against the true 4.592. A time limit is not part of the task, so the value after truncation must come from the state actually reached: stopping there makes values too small, and bootstrapping from the next episode's start makes them wrong in the other direction. The shorter the limit, the larger the damage.
Why engineers care

Gymnasium is maintained by the Farama Foundation and is used by Stable-Baselines3, CleanRL, RLlib, TorchRL and most research code; MuJoCo, Atari and many robotics simulators ship Gymnasium interfaces.

📝 Quick check (Level 0)
0/3 answered
  1. 1. Gymnasium's two main methods are…
  2. 2. Gymnasium is the successor of…
  3. 3. A shared interface lets…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

By hand

  • reset(seed=…) → (observation, info): start a new episode; a seed makes it reproducible.
  • step(action) → (observation, reward, terminated, truncated, info): advance one step.
  • terminated: the environment reached a terminal state of the MDP, such as the goal or a crash; nothing follows, so its value is zero.
  • truncated: the episode was cut for a reason outside the MDP, usually a time limit; the state still has a future.
  • Spaces: Discrete(n) and Box(low, high, shape) describe valid observations and actions, with sample() and contains().
  • Wrappers: classes that wrap an environment to change it without editing it: TimeLimit, RecordEpisodeStatistics, NormalizeObservation, RescaleAction, TimeAwareObservation.
  • Vector environments: SyncVectorEnv and AsyncVectorEnv step k copies together and reset each automatically when its episode ends; in versions 0.26–0.29 the last observation of a finished episode is in info[“final_observation”] (version 1.0 changed the autoreset scheme, so check the documentation of the version you use).
📝 Quick check (Level 1)
0/3 answered
  1. 1. A time limit should set…
  2. 2. Reaching the goal sets…
  3. 3. TimeLimit and RecordEpisodeStatistics are…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

The Gymnasium interface from scratch

Exercise 1.

  • Spaces Discrete and Box; an Env base class with seeded reset; a 10-state chain environment (start 5, right with probability 0.7, reward s/10 per step and 1 for reaching the goal 9, which terminates).
  • Wrappers TimeLimit (reports truncation separately) and RecordEpisodeStatistics (adds the episode’s return and length to info).
  • SyncVectorEnv with automatic reset in the Gymnasium 0.29 style: the returned observation after an episode end is the next episode’s start, and the last observation is in info[“final_observation”].
  • Checks: seeding reproduces trajectories, both kinds of episode end occur, and the vector environment exposes the final observation.

Practice.

  • Always pass a seed to reset at the start of an experiment, and log the library version.
  • Bootstrap through truncation: your value target should be r + γV(s′) unless terminated, with s′ the real final observation.
  • Use wrappers rather than editing environments: time limits, normalisation, action rescaling, frame stacking and recording.
  • Vectorise with SyncVectorEnv for cheap environments and AsyncVectorEnv (subprocesses) for expensive ones.
  • Check new environments with gymnasium.utils.env_checker.check_env before training.
class TimeLimit(Wrapper):
    def __init__(self, env, max_steps):
        super().__init__(env); self.max_steps = max_steps
    def reset(self, seed=None, options=None):
        self.t = 0; return self.env.reset(seed=seed, options=options)
    def step(self, action):
        obs, r, term, trunc, info = self.env.step(action); self.t += 1
        return obs, r, term, trunc or self.t >= self.max_steps, info

# value target in an agent, with a vector environment:
nxt = info["final_observation"]          # not the returned obs
target = r + gamma * V[nxt] * (1 - terminated)   # truncation still bootstraps
🐍 Exercise 1: spaces, wrappers and a vector environment
Implement Gymnasium's spaces, a seeded environment, the TimeLimit and RecordEpisodeStatistics wrappers and an auto-resetting vector environment, and check their behaviour.
📝 Quick check (Level 2)
0/3 answered
  1. 1. Before training on a new environment, run…
  2. 2. For expensive environments use…
  3. 3. The value target bootstraps unless…

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

Why truncation must bootstrap. A time limit is a property of the experiment, not of the task. The value of a state is the expected discounted return from it, which does not depend on how long the episode has run unless time is part of the state. When an episode is cut at a state s′, the correct TD target is r + γV(s′); using r alone, as the old done = True signal led many implementations to do, treats s′ as a dead end and pulls values towards zero. Pardo and colleagues (2018) analysed this and proposed partial-episode bootstrapping, and Gymnasium’s terminated and truncated flags make the distinction explicit.

Why the final observation matters. An auto-resetting vector environment returns the first observation of the next episode in the same call that reports the end of the old one. Bootstrapping from it uses the value of an unrelated state; in the chain, truncations happen near the start, so the bias depends on how values differ between the final state and the start state.

When treating truncation as termination is right. If the remaining time is part of the observation (TimeAwareObservation), the time limit is part of the MDP and its end is a true terminal state. Finite-horizon tasks are naturally modelled this way.

Bias shrinks with longer limits. The fraction of transitions that end by truncation falls as the limit grows, so the bias from either bug falls too; with a limit of 50 steps the episodes in the chain almost always reach the goal first.

📝 Quick check (Level 3)
0/3 answered
  1. 1. Treating truncation as termination pulls values…
  2. 2. Partial-episode bootstrapping was proposed by…
  3. 3. Treating truncation as termination is right when…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

How much do the two common truncation bugs bias TD value estimates, and how does the bias depend on the time limit?

History.

  • G. Brockman and colleagues (2016) released OpenAI Gym; its step returned a single done flag.
  • F. Pardo, A. Tavakoli, V. Levdik and P. Kormushev (2018) showed how time limits corrupt value estimates.
  • The Farama Foundation took over maintenance as Gymnasium (2022); version 0.26 split done into terminated and truncated, and version 1.0 (2024) revised vector-environment autoreset.
  • M. Towers and colleagues (2024) described Gymnasium in a paper.

Exercise 2.

  • TD(0) evaluation of the chain (γ = 0.95) with 8 environments in the vector environment for 15,000 steps, step size 1/n(s)^0.7.
  • Time limits of 5, 15 and 50 steps; three ways of forming the target: correct (bootstrap from the final observation unless terminated), truncation treated as termination, and bootstrapping from the observation the vector environment returned.
  • The true values come from solving the Bellman equations without a time limit (start state: 4.592). Error is the mean absolute error over states 3 to 8.

Mean absolute error (seeds 0, 1, 2):

time limit correct truncation as termination bootstrap from reset observation
5 0.087, 0.074, 0.068 1.930, 1.909, 1.906 1.691, 1.759, 1.741
15 0.016, 0.021, 0.024 0.409, 0.383, 0.401 0.122, 0.156, 0.097
50 0.014, 0.014, 0.026 0.016, 0.014, 0.028 0.014, 0.014, 0.026

Findings.

  • The correct target matched the true values to within 0.09 on every seed and limit.
  • Treating truncation as termination cut the start-state value from 4.592 to 2.49–2.52 with a 5-step limit (error about 1.9), and still to 4.15–4.16 with a 15-step limit.
  • Bootstrapping from the reset observation inflated the start-state value to 6.53–6.55 with a 5-step limit (error 1.69 to 1.76): after a truncation at the start state the target bootstraps from the start state itself, which here is wrong in the other direction.
  • With a 50-step limit truncations were rare and all three agreed to within 0.002.
🐍 Exercise 2 (research): how much do the two common truncation bugs bias TD value estimates, and how does the bias depend on the time limit?
Run TD(0) through an auto-resetting vector environment with time limits of 5, 15 and 50 steps, and compare correct truncation handling with two common bugs.

Gymnasium in practice

  • Libraries built on it: Stable-Baselines3, CleanRL, RLlib, Tianshou and TorchRL accept Gymnasium environments (topic L8-2).
  • Environment collections: Classic Control, Box2D, MuJoCo (topic L8-3), Atari through ALE, and PettingZoo for multi-agent tasks.
  • Fast vectorised environments: EnvPool, Brax, MJX and Isaac Lab provide Gymnasium-like APIs that run thousands of environments in parallel.
  • Reproducibility: pin versions, seed resets, and record episode statistics with the standard wrapper.

References

  1. G. Brockman and colleagues (2016). “OpenAI Gym.” arXiv:1606.01540.
  2. M. Towers and colleagues (2024). “Gymnasium: a standard interface for reinforcement learning environments.” arXiv:2407.17032.
  3. F. Pardo, A. Tavakoli, V. Levdik and P. Kormushev (2018). “Time limits in reinforcement learning.” ICML.
  4. Gymnasium documentation: gymnasium.farama.org.
  5. S. Huang and colleagues (2022). “The 37 implementation details of proximal policy optimization.” ICLR Blog Track.