|
| 1 | +# ALE Vector Environment Guide |
| 2 | + |
| 3 | +## Introduction |
| 4 | + |
| 5 | +The Arcade Learning Environment (ALE) Vector Environment provides a high-performance implementation for running multiple Atari environments in parallel. This implementation utilizes native C++ code with multi-threading to achieve significant performance improvements, especially when running many environments simultaneously. |
| 6 | + |
| 7 | +The vector environment is equivalent to `FrameStackObservation(AtariPreprocessing(gym.make("ALE/{AtariGame}-v5")), stack_size=4)`. |
| 8 | + |
| 9 | +## Key Features |
| 10 | + |
| 11 | +- **Parallel Execution**: Run multiple Atari environments simultaneously with minimal overhead |
| 12 | +- **Standard Preprocessing**: Includes standard preprocessing steps from the Atari Deep RL literature: |
| 13 | + - Frame skipping |
| 14 | + - Observation resizing |
| 15 | + - Grayscale conversion |
| 16 | + - Frame stacking |
| 17 | + - NoOp initialization at reset |
| 18 | + - Fire reset (for games requiring the fire button to start) |
| 19 | + - Episodic life modes |
| 20 | +- **Performance Optimizations**: |
| 21 | + - Native C++ implementation |
| 22 | + - Next-step autoreset (see [blog](https://farama.org/Vector-Autoreset-Mode) for more detail) |
| 23 | + - Multi-threading for parallel execution |
| 24 | + - Thread affinity options for better performance on multi-core systems |
| 25 | + - Batch processing capabilities |
| 26 | +- **Asynchronous Operation**: Split step operation into `send` and `recv` for more flexible control flow |
| 27 | +- **Gymnasium Compatible**: Implements the Gymnasium `VectorEnv` [interface](https://gymnasium.farama.org/api/vector/) |
| 28 | + |
| 29 | +## Installation |
| 30 | + |
| 31 | +The vector implementation is packaged with ale-py that can be installed through PyPI, `pip install ale-py`. |
| 32 | + |
| 33 | +Optionally, users can build the project locally, requiring VCPKG, that will install OpenCV to support observation preprocessing. |
| 34 | + |
| 35 | +## Basic Usage |
| 36 | + |
| 37 | +### Creating a Vector Environment |
| 38 | + |
| 39 | +```python |
| 40 | +from ale_py.vector_env import VectorAtariEnv |
| 41 | + |
| 42 | +# Create a vector environment with 4 parallel instances of Breakout |
| 43 | +envs = VectorAtariEnv( |
| 44 | + game="Breakout", |
| 45 | + num_envs=4, |
| 46 | +) |
| 47 | + |
| 48 | +# Reset all environments |
| 49 | +observations, info = envs.reset() |
| 50 | + |
| 51 | +# Take random actions in all environments |
| 52 | +actions = envs.action_space.sample() |
| 53 | +observations, rewards, terminations, truncations, infos = envs.step(actions) |
| 54 | + |
| 55 | +# Close the environment when done |
| 56 | +envs.close() |
| 57 | +``` |
| 58 | + |
| 59 | +## Advanced Configuration |
| 60 | + |
| 61 | +The vector environment provides numerous configuration options: |
| 62 | + |
| 63 | +```python |
| 64 | +envs = VectorAtariEnv( |
| 65 | + # Required parameters |
| 66 | + game="Breakout", # ROM name in snake_case |
| 67 | + num_envs=8, # Number of parallel environments |
| 68 | + |
| 69 | + # Preprocessing parameters |
| 70 | + frame_skip=4, # Number of frames to skip (action repeat) |
| 71 | + grayscale=True, # Use grayscale observations |
| 72 | + stack_num=4, # Number of frames to stack |
| 73 | + img_height=84, # Height to resize frames to |
| 74 | + img_width=84, # Width to resize frames to |
| 75 | + |
| 76 | + # Environment behavior |
| 77 | + noop_max=30, # Maximum number of no-ops at reset |
| 78 | + fire_reset=True, # Press FIRE on reset for games that require it |
| 79 | + episodic_life=False, # End episodes on life loss |
| 80 | + max_episode_steps=108000, # Max frames per episode (27000 steps * 4 frame skip) |
| 81 | + repeat_action_probability=0.0, # Sticky actions probability |
| 82 | + full_action_space=False, # Use full action space (not minimal) |
| 83 | + |
| 84 | + # Performance options |
| 85 | + batch_size=0, # Number of environments to process at once (default=0 is the `num_envs`) |
| 86 | + num_threads=0, # Number of worker threads (0=auto) |
| 87 | + thread_affinity_offset=-1,# CPU core offset for thread affinity (-1=no affinity) |
| 88 | + seed=0, # Random seed |
| 89 | +) |
| 90 | +``` |
| 91 | + |
| 92 | +## Observation Format |
| 93 | + |
| 94 | +The observation format from the vector environment is: |
| 95 | + |
| 96 | +``` |
| 97 | +observations.shape = (num_envs, stack_size, height, width) |
| 98 | +``` |
| 99 | + |
| 100 | +Where: |
| 101 | +- `num_envs`: Number of parallel environments |
| 102 | +- `stack_size`: Number of stacked frames (typically 4) |
| 103 | +- `height`, `width`: Image dimensions (typically 84x84) |
| 104 | + |
| 105 | +This differs from the standard Gymnasium Atari environment format which uses: |
| 106 | +``` |
| 107 | +observations.shape = (num_envs, stack_size, height, width) # Without num_envs |
| 108 | +``` |
| 109 | + |
| 110 | +## Performance Considerations |
| 111 | + |
| 112 | +### Number of Environments |
| 113 | + |
| 114 | +Increasing the number of environments typically improves throughput until you hit CPU core limits. |
| 115 | +For optimal performance, set `num_envs` close to the number of physical CPU cores. |
| 116 | + |
| 117 | +### Send/Recv vs Step |
| 118 | + |
| 119 | +Using the `send`/`recv` API can allow for better overlapping of computation and environment stepping: |
| 120 | + |
| 121 | +```python |
| 122 | +# Send actions to environments |
| 123 | +envs.send(actions) |
| 124 | + |
| 125 | +# Do other computation here while environments are stepping |
| 126 | + |
| 127 | +# Receive results when ready |
| 128 | +observations, rewards, terminations, truncations, infos = envs.recv() |
| 129 | +``` |
| 130 | + |
| 131 | +### Batch Size |
| 132 | + |
| 133 | +The `batch_size` parameter controls how many environments are processed simultaneously by the worker threads: |
| 134 | + |
| 135 | +```python |
| 136 | +# Process environments in batches of 4 |
| 137 | +envs = VectorAtariEnv(game="Breakout", num_envs=16, batch_size=4) |
| 138 | +``` |
| 139 | + |
| 140 | +A smaller batch size can improve latency while a larger batch size can improve throughput. |
| 141 | +When passing a batch size, the information will include the environment id of each observation |
| 142 | +which is critical as the first (batch size) observations are returned for `reset` and `recv`. |
| 143 | + |
| 144 | +### Thread Affinity |
| 145 | + |
| 146 | +On systems with multiple CPU cores, setting thread affinity can improve performance: |
| 147 | + |
| 148 | +```python |
| 149 | +# Set thread affinity starting from core 0 |
| 150 | +envs = VectorAtariEnv(game="Breakout", num_envs=8, thread_affinity_offset=0) |
| 151 | +``` |
| 152 | + |
| 153 | + |
| 154 | +## Examples |
| 155 | + |
| 156 | +### Training Example with PyTorch |
| 157 | + |
| 158 | +```python |
| 159 | +import torch |
| 160 | +import numpy as np |
| 161 | +from ale_py.vector_env import VectorAtariEnv |
| 162 | + |
| 163 | +# Create environment |
| 164 | +envs = VectorAtariEnv(game="Breakout", num_envs=8) |
| 165 | +device = torch.device("cuda" if torch.cuda.is_available() else "cpu") |
| 166 | + |
| 167 | +# Initialize model (simplified example) |
| 168 | +model = torch.nn.Sequential( |
| 169 | + torch.nn.Conv2d(4, 32, kernel_size=8, stride=4), |
| 170 | + torch.nn.ReLU(), |
| 171 | + torch.nn.Conv2d(32, 64, kernel_size=4, stride=2), |
| 172 | + torch.nn.ReLU(), |
| 173 | + torch.nn.Conv2d(64, 64, kernel_size=3, stride=1), |
| 174 | + torch.nn.ReLU(), |
| 175 | + torch.nn.Flatten(), |
| 176 | + torch.nn.Linear(3136, 512), |
| 177 | + torch.nn.ReLU(), |
| 178 | + torch.nn.Linear(512, envs.single_action_space.n) |
| 179 | +).to(device) |
| 180 | + |
| 181 | +# Reset environment |
| 182 | +observations, _ = envs.reset() |
| 183 | + |
| 184 | +# Training loop |
| 185 | +for step in range(1000): |
| 186 | + # Convert observations to PyTorch tensors |
| 187 | + obs_tensor = torch.tensor(observations, dtype=torch.float32, device=device) / 255.0 |
| 188 | + |
| 189 | + # Get actions from model |
| 190 | + with torch.no_grad(): |
| 191 | + q_values = model(obs_tensor) |
| 192 | + actions = q_values.max(dim=1)[1].cpu().numpy() |
| 193 | + |
| 194 | + # Step the environment |
| 195 | + observations, rewards, terminations, truncations, infos = envs.step(actions) |
| 196 | +``` |
0 commit comments