Module contents
Lesson 13 of 37Core 100 min

Real environments: Gymnasium, MuJoCo and the engineering of the interaction loop

Build reliable reinforcement-learning environment loops with Gymnasium, vector resets, wrappers, probes and MuJoCo.

After this lesson you can

  • Distinguish termination from truncation when constructing targets.
  • Implement environment wrappers and handle vector autoreset modes.
  • Explain MuJoCo state, control and numerical integration.
  • Design custom environments and known-answer probes.
  • Measure vector throughput under comparable conditions.

Before you start

The loop is also part of the agent

A network can calculate the exact formula we give it and learn the wrong target if the next observation belongs to another episode. A time cutoff, automatic reset or reward-changing wrapper are engineering decisions with mathematical consequences.

We follow the documented Gymnasium API and use the version recorded in each experiment. Vector reset names and conventions have changed between versions: record library version, environment identifier and wrappers alongside seeds. The official documentation is the reference for your installation.

An environment contract

The Gymnasium API separates initialization and transition. In an individual environment, reset(seed=semilla) returns (observación, info) and step(acción) returns (observación_siguiente, recompensa, terminated, truncated, info). After termination or truncation, reset before continuing. info may include diagnostics outside the agent’s observation.

Discrete(n) represents a finite set of integers; Box describes shape, type and bounds of a vector or matrix; MultiDiscrete combines discrete components and Dict groups named spaces. Check that observations and actions belong to their declared spaces with consistent types and shapes. Environment and action-space seeds are distinct randomness sources. To reproduce a sequence, typically seed the first reset and then allow the generator to advance; resetting repeatedly with the same seed can repeat the same episode.

InteractiveA transition under the microscope
−2,42,4

step(action) → (obs = [0.000, 0.000, 0.010, 0.000], reward = no step, terminated = false, truncated = false, info = {})

CartPole-v1 equations are reimplemented using explicit Euler, Δt=0.02 and forces ±10, without RNG: reset fixes (0, 0, 0.01, 0). Gymnasium typically uses a random reset in [−0.05,0.05] and float32 observations; this demonstration uses JavaScript arithmetic, so it does not promise bit-for-bit identity. A fall occurs if |x|>2.4 or |θ|>12°, TimeLimit at 500 steps; both flags can be true simultaneously. A reset is required after either.

With γ=0.99 and your chosen estimated V, the target is r+γ(1−terminated)V. The V value is an adjustable assumption, not a measurement. Truncation without termination retains bootstrapping; for genuine termination it is zero. Source: Gymnasium 1.4 CartPole.

Policy
5
Steps
0 / 500
terminated / truncated
false / false
Correct target
no transition
Follow the observations, rewards and flags produced by the loop.

In CartPole-v1 the registered limit is 500 steps; a fall can terminate earlier. Reaching the limit and falling are different causes, although flags can coincide on one transition. The target must prioritize true termination when both flags are true. See the environment specification and the registry of the version you run.

Termination and truncation

In the distinction between termination and truncation, termination belongs to the task defined by the MDP; truncation indicates collection stopped for an external condition such as a step limit. For a one-step target of a continuing task, the bootstrap mask is

yt=rt+1+γ(1−1terminated)V(st+1).y_t=r_{t+1}+\gamma(1-\mathbf 1_{\mathrm{terminated}})V(s_{t+1}).

If truncated but not terminated, st+1s_{t+1} must be the real final observation before reset. Replacing it with zero or the next episode’s first state changes the problem. In a finite horizon that is part of the task, remaining time affects the future: include it in state and treat the horizon’s end as task termination. Pardo and colleagues distinguish the two cases.

InteractiveValue and time limit
0.05.010.0step 1step 8, cutoff

Explicit continuing model: one physical state, reward 1 and no real ending; every H steps a collector resets the counter. The dashed line is 1/(1−γ). H separate estimates are maintained to visualize the effect of the record position, using synchronous TD and α=0.1. Correct truncation retains bootstrapping in the same physical state; the successor is represented by slot 1, which is physically identical.

If the successor value is forced to zero, the limit of these H estimates is (1−γ⁽ᴴ⁻ᵗ⁾)/(1−γ); for the final step it is 1.0. This is not the value of the continuing process. With a single shared parameter there would not be H distinct values: another biased compromise would result. If the horizon were intrinsic to the task, remaining time would have to be part of the state and its end would indeed be terminal. Source: Gymnasium, handling time limits.

Target at truncation
8
0.90
1000
True continuing value
10.00
Learned near cutoff
10.00
Compare the correct target with one zeroing value on a continuing-task cutoff.

With constant reward rr and 0≤γ<10\leq\gamma<1, continuing value is r/(1−γ)r/(1-\gamma). Treating each cutoff as terminal estimates a different quantity, dependent on time remaining until that cutoff. If time is absent from the observation, the same apparent state can mix horizons. This is not exclusive to DQN: PPO and other critic-based methods also need the correct final observation.

