thrust-rl 0.4.0

High-performance reinforcement learning in Rust with the Burn tensor backend
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
# Research Papers & Architecture Insights for Thrust

This document catalogs key papers, systems, and insights that should inform Thrust's architecture design.

> **⚠️ Backend note.** The "Architecture Recommendations" sections below predate
> the Burn migration and recommend `tch-rs` / PyTorch bindings for the GPU path.
> Thrust has since moved entirely to the pure-Rust [Burn]https://burn.dev
> framework (NdArray default; `wgpu` / `cuda` opt-in) — see
> [`BURN_BACKENDS.md`]BURN_BACKENDS.md. The *algorithm* and *systems* insights
> here remain valuable; read the `tch`/PyTorch backend recommendations as
> historical context.

---

## Table of Contents

1. [Core RL Algorithms]#core-rl-algorithms
2. [Systems & Performance]#systems--performance
3. [Rust-Specific Considerations]#rust-specific-considerations
4. [Architecture Recommendations]#architecture-recommendations

---

## Core RL Algorithms

### 1. **Proximal Policy Optimization (PPO)**
- **Paper**: Schulman et al., "Proximal Policy Optimization Algorithms" (2017)
- **ArXiv**: https://arxiv.org/abs/1707.06347
- **Key Insights**:
  - Trust region optimization without KL penalty
  - Clipped objective prevents large policy updates
  - Works well with continuous and discrete actions
  - Naturally parallelizable across environments

**Implementation Details** (37 Critical Details):
- **Blog**: https://iclr-blog-track.github.io/2022/03/25/ppo-implementation-details/
- **Key Details**:
  - Vectorized advantage normalization
  - Learning rate annealing
  - Value function clipping
  - Gradient clipping
  - Orthogonal initialization
  - GAE-Lambda for advantage estimation

### 2. **Generalized Advantage Estimation (GAE)**
- **Paper**: Schulman et al., "High-Dimensional Continuous Control Using GAE" (2016)
- **ArXiv**: https://arxiv.org/abs/1506.02438
- **Key Insights**:
  - Bias-variance tradeoff via λ parameter
  - Exponentially-weighted average of TD errors
  - Typically λ=0.95, γ=0.99 for good performance
  - Critical for sample efficiency

---

## Systems & Performance

### 3. **EnvPool: Highly Parallel Environment Execution**
- **Paper**: https://arxiv.org/abs/2206.10558
- **GitHub**: https://github.com/sail-sg/envpool
- **Key Insights**:
  - **1M+ FPS** on Atari, **3M+ FPS** on MuJoCo
  - C++ thread pool with async execution
  - Zero-copy environment resets
  - Batched observation/action transfers
  - 3x end-to-end speedup with CleanRL PPO (200min → 73min)

**Architecture**:
```
┌─────────────────────────────────────────┐
│  Thread Pool (C++/Rust)                 │
│  ┌────┐ ┌────┐ ┌────┐ ┌────┐           │
│  │Env1│ │Env2│ │Env3│ │Env4│  × N      │
│  └────┘ └────┘ └────┘ └────┘           │
│         Async Execution                 │
│         Zero-Copy Buffers               │
└─────────────────────────────────────────┘
            ↓ Batch Transfer
┌─────────────────────────────────────────┐
│  GPU (PyTorch/tch-rs)                   │
│  Policy Network Forward Pass            │
│  Value Network Forward Pass             │
└─────────────────────────────────────────┘
```

**Why This Matters**:
- Environment execution is often the bottleneck (not GPU)
- Async execution hides environment latency
- Perfect fit for Rust's fearless concurrency

### 4. **Sample Factory: Asynchronous RL**
- **Paper**: Petrenko et al., "Sample Factory: Egocentric 3D Control from Pixels at 100000 FPS" (2020)
- **ArXiv**: https://arxiv.org/abs/2006.11751
- **GitHub**: https://github.com/alex-petrenko/sample-factory
- **Key Insights**:
  - Asynchronous architecture (IMPALA-style)
  - 100K+ FPS throughput
  - Batched inference on GPU
  - Separate actors and learners

**Architecture**:
```
┌──────────┐  ┌──────────┐  ┌──────────┐
│ Actor 1  │  │ Actor 2  │  │ Actor N  │
│ (CPU)    │  │ (CPU)    │  │ (CPU)    │
└────┬─────┘  └────┬─────┘  └────┬─────┘
     │             │              │
     └─────────────┴──────────────┘
         ┌─────────────────────┐
         │  Shared Queue        │
         │  (Lock-free)         │
         └─────────────────────┘
         ┌─────────────────────┐
         │  Learner (GPU)       │
         │  Batched Updates     │
         └─────────────────────┘
```

### 5. **CleanRL: Research-Friendly Implementations**
- **Paper**: Huang et al., "CleanRL: High-quality Single-file Implementations of Deep RL Algorithms" (2022)
- **ArXiv**: https://arxiv.org/abs/2111.08819
- **GitHub**: https://github.com/vwxyzjn/cleanrl
- **Key Insights**:
  - Single-file implementations (ppo.py = 340 lines)
  - No abstractions for debuggability
  - Each file is self-contained
  - 3-4x speedup with EnvPool integration

