Skip to content

Commit 4507f16

Browse files
committed
[Feature] Refactor Dreamer training with async collectors, profiling, and improved config
Major changes: - Switch from SyncDataCollector to MultiCollector with async mode - Add DreamerProfiler class for PyTorch profiling - Add allocate_collector_devices for multi-GPU device allocation - Add make_storage_transform for extend-time image processing - Expand compile config with backend, mode, and per-loss settings - Add profiling config section - Add throughput metrics (FPS, SPS, UPS) - Use fused Adam optimizers - Comprehensive README rewrite - Update CI test command parameters ghstack-source-id: 19cadf7 Pull-Request: #3308
1 parent eb164ad commit 4507f16

5 files changed

Lines changed: 817 additions & 206 deletions

File tree

.github/unittest/linux_sota/scripts/test_sota.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -284,6 +284,7 @@
284284
collector.total_frames=600 \
285285
collector.init_random_frames=10 \
286286
collector.frames_per_batch=200 \
287+
collector.num_collectors=1 \
287288
env.n_parallel_envs=1 \
288289
optimization.optim_steps_per_batch=1 \
289290
optimization.compile=False \
@@ -292,6 +293,7 @@
292293
replay_buffer.buffer_size=120 \
293294
replay_buffer.batch_size=24 \
294295
replay_buffer.batch_length=12 \
296+
replay_buffer.prefetch=1 \
295297
networks.rssm_hidden_dim=17
296298
""",
297299
}
Lines changed: 128 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,129 @@
1-
# Dreamer example
1+
# Dreamer V1
22

3-
## Note:
4-
This example is not included in the benchmarked results of the current release (v0.3). The intention is to include it in the
5-
benchmarking of future releases, to ensure that it can be successfully run with the release code and that the
6-
results are consistent. For now, be aware that this additional check has not been performed in the case of this
7-
specific example.
3+
This is an implementation of the Dreamer algorithm from the paper
4+
["Dream to Control: Learning Behaviors by Latent Imagination"](https://arxiv.org/abs/1912.01603) (Hafner et al., ICLR 2020).
5+
6+
Dreamer is a model-based reinforcement learning algorithm that:
7+
1. Learns a **world model** (RSSM) from experience
8+
2. **Imagines** future trajectories in latent space
9+
3. Trains **actor and critic** using analytic gradients through the imagined rollouts
10+
11+
## Setup
12+
13+
### Dependencies
14+
15+
```bash
16+
# Create virtual environment
17+
uv venv torchrl --python 3.12
18+
source torchrl/bin/activate
19+
20+
# Install PyTorch (adjust for your CUDA version)
21+
uv pip install --pre torch torchvision --index-url https://download.pytorch.org/whl/nightly/cu128
22+
23+
# Install TorchRL and TensorDict
24+
uv pip install tensordict torchrl
25+
26+
# Install additional dependencies
27+
uv pip install mujoco dm_control wandb tqdm hydra-core
28+
```
29+
30+
### System Dependencies (for MuJoCo rendering)
31+
32+
```bash
33+
apt-get update && apt-get install -y \
34+
libegl1 \
35+
libgl1 \
36+
libgles2 \
37+
libglvnd0
38+
```
39+
40+
### Environment Variables
41+
42+
```bash
43+
export MUJOCO_GL=egl
44+
export MUJOCO_EGL_DEVICE_ID=0
45+
```
46+
47+
## Running
48+
49+
```bash
50+
python dreamer.py
51+
```
52+
53+
### Configuration
54+
55+
The default configuration trains on DMControl's `cheetah-run` task. You can override settings via command line:
56+
57+
```bash
58+
# Different environment
59+
python dreamer.py env.name=walker env.task=walk
60+
61+
# Mixed precision options: false, true (=bfloat16), float16, bfloat16
62+
python dreamer.py optimization.autocast=bfloat16 # default
63+
python dreamer.py optimization.autocast=float16 # for older GPUs
64+
python dreamer.py optimization.autocast=false # disable autocast
65+
66+
# Adjust batch size
67+
python dreamer.py replay_buffer.batch_size=1000
68+
```
69+
70+
## Known Caveats
71+
72+
### 1. Mixed Precision (Autocast) Compatibility
73+
74+
Some GPU/cuBLAS combinations have issues with `bfloat16` autocast, resulting in:
75+
```
76+
RuntimeError: CUDA error: CUBLAS_STATUS_INVALID_VALUE when calling cublasGemmEx
77+
```
78+
79+
**Solutions:**
80+
- Try float16: `optimization.autocast=float16`
81+
- Or disable autocast entirely: `optimization.autocast=false`
82+
83+
Note: Ensure your PyTorch CUDA version matches your driver. For example, with CUDA 13.0:
84+
```bash
85+
uv pip install --pre torch torchvision --index-url https://download.pytorch.org/whl/nightly/cu130
86+
```
87+
88+
### 2. Benchmarking Status
89+
90+
This implementation has not been fully benchmarked against the original paper's results.
91+
Performance may differ from published numbers.
92+
93+
### 3. Video Logging
94+
95+
To enable video logging of both real and imagined rollouts:
96+
```bash
97+
python dreamer.py logger.video=True
98+
```
99+
100+
This requires additional setup for rendering and significantly increases computation time.
101+
102+
## Architecture Overview
103+
104+
```
105+
World Model:
106+
- ObsEncoder: pixels -> encoded_latents
107+
- RSSMPrior: (state, belief, action) -> next_belief, prior_dist
108+
- RSSMPosterior: (belief, encoded_latents) -> posterior_dist, state
109+
- ObsDecoder: (state, belief) -> reconstructed_pixels
110+
- RewardModel: (state, belief) -> predicted_reward
111+
112+
Actor: (state, belief) -> action_distribution
113+
Critic: (state, belief) -> state_value
114+
```
115+
116+
## Training Loop
117+
118+
1. **Collect** real experience from environment
119+
2. **Train world model** on sequences from replay buffer (KL + reconstruction + reward loss)
120+
3. **Imagine** trajectories starting from encoded real states
121+
4. **Train actor** to maximize imagined returns (gradients flow through dynamics)
122+
5. **Train critic** to predict lambda returns on imagined trajectories
123+
124+
## References
125+
126+
- Original Paper: [Dream to Control: Learning Behaviors by Latent Imagination](https://arxiv.org/abs/1912.01603)
127+
- PlaNet (predecessor): [Learning Latent Dynamics for Planning from Pixels](https://arxiv.org/abs/1811.04551)
128+
- DreamerV2: [Mastering Atari with Discrete World Models](https://arxiv.org/abs/2010.02193)
129+
- DreamerV3: [Mastering Diverse Domains through World Models](https://arxiv.org/abs/2301.04104)

sota-implementations/dreamer/config.yaml

Lines changed: 45 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,9 @@ collector:
1515
total_frames: 5_000_000
1616
init_random_frames: 3000
1717
frames_per_batch: 1000
18+
# Number of parallel collector workers (async mode)
19+
# On multi-GPU: must be <= num_gpus - 1 (cuda:0 reserved for training)
20+
num_collectors: 7
1821
device:
1922

2023
optimization:
@@ -26,13 +29,18 @@ optimization:
2629
value_lr: 8e-5
2730
kl_scale: 1.0
2831
free_nats: 3.0
29-
optim_steps_per_batch: 80
32+
optim_steps_per_batch: 20
3033
gamma: 0.99
3134
lmbda: 0.95
3235
imagination_horizon: 15
33-
compile: False
34-
compile_backend: inductor
35-
use_autocast: True
36+
compile:
37+
enabled: True
38+
backend: inductor # or cudagraphs
39+
mode: reduce-overhead
40+
# Which losses to compile (subset of: world_model, actor, value)
41+
losses: ["world_model", "actor", "value"]
42+
# Autocast options: false, true (=bfloat16), float16, bfloat16
43+
autocast: bfloat16
3644

3745
networks:
3846
exploration_noise: 0.3
@@ -41,13 +49,21 @@ networks:
4149
rssm_hidden_dim: 200
4250
hidden_dim: 400
4351
activation: "elu"
52+
# Use torch.scan for RSSM rollout (faster, no graph breaks with torch.compile)
53+
use_scan: False
54+
rssm_rollout:
55+
# Compile only the per-timestep RSSM rollout step (keeps Python loop, avoids scan/unrolling).
56+
compile: False
57+
compile_backend: inductor
58+
compile_mode: reduce-overhead
4459

4560

4661
replay_buffer:
47-
batch_size: 2500
62+
batch_size: 10000
4863
buffer_size: 1000000
4964
batch_length: 50
5065
scratch_dir: null
66+
prefetch: 8
5167

5268
logger:
5369
backend: wandb
@@ -58,3 +74,27 @@ logger:
5874
eval_iter: 10
5975
eval_rollout_steps: 500
6076
video: False
77+
78+
profiling:
79+
# Enable PyTorch profiling (overrides total_frames to profiling_total_frames)
80+
enabled: False
81+
# Total frames to collect when profiling (default: 5005 = 5 collection iters + buffer warmup)
82+
total_frames: 5005
83+
# Skip the first N optim steps (no profiling at all)
84+
skip_first: 1
85+
# Warmup steps (profiler runs but data discarded for warmup)
86+
warmup_steps: 1
87+
# Number of optim steps to profile (actual traced data)
88+
active_steps: 1
89+
# Export chrome trace to this file (if set)
90+
trace_file: dreamer_trace.json
91+
# Profile CUDA kernels (VERY heavy on GPU - 13GB vs 1GB trace!)
92+
profile_cuda: true
93+
# Record tensor shapes
94+
record_shapes: True
95+
# Profile memory usage
96+
profile_memory: True
97+
# Record Python call stacks
98+
with_stack: True
99+
# Compute FLOPs
100+
with_flops: True

0 commit comments

Comments
 (0)