In GAE, an implementation processing separate episodes can use δt=rt+1+γ(1−terminatedt)V(st+1)−V(st)\delta_t=r_{t+1}+\gamma(1-\mathrm{terminated}_t)V(s_{t+1})-V(s_t) and stop advantage recursion at any episode boundary, including truncation. At that boundary it retains the final-observation bootstrap when there was no true termination, but does not incorporate advantages from the new episode. The bootstrap mask and mask preventing crossing a reset serve different functions.

Wrappers change what is measured

A wrapper transforms an interface or adds state. Order matters. If RecordEpisodeStatistics must count TimeLimit cutoffs and record original reward, place the limit around the base environment, statistics around the limit and any reward transformation around statistics. The outer wrapper receives the inner result and can modify it afterward. In evaluation, document whether normalization statistics are frozen and from what data they were obtained.

Clipping actions, normalizing observations or rewards, repeating actions and preprocessing images solve different problems. Atari adds choices such as frame skip, grayscale, resizing and frame stacking; order and version form part of the protocol. Transformed reward may serve learning while untransformed return reports the task. Do not assume two scores are comparable without checking what each measures. Individual and vector wrappers have their own interfaces: check compatibility in Gymnasium documentation.

Multiple environments and three reset modes

Vectorized environments group observations, actions and results. SyncVectorEnv advances copies in one process; AsyncVectorEnv uses processes and communication, adding cost and requiring environment factories to run in child processes. More processes do not guarantee higher performance: it depends on simulation, communication and batch-processing costs.

InteractiveWhere the final state goes
Environment 1: initial reset
obs = e0:0; r = 0; terminated = false
Final observation: none
Store: none
Environment 2: initial reset
obs = e0:0; r = 0; terminated = false
Final observation: none
Store: none
Environment 3: initial reset
obs = e0:0; r = 0; terminated = false
Final observation: none
Store: none
Environment 4: initial reset
obs = e0:0; r = 0; terminated = false
Final observation: none
Store: none
Environment 5: initial reset
obs = e0:0; r = 0; terminated = false
Final observation: none
Store: none
Environment 6: initial reset
obs = e0:0; r = 0; terminated = false
Final observation: none
Store: none
Environment 7: initial reset
obs = e0:0; r = 0; terminated = false
Final observation: none
Store: none
Environment 8: initial reset
obs = e0:0; r = 0; terminated = false
Final observation: none
Store: none

Deterministic teaching model: each copy ends after 2 to 6 transitions, with observations in episode:step form and reward 1. In NEXT_STEP the terminating step returns the final observation; the next call resets that environment, ignores its action and returns reward 0 without a transition. In SAME_STEP the final step returns the first new observation and the final one is retrieved with info["final_obs"] and the info["_final_obs"] mask. In DISABLED request reset(options={"reset_mask": mask}) before continuing. The final step's reward and flag still belong to the previous transition.

Here all endings are terminated; truncation would still require its final observation for bootstrapping. Source: Gymnasium, autoreset modes.

Mode
Vector steps
0
Environments awaiting reset
0
Compare autoreset modes and decide which transitions can be stored.

In the currently documented autoreset API, the modes are:

  • NEXT_STEP: the terminating step returns the final observation. The next call resets that copy; its action is ignored and the reset result is not a task transition.
  • SAME_STEP: the terminating step already returns the new episode observation. In the documented API, retrieve the final observation from info["final_obs"] with mask info["_final_obs"]; use that final observation to store the preceding transition.
  • DISABLED: the caller explicitly resets finished copies, for example with a reset mask supported by that version.

Earlier versions may use other names, such as final_observation; do not infer a universal key from one example. In a vector, each copy may finish at a different step: retain a per-copy mask and check the shapes of info. In the current implementation an integer seed on vector reset is expanded per copy; explicitly passing the same seed to all can generate identical trajectories in deterministic environments.

MuJoCo: model, state and physics

MuJoCo simulates mechanical systems defined with MJCF. mjModel contains compiled structure and parameters; mjData contains mutable state and quantities computed during simulation. A step applies controls, computes dynamics and constraints, and integrates state. A Gymnasium environment step can contain several physics steps: record both intervals before comparing trajectories or costs.

InteractiveActuators and contacts
The engine loads when the button is pressed. Until then there is no simulated trajectory.

Official engine MuJoCo 3.8.1 WASM, one thread, and Gymnasium 1.4 MJCF Hopper-v5. The three controls are normalized inputs to motors with gear 200; the simulator calculates forces and contacts. The image projects centers, axes and radii of the engine capsules; it is not a full 3D renderer. The floor and foot tangential friction and MJCF RK4 timestep can be modified. Each click runs up to ten steps; potential and kinetic energy are computed by MuJoCo.