**Philosophy for Thrust**:
- Clear, readable implementations over abstraction
- Each algorithm in one file when possible
- Optimize hot paths without sacrificing clarity

### 6. **V-trace: Off-Policy Correction**
- **Paper**: Espeholt et al., "IMPALA: Scalable Distributed Deep-RL with Importance Weighted Actor-Learner Architectures" (2018)
- **ArXiv**: https://arxiv.org/abs/1802.01561
- **Key Insights**:
  - Off-policy correction for async RL
  - Importance sampling with clipping
  - PufferLib uses this for stability
  - Critical for distributed training

---

## Rust-Specific Considerations

### 7. **Tokio vs Rayon: Async vs Parallelism**
- **Blog**: https://blog.dureuill.net/articles/dont-mix-rayon-tokio/
- **Key Insights**:
  - **Don't mix Tokio and Rayon directly** - causes deadlocks
  - Use channels for communication between async and parallel code
  - Tokio = async I/O (network, timers)
  - Rayon = data parallelism (CPU-bound work)

**For RL in Rust**:
```rust
// Good: Separate concerns
┌─────────────────────────┐
│ Rayon Thread Pool       │
│ - Environment execution │
│ - Data preprocessing    │
│ - Advantage computation │
└─────────────────────────┘
           ↓ Channel
┌─────────────────────────┐
│ Main Thread (or Tokio)  │
│ - GPU inference         │
│ - Model updates         │
│ - Logging/metrics       │
└─────────────────────────┘
```

### 8. **Border: Async RL in Rust**
- **GitHub**: https://github.com/laboroai/border
- **Key Insights**:
  - Uses Tokio for async training
  - Separate actor processes with shared replay buffer
  - tch-rs for PyTorch bindings
  - Supports DQN, SAC, IQN

**Architecture Lessons**:
- Async actors work well in Rust
- Channels for actor → learner communication
- tch-rs is mature enough for production use

### 9. **Zero-Copy and Performance**
- **Insight**: Rust's ownership model enables true zero-copy
- **Key Patterns**:
  - `Arc<Mutex<T>>` for shared mutable state
  - `crossbeam` channels for lock-free MPMC
  - Memory-mapped buffers for observations
  - GPU-pinned memory for faster transfers

---

## Architecture Recommendations

### Design Principles for Thrust

#### 1. **Separate Compute from Coordination**
```rust
// Environment execution: Rayon (CPU parallelism)
// GPU inference: tch-rs (blocking)
// Coordination: Channels (no shared memory)
```

**Why**:
- Avoid Tokio/Rayon mixing issues
- Clear ownership boundaries
- Predictable performance

#### 2. **EnvPool-Inspired Thread Pool**
```rust
pub struct EnvPool {
    envs: Vec<CartPole>,
    thread_pool: rayon::ThreadPool,
    observation_buffer: Vec<Vec<f32>>,
}

impl EnvPool {
    pub fn step_async(&mut self, actions: &[i64]) -> StepResult {
        // Parallel step across all environments
        self.thread_pool.install(|| {
            self.envs.par_iter_mut()
                .zip(actions)
                .map(|(env, &action)| env.step(action))
                .collect()
        })
    }
}
```

**Benefits**:
- 10-100x faster than sequential execution
- Scales with CPU cores
- Zero-copy observation collection

#### 3. **Batched GPU Inference**
```rust
pub struct PolicyBatch {
    observations: Tensor,  // [batch_size, obs_dim]

    pub fn forward(&self, policy: &Policy) -> (Tensor, Tensor) {
        // Single GPU call for entire batch
        policy.forward(&self.observations)
    }
}
```

**Benefits**:
- Amortize GPU kernel launch overhead
- Better GPU utilization
- 5-10x faster than per-env inference

#### 4. **Lock-Free Rollout Buffer**
```rust
pub struct RolloutBuffer {
    // Pre-allocated, no runtime allocation
    observations: Vec<Vec<f32>>,

    // Direct indexing, no locks needed
    pub fn store(&mut self, step: usize, env_id: usize, ...) {
        self.observations[step][env_id] = obs;
    }
}
```

**Benefits**:
- No allocation during training
- Cache-friendly layout
- Thread-safe with simple ownership

#### 5. **CUDA Kernels for Hot Paths (Future)**
Following PufferLib's lead:
- GAE computation → CUDA kernel (1000x speedup)
- Observation preprocessing → CUDA
- Reward normalization → CUDA

**Implementation**:
```rust
// Use cuda-sys or cudarc
mod cuda_ops {
    pub fn compute_gae_advantages(
        values: &[f32],
        rewards: &[f32],
        dones: &[bool],
        gamma: f32,
        lambda: f32,
    ) -> Vec<f32> {
        // CUDA kernel dispatch
    }
}
```

### Performance Targets

Based on literature:

