RL in 100 Lines of PyTorch
Road to FlashRL, Part 1
It has been 10 years since Andrej Karpathy dropped his “Pong from Pixels” blog post: Just ~130 lines of NumPy to learn Pong from raw pixels with a 2-layered neural net. You could copy-paste the gist, run it, grab a coffee… and come back hours later to watch your little paddle slowly learn to hit the ball. Fast-forward to today: everyone can train neural nets to write coherent text in a minute, so learning Pong is surely doable in a second, right… no, even the fastest Pong training today, rl_games on EnvPool, still takes minutes.
In this series of blog posts we celebrate 10 years of “Pong from Pixels” and embrace the from first principles, tiny mindset. We will end up with all the pieces needed to write RL in CUDA/PTX for maximum speed, put together in ⚡FlashRL🍪 (try it now if you want to skip ahead).
In this initial blog post we
- Boil down RL into <100 lines of PyTorch
- Make it ~400x faster using the core insight popularized by PufferLib.
Click here for the core insight spoiler
Instead of the RL environment (env) being pure Python (or an Atari ROM wrapped in Python), write the env logic + PyTorch tensor IO directly in C!Just like “Pong from Pixels”, the resulting scripts are ready to be copy-pasted here.
STAY TUNED…
All blogs of this series will be announced here and linked in this list upon release:
TL;DR
In this blog post we
- motivate why
- game RL is important
- simple & fast code is underrated
- boil down RL into <100 lines of PyTorch and based on that explain…
- …why RL is harder than supervised learning
- …what A2C adds to basic policy gradients (+ why we do not use PPO)
- introduce “agent chasing cookies” as our simple RL environment
- 400x speed up training by making the environment code less dumb
- learn another bitter lesson: RL not using pixels
Motivation
“Why do this? Why should I care about simpler, faster code? These tiny neural nets are way less capable than LLMs anyway!” This is what my inner Reviewer 2 would say. So let’s try to find an excuse to go down the engineering rabbit hole to make game RL as fast as possible. In the final blog post I will argue why game RL still matters in the age of LLMs. But let’s be a little bit more modest here and give arguments for 1. non-LLM RL and 2. Simplicity & Speed!
-
Even if we were sure that LLMs are THE way to AGI, doing Non-LLM RL can still inform LLM training (and hence AGI). As the modded-nanogpt competition showed, many tweaks that led to record speed training of GPT-small could be bulk copy-pasted for a record speed GPT-medium training. Especially in the age of coding agents, RL training in seconds enables large-scale algorithm search, e.g. for optimizers that beat Adam and Muon. Karpathy’s autoresearch and modded-nanogpt’s new optimization track head that way. The track’s record optimizer ANVIL2 (also FlashRL’s default) shows how: Its author let coding agents implement, but did the ideation without them, since autonomous agents mostly got stuck tuning hyperparameters.
-
Code used/published in academia is often not optimized for Simplicity & Speed, with (in my view) underrated consequences: Anyone trying to reproduce published results suffers if the code is complicated and slow. The worst thing that can happen is complicated, slow code in something that becomes THE state-of-the-art method and is therefore used by many researchers. This initial seed of bad code will accumulate technical debt that, like financial debt, compounds over time to the point that trying a simple research idea takes hours to write and days to run. Hence, rebuilding stuff from scratch once in a while is necessary to keep the iteration loop(=the engine of science) unstuck.
Simple(st) RL code
I tried my best to make the code in cookie1.py as simple as possible: click here to judge yourself.
Excluding the Env class, the core of RL fits into <100 lines of PyTorch!
Let’s start the walkthrough with these (simplified) lines at the end of cookie1.py:
env = Env(n_agents:=4096)
net = Net(env.n_obs, n_output=env.n_acts + 1, n_hidden=32)
adam = torch.optim.Adam(net.parameters(), lr=.1)
bufs = get_buffers(env, n_steps:=32)
env.reset(bufs['env_rand'][0].cpu())
for _ in range(n_epochs:=40):
rollout(env, net, bufs, n_steps)
gae(bufs)
adam.zero_grad()
backward(env, net, bufs)
adam.step()
The first 5 lines initialize
env: steps/resets multiple agentsnet: linear + relu + linearadam: optimizer updatingnetbufs: dict of tensors for rollout dataenv.reset: sets env into random state
The 5 lines in the loop almost look like supervised learning (see first code block in next chapter). Only 3 functions left to understand the core of RL:
rolloutdoes a fewenv.steps withacts predicted by thenetand writes tobufsgaedoes Generalized Advantage Estimation and writes tobufs['adv']backwardcomputesnetgradients
Each of these functions consists of only 5-15 lines of code. Go read them:
Click to see rollout, gae, backward
def rollout(env, net, bufs, n_steps=32, device=DEVICE):
act_rand = bufs['act_rand'].roll(bufs['rand_roll'])
env_rand = bufs['env_rand'].roll(bufs['rand_roll'])
for i in range(n_steps):
ram = env.ram.to(device=device)
obs = env.get_obs(ram)
with torch.no_grad(): output = net(obs)
logp = output[:, :-1].log_softmax(dim=-1)
act = (logp.exp().cumsum(1)[:, :-1] < act_rand[i, :, None]).sum(1).byte()
bufs['ram'][i] = ram
bufs['act'][i] = act
bufs['value'][i] = output[:, -1]
env.step(act.cpu(), env_rand[i].cpu())
bufs['reward'][i] = env.reward.to(device)
bufs['done'][i] = env.done.to(device)
bufs['rand_roll'] += 1
def gae(bufs, gamma=.99, lambda_=.95):
reward, done, value, adv = bufs['reward'], bufs['done'], bufs['value'], bufs['adv']
adv[-1] = reward[-1] - value[-1]
not_done = 1. - done
for t in range(len(adv) - 2, -1, -1):
delta = reward[t] + gamma * value[t + 1] * not_done[t] - value[t]
adv[t] = delta + gamma * lambda_ * not_done[t] * adv[t + 1]
def backward(env, net, bufs, entropy_coef=.01, value_coef=.5):
obs = env.get_obs(bufs['ram'].flatten(end_dim=1))
output = net(obs)
logp = output[:, :-1].view(*bufs['act'].shape, -1).log_softmax(dim=-1)
value = output[:, -1].view(*bufs['value'].shape)
adv_normed = (bufs['adv'] - bufs['adv'].mean()) / (bufs['adv'].std() + 1e-8)
policy_loss = -logp.gather(-1, bufs['act'][..., None].long())[..., 0] * adv_normed
entropy = -(logp * logp.exp()).sum(-1)
value_loss = .5 * (bufs['value'] + bufs['adv'] - value).pow(2)
loss = (policy_loss - entropy_coef * entropy + value_coef * value_loss).mean()
loss.backward()
Simplicity ✅
Let’s explain how this code works before we chase the ✅ for speed!
Why is RL harder than supervised learning?
Supervised learning (SL) in a nutshell: During SL (sentence continues here 👇)
net = Net() # the neural net
optimizer = Adam(net.parameters()) # coupled with an optimizer
for input, target in samples: # is provided with training data
prediction = net(input) # and the nets prediction
error = (target - prediction) ** 2 # is compared to the desired output.
optimizer.zero_grad() # the gradients of the net parameters
error.mean().backward() # wrt the error of the prediction,
optimizer.step() # are used to nudge the parameters
# rinse & repeat # to reduce the error iteratively
Now call it loss instead of error and associate this code with a mental image of blindly (optimizer.)stepping down a curved plane(=loss landscape) towards its valley(=optimum) based on the slope(=gradient) under your feet: Congrats, you refreshed your SL understanding!
The two main differences that make RL harder than SL are:
- We optimize reward instead of e.g. a mean squared error (MSE) loss → the learning signal is not directly differentiable (requirement for gradient descent optimizers like Adam)
- We have no idea which
actled to a high reward, while the contribution of each sample to e.g. an MSE loss is trivial
RL “solves”(=manages to learn after maaany steps) it like this:
- Increase the probability of
acts that gave a positive reward (vice versa for negative rewards) → for the few steps with nonzero reward we’ve got gradients(=direction to nudgenetparameters)! - Distribute rewards backwards over time:
acts that at some point lead to positive rewards should have their probability increased (vice versa for negative rewards) → we’ve got gradients for all steps!
Let’s take a look at the differentiable learning signal we came up with:
| Timestep | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|
| Reward | -1 | 0 | 0 | +1 | 0 |
| Return (Discounted with γ = 0.9) | -0.27 | 0.81 | 0.90 | 1.00 | 0.00 |
Weighting logp with these discounted rewards(=return) gives Karpathy’s policy gradient.
You wanna understand policy gradients deeper? (Re)read “Pong from Pixels”!
In our code we use Generalized Advantage Estimation (GAE), which incorporates value predictions into this policy gradient.
Next to the n_acts action outputs, value prediction adds one output node and adds the MSE between value and return (weighted by value_coef) to the loss:
This way we teach our net to anticipate future reward, since return is future reward!
With the concept of value prediction, we have one last thing we need to add to our vocabulary: advantage
| Timestep | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|
| Reward | -1 | 0 | 0 | +1 | 0 |
| Return (Discounted with γ = 0.9) | -0.27 | 0.81 | 0.90 | 1.00 | 0.00 |
| Value | 0.00 | 0.70 | 0.80 | 0.90 | 0.00 |
| Advantage (λ = 1) | -0.27 | +0.11 | +0.10 | +0.10 | 0.00 |
| GAE Advantage (λ = 0.95) | -0.28 | +0.10 | +0.10 | +0.10 | 0.00 |
With λ = 1, GAE advantage is just return minus value.
With λ = 0.95 it is a smoother, lower-variance version of return minus value (see the gae function above for the full definition).
One more helpful property (to understand my value_loss definition in backward): value plus adv is return!
Now you understand how to get from policy gradients to advantage actor-critic (A2C) RL!
“A2C?! Why not PPO?”
Let’s first understand what PPO would do compared to A2C by looking at a pseudo PPO training loop:
for i in range(n_epochs):
rollout(env, net, bufs, n_steps)
gae(bufs)
for batch in split(bufs, n_batches:=4):
adam.zero_grad()
backward(env, net, batch)
adam.step()
PPO splits bufs into (e.g. n_batches=4) batches, doing an optimizer step for each batch.
Nice, 4 instead of 1 step means 4x the learning, right?
No, each batch is 4x smaller, so gradients are noisier and need smaller steps(=learning rates)!
But the real issue is this: Only the first batch is on-policy(=produced by the current net)!
Since adam.step() updates the net after the first batch (but the data in bufs stays the same), the second batch holds old(=off-policy) data produced with the old, non-updated net.
This issue gets larger for each batch in an epoch: The net is drifting away from the data in bufs.
PPO mitigates this drift by clipping the net output change(=ratio of up-to-date net outputs vs. non-updated output stored in bufs) for each observation, introducing clip_coef and value_clip_coef. Yay, two more hyperparameters to fiddle with 🙈.
Imagine we did PPO but only kept the high-quality first batch update, which needs no clipping.
And to not waste 75% of bufs, we set n_batches=1.
You know what we would end up with?
A2C 🙃!
PPO reuses data because env steps used to be expensive. Spoiler: by the end of this post, they are not.
Another argument against PPO: As documented in “The 37 Implementation Details of Proximal Policy Optimization”, PPO is easy to implement wrong.
Even geohot got frustrated with RL (“RL does not work”), partly due to unsuccessful (but addictive) hyperparameter fiddling.
Besides truly on-policy gradients, A2C’s biggest win is simplicity: 4 fewer knobs to fiddle with (clip_coef, value_clip_coef, n_batches & update_epochs, the number of passes over bufs).
Sorry, I could not resist making this meme: This is me trying to find a catchy ending for this chapter!
hide animation
The RL Environment (Env)
Now that we made the code simple, the final step is to make it fast. Since we will go all the way down the rabbit hole to CUDA/PTX in this blog series, we should be very careful to carry the least amount of baggage when picking the env.
Instead of Pong (we will get there at the end), I picked an agent chasing a cookie (see GIF) as a nod to one of my favorite podcast episodes:
“Happiness is a cookie the brain bakes for itself” – Joscha Bach, 100th Lex Fridman Podcast Episode
In this 8x8 grid a perfect agent eats a cookie every 4th step on average: An average reward of 0.25 is the maximum.
Baseline Env
Here is the Python baseline of the environment:
Click to see Env class
import torch
class Env:
def __init__(self, n_agents=4096, use_pixels=False, size_x=8, size_y=8):
self.n_agents = n_agents
self.use_pixels = use_pixels
self.size_x = size_x
self.size_y = size_y
self.n_ram = 5
self.n_acts = 5
self.ram = torch.zeros((n_agents, self.n_ram), dtype=torch.int32)
self.reward = torch.zeros(n_agents)
self.done = torch.zeros(n_agents, dtype=torch.int8)
# ...some code I omitted for brevity
def reset(self, rand, idx=None):
idxs = range(len(rand)) if idx is None else [idx]
for i in idxs:
self.ram[i, 4] = 0
self.ram[i, 0] = self.size_x // 2 - 1
self.ram[i, 1] = self.size_y // 2 - 1
r = int(rand[i] * (self.size_x * self.size_y))
self.ram[i, 2] = r % self.size_x
self.ram[i, 3] = r // self.size_x
if (self.ram[i, :2] == self.ram[i, 2:4]).all():
self.ram[i, 2] -= 1
def step(self, act, rand):
for i in range(self.n_agents):
x = self.ram[i, 0]
y = self.ram[i, 1]
if (act[i] == 1): x -= 1
elif (act[i] == 2): x += 1
elif (act[i] == 3): y -= 1
elif (act[i] == 4): y += 1
won = x == self.ram[i, 2] and y == self.ram[i, 3]
off_grid = x >= self.size_x or y >= self.size_y or x < 0 or y < 0
self.done[i] = won or off_grid or self.ram[i, 4] > self.size_x
if self.done[i]:
self.reward[i] = 1 if won else -1
self.reset(rand, i)
else:
self.ram[i, 4] += 1
self.reward[i] = 0
self.ram[i, 0] = x
self.ram[i, 1] = y
Env holds the game state (ram: agent and cookie positions + timestep), reward, and done (end of a game) tensors for multiple (n_agents) agents.
Its get_obs (omitted above) turns the positions in ram into the observations (obs) the net sees.
Its whole logic is defined in reset and step.
Let’s use this baseline (by setting use_c_env = False) and run python cookie1.py:
20K steps/s | reward: 0.239: 100%|███████████| 40/40 [06:13<00:00, 9.35s/it]
Well, it learned the game (reward: 0.239 close to 0.25) but it took >6 minutes on a 5090 at only ~20K steps per second (SPS)!
This is a typical speed for RL training and the baseline we wanna improve upon.
A good quote at this point is:
“If you made something 2x faster, you might have done something smart.
If you made something 100x faster, you definitely just stopped doing something stupid.” – Fabian Giesen
So, before moving on to the next chapter: Can you point at the stupidity in the above code?
Faster CEnv
Here is the root of stupidity in the baseline:
class Env:
...
def step(self, act, rand):
for i in range(self.n_agents):
...
Aaah, of course this is slow (being in Python): We loop across n_agents(=4096 per default) in env.step()!
Experienced PyTorch/NumPy nerds avoid such loops via broadcasting.
That works for this simple step, but not for most envs.
Instead of desperately holding on to Python, we can just rewrite step and reset in C:
Click to see C implementation
typedef struct { i32 agent_x, agent_y, cookie_x, cookie_y, time; } Ram;
static void env_reset(Ram *ram, i32 size_x, i32 size_y, f32 rand) {
ram->time = 0;
ram->agent_x = size_x / 2 - 1;
ram->agent_y = size_y / 2 - 1;
i32 cell = (i32)(rand * (size_x * size_y));
ram->cookie_x = cell % size_x;
ram->cookie_y = cell / size_x;
if (ram->agent_x == ram->cookie_x && ram->agent_y == ram->cookie_y) ram->cookie_x--;
}
void reset(i32 n_agents, Ram *ram, i32 size_x, i32 size_y, f32 *rands) {
for (i32 i = 0; i < n_agents; i++)
env_reset(&ram[i], size_x, size_y, rands[i]);
}
void step(i32 n_agents, Ram *ram, i32 size_x, i32 size_y, f32 *rands,
u8 *act, f32 *reward, i8 *done) {
for (i32 i = 0; i < n_agents; i++) {
i32 x = ram[i].agent_x, y = ram[i].agent_y;
if (act[i] == 1) x--;
else if (act[i] == 2) x++;
else if (act[i] == 3) y--;
else if (act[i] == 4) y++;
i8 won = (x == ram[i].cookie_x && y == ram[i].cookie_y);
i8 off_grid = (x >= size_x || y >= size_y || x < 0 || y < 0);
done[i] = won || off_grid || ram[i].time > size_x;
if (done[i]) {
reward[i] = won ? 1 : -1;
env_reset(&ram[i], size_x, size_y, rands[i]);
} else {
reward[i] = 0;
ram[i].time++;
ram[i].agent_x = x;
ram[i].agent_y = y;
}
}
}
We can simply compile this C code from Python (calling gcc) and load the shared library via ctypes.CDLL:
Click to see CEnv class
class CEnv(Env):
def __init__(self, n_agents=4096, use_pixels=False, size_x=8, size_y=8):
super().__init__(n_agents, use_pixels, size_x, size_y)
with TemporaryDirectory() as tmp:
Path(f'{tmp}/c_lib.c').write_text(C_CODE)
check_call(f'gcc -shared -fPIC -O3 -o {tmp}/c_lib.so {tmp}/c_lib.c', shell=True)
self.c_lib = CDLL(f'{tmp}/c_lib.so')
self.c_lib.reset.argtypes = [c_int32, c_void_p,
c_int32, c_int32, c_void_p]
self.c_lib.step.argtypes = [c_int32, c_void_p,
c_int32, c_int32, c_void_p,
c_void_p, c_void_p, c_void_p]
def reset(self, rand):
self.c_lib.reset(self.n_agents, self.ram.data_ptr(),
self.size_x, self.size_y, rand.data_ptr())
def step(self, act, rand):
self.c_lib.step(self.n_agents, self.ram.data_ptr(),
self.size_x, self.size_y, rand.data_ptr(),
act.data_ptr(), self.reward.data_ptr(), self.done.data_ptr())
CEnv inherits everything from Env except reset and step: it compiles the C code in a temporary directory and loads the resulting library as a CDLL (self.c_lib).
Much time is saved if simple C can just directly access and modify the PyTorch tensor data!
Let’s set use_c_env = True and run python cookie1.py:
8025K steps/s | reward: 0.249: 100%|███████████| 40/40 [00:01<00:00, 34.99it/s]
Wow, it trained in a second with 8 million steps per second compared to the baseline…
20K steps/s | reward: 0.239: 100%|███████████| 40/40 [06:13<00:00, 9.35s/it]
…20 thousand steps per second: ~400x faster!
Conclusion
Key takeaway: Move the env next to the net. Python loops starve the GPU, while C writing straight into PyTorch tensors keeps it fed.
The CEnv plus the <100 lines in cookie1.py (excluding the Env class) is the prototype of FlashRL’s torch backend.
It trains at millions of steps per second while the RL algorithm stays easy to tinker with (in flashrl/main.py: <100 lines of code).
If you are eager to learn how the flash backend of FlashRL works, see you in the next post where we prepare the jump from PyTorch to CUDA!
Another Bitter Lesson: Not Using Pixels
The attentive reader might notice that obs does not hold pixel values but 2D coordinates, which makes the learning task way easier (John Carmack called it cheating).
Hand-crafted inputs instead of pixels: Sutton would call it bitter, RL does it all the time, and outside of RL hardly anyone notices.
OpenAI Five (OpenAI’s Dota 2 AI) and AlphaStar (DeepMind’s StarCraft II AI) did not learn from pixels either.
There are good reasons not to train on pixels (more in the final post), but you can choose for yourself:
Set use_pixels=True in cookie1.py (or any script of this series) to train on pixels in the spirit of “Pong from Pixels”.
For our agent-chasing-cookie env (see GIF) the pixel values are 1 for the agent 🪱 and 2 for the cookie 🍪 (else 0) with size_x×size_y(=64 per default) total pixels (go increase size_x and size_y for more pixels).