After each step, MuJoCo warning counters are checked and the batch stops if any increase. On an invalid value, the engine may reset the state internally; the warning is retained even if later readings are finite. Finite readings and no warnings do not guarantee numerical stability.

Provenance, changes and licenses
# Procedencia y cambios locales

Motor monohilo de `@mujoco/mujoco` 3.8.1, publicado por Google DeepMind bajo Apache-2.0. El MJCF `hopper.xml` procede de Gymnasium v1.4.0, bajo licencia MIT. Se conservan ambos textos de licencia.

- `mujoco.js` oficial: SHA-256 `3bd00d879e95fab2f746a1f3bc05e9f97defba537aad716ed8ec7297e3c992b0`; archivo modificado: `3ce5c064ae1de26011a7b8b2ac2e8a1eb833f8be590ce347a377e533e2038f18`.
- `mujoco.wasm` sin cambios: SHA-256 `1e1f288b261794341baf2de3ca4b2a83bf33ea3d195c7c057c90150f0a275c85`.
- `mujoco.d.ts` sin cambios: SHA-256 `28917c3a709ee762792aa784d612cf293ca01c1cc817b54dfa3b730f4b09ff3d`.
- `hopper.xml` sin cambios: SHA-256 `3ce93a055ffdcd83c0c701d2400768e40d2cbb9532f3c4ae33377c27f8b39f9e`.

En `getUniqueRunDependency`, el sufijo aleatorio se reemplazó por un contador `BigInt` local creciente. El algoritmo sigue probando el nombre original y, si está ocupado, busca un sufijo libre en `runDependencyTracking`. Estos identificadores coordinan cargas de archivos y no intervienen en la física. El binario WASM y las licencias no se han modificado.



                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright [yyyy] [name of copyright owner]

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.


The MIT License

Copyright (c) 2016 OpenAI
Copyright (c) 2022 Farama Foundation

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
0.0
0.0
0.0
0.002
0.9
0
Simulated time
not loaded
Contacts
not loaded
Potential / kinetic energy
not loaded
Explore how inputs and model parameters affect simulation.

A joint defines degrees of freedom and limits; an actuator transforms control signals into forces according to its parameters; contacts appear when geometries interact and are resolved using MuJoCo’s constraint model. Friction, damping, contacts and controls can dissipate or supply energy. MuJoCo’s documented Euler integrator is semi-implicit; an overly large step can degrade accuracy or cause numerical problems, but energy variation alone does not prove instability.

To study energy conservation, remove actuation and dissipative forces, avoid contacts, enable energy calculation and compare integrators or steps over the same physical time. Reported energy and constraints have specific conventions: check what data.energy includes and observe warnings or automatic resets on invalid numerical states. The computation documentation and MJCF reference define these details.

Hopper, HalfCheetah, Walker2d, Ant and Humanoid have different bodies and action spaces. Their versioned identifiers can also change observations, rewards or dynamics. Report the exact identifier for any result and avoid comparing versions as if they were necessarily the same problem.

Custom environments, probes and performance

A custom environment must declare its spaces, correctly use the generator initialized by reset, respect the step contract and separate terminals from external cutoffs. check_env helps detect interface violations, but does not prove the rewards or designed problem make sense. A patch prioritization environment, for example, must specify what each action represents, how state changes and its cost or benefit, without confusing a learning simulation with an actual security assessment.

Probes are small MDPs with known answers: constant reward, observation-dependent reward, delayed discounted reward, action choice and combinations of these ideas. An agent that fails to learn these answers may have mask, index, discount or update errors even if it produces a plausible-looking curve on a large task. Fix each probe’s policy and assumptions before deriving its answer.

To measure local performance, use the same environment, version, number of copies and useful work; distinguish physical steps, vector calls and individual transitions. Measure warmup and multiple repetitions, reporting variability and process count. CPU, memory and GPU are shared, so an exact time obtained here is not an algorithm property. SyncVectorEnv, AsyncVectorEnv, systems such as EnvPool and JAX environments have different costs and requirements: a comparison applies only to the measured implementation and hardware.

Labs

The labs use Gymnasium 1.4 and installed MuJoCo. In an isolated environment you can install gymnasium[classic-control,mujoco], numpy and, for video, moviepy and imageio-ffmpeg. Mode ORYON_QUICK=1 reduces steps, workers and duration; ORYON_L13_OUT selects the output directory and ORYON_VIDEO=1 explicitly enables recording. ORYON_WORKERS selects 1 to 64 environments: default is 4 and fast mode uses at most 2. For example, 24 can be tried when the machine is available; processes have coordination costs and that count does not guarantee affinity or use of 24 physical cores. Performance depends on machine and shared load.

The custom environment represents three pending patches: its state includes the remaining decision budget because the horizon belongs to the task. An external TimeLimit can cut off before that horizon and produce truncated. The vector benchmark uses DISABLED: it retains each transition before resetting finished copies. On Windows we run the asynchronous benchmark in a child process guarded by __main__, so spawn workers do not rerun the cell.