| Component | Target | Reference |
|-----------|--------|-----------|
| Environment FPS | 100K-1M | EnvPool (Atari) |
| GPU Batch Size | 2048-8192 | CleanRL, Sample Factory |
| Samples/sec (CartPole) | 1M+ | Should be easy with Rust |
| Training Time (Atari) | <1 hour | EnvPool + CleanRL |

### Key Trade-offs

#### Synchronous vs Asynchronous
- **Sync (PPO)**: Simpler, more stable, on-policy
- **Async (IMPALA)**: Higher throughput, requires V-trace, off-policy
- **Recommendation**: Start with sync PPO, add async later

#### CPU vs GPU Environments
- **CPU**: Most environments, easier to parallelize
- **GPU** (IsaacGym): Massive parallelism (1000s envs), tight integration
- **Recommendation**: Focus on CPU first, GPU env support later

#### Abstraction vs Performance
- **High abstraction**: Easier to use, harder to optimize
- **Low abstraction**: CleanRL-style, clear hot paths
- **Recommendation**: Minimal abstractions, clear ownership

---

## Recommended Reading Order

1. **Start here**: [37 PPO Implementation Details]https://iclr-blog-track.github.io/2022/03/25/ppo-implementation-details/
2. **System design**: [EnvPool Paper]https://arxiv.org/abs/2206.10558
3. **Rust patterns**: [Don't Mix Tokio and Rayon]https://blog.dureuill.net/articles/dont-mix-rayon-tokio/
4. **Reference impl**: [CleanRL PPO]https://github.com/vwxyzjn/cleanrl/blob/master/cleanrl/ppo.py
5. **Advanced**: [Sample Factory Paper]https://arxiv.org/abs/2006.11751

---

## Next Steps for Thrust

### Phase 1: Core Synchronous PPO ✅ (In Progress)
- [x] CartPole environment
- [x] Rollout buffer with GAE
- [ ] MLP policy (tch-rs)
- [ ] PPO training loop
- [ ] Basic benchmarks

### Phase 2: Performance Optimization
- [ ] Rayon-based EnvPool
- [ ] Batched GPU inference
- [ ] Zero-copy observation buffers
- [ ] Vectorized environments
- [ ] Target: 100K+ samples/sec on CartPole

### Phase 3: Advanced Features
- [ ] CUDA kernels for GAE
- [ ] Async actors (IMPALA-style)
- [ ] Distributed training
- [ ] More environments (Atari, MuJoCo)

### Phase 4: Research Features
- [ ] Recurrent policies (LSTM)
- [ ] Multi-agent support
- [ ] Curiosity-driven exploration
- [ ] Population-based training

---

## Key Questions to Answer

### Architecture Decisions

1. **Environment Parallelism**:
   - Q: Use Rayon thread pool or manual threads?
   - A: Rayon - easier to use, well-tested, integrates with iterators

2. **GPU Strategy**:
   - Q: tch-rs, candle, or burn?
   - A: tch-rs - most mature, proven in Border, PyTorch compatibility

3. **Buffer Layout**:
   - Q: [steps, envs] or [segments, horizon]?
   - A: Start with [steps, envs] simpler, profile and optimize later

4. **Observation Types**:
   - Q: Support images (CNNs) from the start?
   - A: Start with vectors (CartPole, MuJoCo), add images in Phase 2

5. **Communication Pattern**:
   - Q: Shared memory or message passing?
   - A: Message passing (channels) - safer, easier to reason about

---

## Performance Checklist

Before claiming "production ready":

- [ ] 100K+ samples/sec on CartPole (single machine)
- [ ] Match or beat PufferLib on same hardware
- [ ] <1 hour Atari training (40M frames)
- [ ] Zero-copy environment execution
- [ ] Batched GPU inference
- [ ] Memory efficient (no runtime allocation in hot path)
- [ ] Reproducible results (fixed seeds)
- [ ] Comprehensive benchmarks

---

## References

### Papers
- PPO: https://arxiv.org/abs/1707.06347
- GAE: https://arxiv.org/abs/1506.02438
- EnvPool: https://arxiv.org/abs/2206.10558
- Sample Factory: https://arxiv.org/abs/2006.11751
- CleanRL: https://arxiv.org/abs/2111.08819
- IMPALA: https://arxiv.org/abs/1802.01561

### Systems
- CleanRL: https://github.com/vwxyzjn/cleanrl
- EnvPool: https://github.com/sail-sg/envpool
- Sample Factory: https://github.com/alex-petrenko/sample-factory
- PufferLib: https://github.com/PufferAI/PufferLib
- Border (Rust): https://github.com/laboroai/border

### Resources
- 37 PPO Details: https://iclr-blog-track.github.io/2022/03/25/ppo-implementation-details/
- Tokio vs Rayon: https://blog.dureuill.net/articles/dont-mix-rayon-tokio/
- tch-rs: https://github.com/LaurentMazare/tch-rs

---

*Last Updated: 2025-11-05*
*Thrust Version: 0.1.0 (Phase 1, Week 1)*