[ ]Custom environment, loop and vectorizationLocal GPU
import functools
import json
import os
from pathlib import Path
import subprocess
import sys
import tempfile
import time
import gymnasium as gym
import numpy as np
from gymnasium import spaces
from gymnasium.utils.env_checker import check_env

quick=os.environ.get('ORYON_QUICK','0')=='1'
out=Path(os.environ.get('ORYON_L13_OUT','oryon-m22-l13'))
out.mkdir(parents=True,exist_ok=True)

class PatchPriority(gym.Env):
    metadata={'render_modes':[]}
    def __init__(self,horizon=5):
        self.horizon=horizon
        self.action_space=spaces.Discrete(3)
        self.observation_space=spaces.MultiDiscrete([2,2,2,horizon+1])
    def reset(self,*,seed=None,options=None):
        super().reset(seed=seed)
        self.pending=np.ones(3,dtype=np.int64)
        self.remaining=self.horizon
        return self._obs(),{}
    def _obs(self):
        return np.array([*self.pending,self.remaining],dtype=np.int64)
    def step(self,action):
        if not self.action_space.contains(action): raise ValueError('Acción inválida')
        value=(1.,2.,3.)[int(action)] if self.pending[action] else -.2
        self.pending[action]=0; self.remaining-=1
        terminated=bool(not self.pending.any() or self.remaining==0)
        return self._obs(),value,terminated,False,{}

check_env(PatchPriority(),skip_render_check=True)
patch=gym.wrappers.TimeLimit(PatchPriority(),max_episode_steps=2)
obs,_=patch.reset(seed=1301)
obs,r,term,trunc,_=patch.step(0)
obs,r,term,trunc,_=patch.step(0)
assert trunc and not term and obs[-1]==3
patch.close()
print('PatchPriority: check_env correcto; corte externo distinguido del horizonte')

# TimeLimit dentro de estadísticas y normalización fuera: info registra retorno crudo.
metric_env=gym.make('CartPole-v1',max_episode_steps=10)
metric_env=gym.wrappers.RecordEpisodeStatistics(metric_env)
metric_env=gym.wrappers.NormalizeReward(metric_env)
metric_env.reset(seed=1308); metric_env.action_space.seed(1309)
normalized_total=0.0
while True:
    _,reward,term,trunc,info=metric_env.step(metric_env.action_space.sample())
    normalized_total+=reward
    if term or trunc: break
assert 'episode' in info
print('Retorno crudo',float(info['episode']['r']),
      'retorno normalizado',round(normalized_total,4),'longitud',int(info['episode']['l']))
metric_env.close()

# Las versiones y los errores de disponibilidad se dejan visibles.
print('Gymnasium',gym.__version__,'NumPy',np.__version__)
for name in ('CartPole-v1','Acrobot-v1','MountainCar-v0','Hopper-v5'):
    env=None
    try:
        env=gym.make(name)
        state,info=env.reset(seed=1302); env.action_space.seed(1303)
        total=0.0; completed=0; cuts=0
        for step in range(40 if quick else 2000):
            state,reward,term,trunc,info=env.step(env.action_space.sample())
            total+=reward
            if term or trunc:
                completed+=int(term); cuts+=int(trunc and not term)
                state,info=env.reset()
        print(name,'pasos',step+1,'retorno acumulado',round(total,3),
              'terminales',completed,'cortes',cuts)
    except (ImportError,gym.error.DependencyNotInstalled) as exc:
        print(name,'no disponible:',type(exc).__name__,str(exc))
    finally:
        if env is not None: env.close()

async_program=r'''import functools,hashlib,json,multiprocessing as mp,time
import gymnasium as gym
import numpy as np

def worker(pipe,spec):
    env=gym.make(spec); pending=False
    try:
        while True:
            command,value=pipe.recv()
            if command=='close': break
            if command=='reset':
                obs,info=env.reset(seed=value); pending=False
                pipe.send((obs,info))
            elif command=='step':
                if pending: raise RuntimeError('Reinicia el entorno terminado antes de actuar')
                result=env.step(int(value)); pending=result[2] or result[3]
                pipe.send(result)
            else: raise ValueError('Comando desconocido')
    except EOFError:
        pass
    finally:
        env.close(); pipe.close()

class PipeVector:
    # Misma interfaz de lotes del ejercicio: no reinicia automáticamente.
    def __init__(self,connections):
        self.connections=list(connections); self.pending=False
    def step_async(self,actions):
        if self.pending: raise RuntimeError('Ya hay un lote pendiente')
        actions=list(actions)
        if len(actions)!=len(self.connections): raise ValueError('Número de acciones incorrecto')
        for pipe,action in zip(self.connections,actions): pipe.send(('step',int(action)))
        self.pending=True
    def step_wait(self):
        if not self.pending: raise RuntimeError('No hay lote pendiente')
        result=[pipe.recv() for pipe in self.connections]
        self.pending=False
        return result

class PipeEnvironment:
    def __init__(self,n):
        self.parents=[]; self.processes=[]
        self.observations=[None]*n
        context=mp.get_context('spawn')
        try:
            for _ in range(n):
                parent,child=context.Pipe()
                self.parents.append(parent)
                try:
                    process=context.Process(target=worker,args=(child,'CartPole-v1'))
                    process.start(); self.processes.append(process)
                finally:
                    child.close()
        except BaseException:
            self.close(); raise
        self.vector=PipeVector(self.parents)
    def reset(self,seed=None,options=None):
        mask=np.ones(len(self.parents),dtype=bool) if options is None else np.asarray(options['reset_mask'],dtype=bool)
        if mask.shape!=(len(self.parents),): raise ValueError('Máscara de reset incompatible')
        if self.vector.pending: raise RuntimeError('Hay un lote pendiente')
        for i,pipe in enumerate(self.parents):
            if mask[i]: pipe.send(('reset',None if seed is None else seed+i))
        for i,pipe in enumerate(self.parents):
            if mask[i]: self.observations[i]=pipe.recv()[0]
        if any(obs is None for obs in self.observations): raise RuntimeError('Primero reinicia todas las copias')
        return np.asarray(self.observations),{}
    def step(self,actions):
        self.vector.step_async(actions)
        result=self.vector.step_wait()
        self.observations=[x[0] for x in result]
        return (np.asarray([x[0] for x in result]),np.asarray([x[1] for x in result]),
                np.asarray([x[2] for x in result]),np.asarray([x[3] for x in result]),{})
    def close(self):
        for pipe in self.parents:
            try: pipe.send(('close',None))
            except (BrokenPipeError,EOFError,OSError): pass
        for process in self.processes:
            process.join(timeout=5)
            if process.is_alive(): process.terminate(); process.join()
        for pipe in self.parents: pipe.close()

def benchmark(mode,n,steps,warmup,repetitions):
    startup=time.perf_counter()
    if mode=='pipe': env=PipeEnvironment(n)
    else:
        cls=gym.vector.SyncVectorEnv if mode=='sync' else gym.vector.AsyncVectorEnv
        env=cls([functools.partial(gym.make,'CartPole-v1') for _ in range(n)],
                autoreset_mode=gym.vector.AutoresetMode.DISABLED)
    rows=[]
    try:
        def advance(actions):
            obs,reward,term,trunc,_=env.step(actions)
            # Copia primero la transición final, antes de reiniciar cualquier copia.
            transition=tuple(np.asarray(x).copy() for x in (obs,reward,term,trunc))
            done=transition[2] | transition[3]
            if np.any(done): env.reset(options={'reset_mask':done.copy()})
            return transition
        initial,_=env.reset(seed=1297)
        startup_seconds=time.perf_counter()-startup
        # La acción fija provoca finales y verifica también los resets parciales.
        digest=hashlib.sha256(); digest.update(np.asarray(initial,dtype=np.float64).tobytes())
        checked_resets=0
        for _ in range(64):
            obs,reward,term,trunc=advance(np.zeros(n,dtype=np.int64))
            checked_resets+=int(np.count_nonzero(term | trunc))
            for value,dtype in ((obs,np.float64),(reward,np.float64),(term,np.uint8),(trunc,np.uint8)):
                digest.update(np.asarray(value,dtype=dtype).tobytes())
        assert checked_resets>0, 'El cotejo no incluyó ningún reinicio parcial'
        env.reset(seed=1299); rng=np.random.default_rng(1298)
        for _ in range(warmup): advance(rng.integers(0,2,size=n))
        for trial in range(repetitions):
            env.reset(seed=1304+100*trial); rng=np.random.default_rng(1305+100*trial)
            valid=0; start=time.perf_counter()
            for _ in range(steps):
                advance(rng.integers(0,2,size=n))
                valid+=n
            seconds=time.perf_counter()-start
            rows.append({'transitions':valid,'seconds':seconds,'transitions_per_second':valid/seconds})
    finally:
        env.close()
    rates=[row['transitions_per_second'] for row in rows]
    return {'startup_seconds':startup_seconds,'trajectory_sha256':digest.hexdigest(),'checked_resets':checked_resets,
            'runs':rows,'mean':float(np.mean(rates)),'std':float(np.std(rates))}

def main():
    n=WORKERS; steps=STEPS; warmup=WARMUP; repetitions=REPETITIONS
    result={mode:benchmark(mode,n,steps,warmup,repetitions) for mode in ('sync','async','pipe')}
    counts=[[run['transitions'] for run in result[mode]['runs']] for mode in ('sync','async','pipe')]
    assert counts[0]==counts[1]==counts[2], 'Los entornos no procesaron las mismas transiciones'
    assert len({result[mode]['trajectory_sha256'] for mode in ('sync','async','pipe')})==1, 'Trayectorias diferentes'
    print(json.dumps(result))

if __name__=='__main__': main()
'''
try: requested_workers=int(os.environ.get('ORYON_WORKERS','4'))
except ValueError as exc: raise ValueError('ORYON_WORKERS debe ser un entero entre 1 y 64') from exc
if not 1<=requested_workers<=64: raise ValueError('ORYON_WORKERS debe estar entre 1 y 64')
workers=min(2,requested_workers) if quick else requested_workers
steps=50 if quick else 2000
warmup=10 if quick else 100
repetitions=2 if quick else 5
with tempfile.TemporaryDirectory(prefix='oryon-vector-',dir=out) as tmp:
    helper=Path(tmp)/'benchmark.py'
    code=(async_program.replace('WORKERS',str(workers)).replace('STEPS',str(steps))
          .replace('WARMUP',str(warmup)).replace('REPETITIONS',str(repetitions)))
    helper.write_text(code,encoding='utf-8')
    completed=subprocess.run([sys.executable,str(helper)],capture_output=True,text=True,encoding='utf-8')
    if completed.returncode!=0:
        raise RuntimeError('Benchmark asíncrono falló: '+completed.stderr[-2000:])
    timings=json.loads(completed.stdout.strip().splitlines()[-1])
print('Benchmark DISABLED:',timings,'workers',workers,'calentamiento',warmup)

video=os.environ.get('ORYON_VIDEO','0')=='1'
if video:
    env=gym.make('CartPole-v1',render_mode='rgb_array')
    try:
        env=gym.wrappers.RecordVideo(env,str(out/'video'),episode_trigger=lambda episode:episode==0)
        state,_=env.reset(seed=1306); env.action_space.seed(1307)
        while True:
            state,reward,term,trunc,_=env.step(env.action_space.sample())
            if term or trunc: break
    finally: env.close()
    print('Vídeo de CartPole guardado en',out/'video')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The benchmark compares SyncVectorEnv, AsyncVectorEnv and a minimal PipeVector with the same DISABLED mode, actions and seeds per repetition. It first compares a fingerprint of observations, rewards and signals; then warms each implementation and shows individual measurements, mean and deviation. It separately measures construction and first reset, excluding startup and shutdown from sustained throughput. Each transition is copied before partial reset, whose cost is included in throughput. PipeVector uses the exercise’s batch interface; the adapter adds reset and close, but the benchmark does not automatically run the reader’s solution. Each environment and its processes close in finally; the guarded test supervises the entire process tree. Video records only with ORYON_VIDEO=1.

The output of TimeLimit can have terminated and truncated both true. For a value target, bootstrap is zero when terminated is true; on pure truncation use the transition’s final observation. In NEXT_STEP that observation appears on the terminating call; in SAME_STEP extract info['final_obs'] under mask info['_final_obs']. DISABLED requires explicit reset of finished indices.

The next five probes are small MDPs with analytical solutions. Interface check_agent receives a function returning two Q values for each identifier and observation. We separately check that environment transitions match those solutions. Such a suite detects some agent errors, but does not prove it works in every environment.

[ ]Five probes with known valuesLocal GPU
import gymnasium as gym
import numpy as np
from gymnasium import spaces
from gymnasium.utils.env_checker import check_env

class Probe(gym.Env):
    metadata={'render_modes':[]}
    def __init__(self,kind):
        if kind not in range(5): raise ValueError('Sonda desconocida')
        self.kind=kind; self.observation_space=spaces.Discrete(2); self.action_space=spaces.Discrete(2)
    def reset(self,*,seed=None,options=None):
        super().reset(seed=seed)
        default=int(self.np_random.integers(2)) if self.kind in (1,4) else 0
        self.state=int(options.get('state',default)) if options else default
        if not self.observation_space.contains(self.state): raise ValueError('Estado inválido')
        return self.state,{}
    def step(self,action):
        if not self.action_space.contains(action): raise ValueError('Acción inválida')
        if self.kind==0: reward,terminated=1.0,True
        elif self.kind==1: reward,terminated=(1.0 if self.state else -1.0),True
        elif self.kind==2:
            reward,terminated=(0.0,False) if self.state==0 else (1.0,True)
        elif self.kind==3: reward,terminated=float(action),True
        else: reward,terminated=float(action==self.state),True
        if self.kind==2 and not terminated: self.state=1
        return self.state,reward,terminated,False,{}

gamma=.9
truth={0:{0:[1.,1.]},1:{0:[-1.,-1.],1:[1.,1.]},
       2:{0:[gamma,gamma],1:[1.,1.]},3:{0:[0.,1.]},
       4:{0:[1.,0.],1:[0.,1.]}}
for kind,states in truth.items():
    check_env(Probe(kind),skip_render_check=True)
    for state,expected in states.items():
        for action in range(2):
            env=Probe(kind); obs,_=env.reset(seed=1310,options={'state':state})
            nxt,reward,term,trunc,_=env.step(action)
            continuation=0.0 if term else truth[kind][nxt][0]
            assert np.isclose(reward+gamma*continuation,expected[action],atol=1e-12)
            env.close()

def check_agent(predict_q,tolerance=.05):
    failures=[]
    for kind,states in truth.items():
        for state,expected in states.items():
            predicted=np.asarray(predict_q(kind,state),dtype=float)
            if predicted.shape!=(2,) or not np.all(np.isfinite(predicted)) or not np.allclose(predicted,expected,atol=tolerance,rtol=0):
                failures.append((kind,state))
    return failures

assert not check_agent(lambda kind,state:truth[kind][state],1e-12)
assert check_agent(lambda kind,state:[0.,0.])
print('Cinco sondas verificadas; un oráculo pasa y el predictor nulo falla',
      len(check_agent(lambda kind,state:[0.,0.])), 'casos')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

To test a trained agent, replace the oracle with a function querying its Q values after training on each probe. Declare the tolerance, and use multiple seeds for a stochastic test; the exact check above checks the probe contract and does not certify training.

The next MJCF model has two joints and two motors. To measure energy drift, controls, damping and contacts are disabled; gravity remains active. Flag energy enables kinetic and potential energy calculation. Numerical integration need not conserve exact energy: we compare differences after the same physical time with several steps. In the environment, TimeLimit is an external cutoff, not a physical goal.

[ ]MJCF: actuated double pendulum and energyLocal GPU
import math
import os
import gymnasium as gym
import mujoco
import numpy as np
from gymnasium import spaces
from gymnasium.utils.env_checker import check_env

quick=os.environ.get('ORYON_QUICK','0')=='1'
XML='''<mujoco model="doble_pendulo">
  <option timestep="0.002" gravity="0 0 -9.81" integrator="RK4">
    <flag energy="enable"/>
  </option>
  <default>
    <joint type="hinge" axis="0 1 0" damping="0"/>
    <geom type="capsule" size="0.03" density="500" contype="0" conaffinity="0"/>
    <motor ctrllimited="true" ctrlrange="-1 1"/>
  </default>
  <worldbody>
    <body name="link1" pos="0 0 0">
      <joint name="joint1"/>
      <geom fromto="0 0 0 0 0 -0.5"/>
      <body name="link2" pos="0 0 -0.5">
        <joint name="joint2"/>
        <geom fromto="0 0 0 0 0 -0.5"/>
      </body>
    </body>
  </worldbody>
  <actuator>
    <motor name="motor1" joint="joint1"/>
    <motor name="motor2" joint="joint2"/>
  </actuator>
</mujoco>'''

def drift(timestep,duration):
    model=mujoco.MjModel.from_xml_string(XML)
    model.opt.timestep=timestep
    data=mujoco.MjData(model)
    data.qpos[:]=[.8,-.5]; data.qvel[:]=0; data.ctrl[:]=0
    mujoco.mj_forward(model,data)
    initial=float(np.sum(data.energy))
    steps=round(duration/timestep)
    for _ in range(steps): mujoco.mj_step(model,data)
    mujoco.mj_forward(model,data)
    final=float(np.sum(data.energy))
    if not np.all(np.isfinite(data.qpos)) or not np.isfinite(final):
        raise ArithmeticError('Estado o energía no finitos')
    return initial,final,steps,float(data.time)

duration=.2 if quick else 4.0
print('MuJoCo',mujoco.__version__,'tiempo físico',duration)
for dt in (.002,.005,.01):
    initial,final,steps,elapsed=drift(dt,duration)
    print('dt',dt,'pasos',steps,'tiempo simulado',round(elapsed,6),
          'energía inicial',round(initial,8),'final',round(final,8),
          'deriva absoluta',round(final-initial,8))

class DoublePendulum(gym.Env):
    metadata={'render_modes':[]}
    def __init__(self):
        self.model=mujoco.MjModel.from_xml_string(XML)
        self.data=mujoco.MjData(self.model)
        self.action_space=spaces.Box(-1.,1.,shape=(2,),dtype=np.float32)
        self.observation_space=spaces.Box(-np.inf,np.inf,shape=(4,),dtype=np.float64)
    def _obs(self):
        return np.concatenate((self.data.qpos.copy(),self.data.qvel.copy()))
    def reset(self,*,seed=None,options=None):
        super().reset(seed=seed)
        mujoco.mj_resetData(self.model,self.data)
        self.data.qpos[:]=self.np_random.uniform(-.1,.1,size=2)
        mujoco.mj_forward(self.model,self.data)
        return self._obs(),{}
    def step(self,action):
        action=np.asarray(action,dtype=np.float32)
        if not self.action_space.contains(action): raise ValueError('Acción inválida')
        self.data.ctrl[:]=action
        for _ in range(5): mujoco.mj_step(self.model,self.data)
        obs=self._obs()
        if not np.all(np.isfinite(obs)): raise ArithmeticError('Estado no finito')
        reward=-float(obs[:2]@obs[:2]+.01*(obs[2:]@obs[2:])+.001*(action@action))
        return obs,reward,False,False,{}

check_env(DoublePendulum(),skip_render_check=True)
env=gym.wrappers.TimeLimit(DoublePendulum(),max_episode_steps=3)
obs,_=env.reset(seed=1311)
for _ in range(3): obs,reward,term,trunc,info=env.step(np.zeros(2,dtype=np.float32))
assert not term and trunc and env.observation_space.contains(obs)
env.close()
print('Entorno validado; el límite externo se informa como truncamiento')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Energy recorded by MuJoCo includes gravitational potential and kinetic energy in this model without springs or contacts. In other models mjData.energy excludes constraint energy, and actuators, dissipation and contacts can change mechanical energy. A smaller step is not a universal stability guarantee for every integrator or model. Measurements belong to the experiment, not a general law.

Exercises

CodeA horizon that is part of the task
With Gymnasium 1.4.0 implement RemainingTime(env, horizon), a gym.Wrapper for an environment with any observation space. horizon is a positive integer. The returned observation must be a dictionary {'observation': obs, 'remaining': t}, with a Dict space preserving the original space and using Discrete(horizon+1) for t. reset(seed=None, options=None) forwards both parameters to the environment, returns the same info and starts with t=horizon. Each step forwards the action, decrements t by one and preserves reward and info. If the counter reaches zero, the horizon is part of the task: return terminated=True. Also preserve terminated and truncated from the inner transition, so both may be true simultaneously. An inner truncation before the horizon does not become termination. After either end, disallow step until reset and raise RuntimeError. Do not change the original observation or space. Reject invalid horizon with ValueError.
import gymnasium as gym

class RemainingTime(gym.Wrapper):
  pass
Shift+Enter to run
QuizSix loops, three reset modes
In Gymnasium 1.4.0 each row i has obs, action a, reward r, next_obs, term and trunc; done=term|trunc. Store each real transition once, including its final observation, and continue collecting after reset. Which of these six fragments are incorrect? 1) NEXT_STEP: always store (obs,a,r,next_obs). 2) NEXT_STEP: store only if previous_done[i] was false, then update previous_done=done. 3) SAME_STEP: always store next_obs without consulting info. 4) SAME_STEP: if done use info['final_obs'][i] under mask _final_obs, otherwise next_obs. 5) DISABLED: store next_obs before reset(options={'reset_mask': done}) when any done. 6) DISABLED: reset with mask first and use its returned observation as the finished transition’s next observation.
NumericFrames and simulated time
10⁷ agent steps complete, each advancing exactly 4 game frames at 60 Hz; none is cut short. How many hours of simulated play do they represent?
QuizWhich reward do statistics measure
You construct env = W4(W3(W2(W1(base)))); W1 is innermost. You want the external limit in statistics and statistics to sum original reward, while the agent receives transformed reward. Which order is suitable?
CodeSend before waiting
Implement PipeVector(connections) and start_workers(ctx, worker, specs) for a minimal asynchronous vector. start_workers creates one Pipe and Process per specs entry using ctx.Pipe() and ctx.Process(target=worker,args=(child_end,spec)), starts processes, closes child ends in the parent, and returns (PipeVector with parent ends, process list). worker must be importable with spawn; it accepts ('step', action) and replies (observation, reward, terminated, truncated, info). Workers follow DISABLED mode and the caller resets each finished environment before reuse; this class does not autoreset. step_async(actions) requires one action per connection, sends every command before receiving any and leaves a pending batch. step_wait() requires a pending batch, receives one response per connection in the same order and returns the list of tuples. Raise ValueError for incorrect length and RuntimeError for sending another batch before collecting the previous one or waiting without a batch. If send or recv fails, propagate the error: batch and connections may be out of sync, so the caller must close and rebuild the vector. The caller manages process closure and recovery. Tests check real pipes and a simulated context without starting processes; run the lab to test real processes. To compare throughput with official AsyncVectorEnv, use the same environment, seeds, DISABLED mode and number of real transitions; discard warmup and measure startup and stepping separately.
def start_workers(ctx, worker, specs):
  pass

class PipeVector:
  pass
Shift+Enter to run
[ ]Check the exercise framesBrowser
agent_steps=10**7
frames_per_step=4
frames=agent_steps*frames_per_step
print('Fotogramas:',frames,'horas a 60 Hz:',frames/60/3600)