Road to FlashRL, Part 2

In Part 1 we made our PyTorch-based RL training script cookie1.py ~400x faster by rewriting the environment (agent chasing a cookie) in <100 lines of C.

In this post we will gently remove PyTorch to prepare ourselves for another speedup in the next blog post (CUDA incoming 🤓):

  • First, we rewrite cookie1.py without using PyTorch’s autograd, similar to Karpathy’s ~130 lines of NumPy “Pong from Pixels” (the spirit animal of this blog series). The resulting cookie2.py will help us fully understand what happens during…
    • the forward pass
    • the backward pass
    • the optimizer step
  • Second, we use our gained understanding for a full rewrite in C in cookie2.c

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).

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 post we continue to speed up RL training and

  • motivate why
    • PyTorch is great…
    • …but has a hidden cost
  • ditch PyTorch autograd (rewrite the code as if only NumPy existed)
    • understand weight initialization
    • calculate the gradients (hard part)
    • see how simple Adam is
  • rewrite in one standalone C file
    • be amazed by the non-GPU speed

Motivation: Why throw away PyTorch?

First of all: PyTorch is great!

It keeps the convenient NumPy syntax while enabling easy gradient calculation via .backward(). Also, in contrast to TensorFlow 1, it runs in eager mode by default, so calculations start instantly (no session.run() needed). Hence PyTorch is THE package to quickly test out new research ideas.

However, this convenience comes with an often overlooked cost: Opaqueness!

pip install torch results in a >1 GB download due to the millions of lines of code that stand between your little research script and the hardware. As long as the research script does stuff that stays within the box of things that PyTorch is optimized for, everything works great, but: Successful research often happens outside the box!

The PyTorch baseline Env and the ~400x faster CEnv from the first blog post are a perfect example of PyTorch’s opaqueness cost: Inside the convenient Python/PyTorch box, detached from the hardware, it is easy to not know how slow the PyTorch Env (or an Atari ROM wrapped in Python) is compared to what the hardware could do. Knowing the speed of C(=hardware-native language) and the fact that PyTorch tensors are just memory buffers(=easily accessible in C) helped us to make our research script much faster.

So, there are performance gaps in PyTorch that are often misinterpreted as limits of the hardware. But maybe our cookie1.py script is already at the limit of the hardware—how do we know? Well, let’s set use_c_env = True and run it via python cookie1.py:

8025K steps/s | reward: 0.249: 100%|███████████| 40/40 [00:01<00:00, 34.99it/s]

Now let’s uncomment the DEVICE = 'cpu' line (avoiding the GPU) and run it again:

3508K steps/s | reward: 0.248: 100%|███████████| 40/40 [00:00<00:00, 44.33it/s]

Using only the CPU we are still getting almost half the speed 🤔. Looking at the theoretical possible floating-point operations per second (FLOPS) of the hardware I am using…

  • RTX 5090 GPU: 420 TFLOPS (FP16)
  • AMD 5950X CPU: 2 TFLOPS (FP32)

…we see that the GPU should be ~200x instead of only ~2x faster than the CPU: We are constrained by PyTorch!

There is a ~100x speedup on the table by rewriting cookie1.py in a GPU-native language!

Let’s start the journey to CUDA with a warmup in no-autograd PyTorch(=cookie2.py) followed by C(=cookie2.c).

cookie2.py: No Autograd

cookie2.py is the whole rewrite of cookie1.py. The tests that we will use later to be absolutely sure that C/CUDA and PyTorch do the same math live in test/.

Instead of torch.nn.Module (used in Net), .backward and torch.optim.Adam, cookie2.py uses

  • MyNet: Calculates the forward pass using simple tensors as weights and biases instead of torch.nn.Linear
  • my_backward: Calculates the gradients(=backward pass) for MyNet
  • MyAdam: Does the adam.step() for MyNet

Don’t panic, this is not rocket science: All 3 of them together are ~50 lines of code.

MyNet

class MyNet:
    def __init__(self, n_input, n_output, n_hidden, device=DEVICE):
        with torch.device(device):
            self.w0 = n_input **-.5 * (torch.rand(n_input, n_hidden) * 2 - 1)
            self.b0 = n_input **-.5 * (torch.rand(n_hidden) * 2 - 1)
            self.w1 = n_hidden**-.5 * (torch.rand(n_hidden, n_output) * 2 - 1)
            self.b1 = n_hidden**-.5 * (torch.rand(n_output) * 2 - 1)

    def parameters(self):
        return [self.w0, self.b0, self.w1, self.b1]

    def __call__(self, x):
        hidden = (x @ self.w0 + self.b0).relu()
        return hidden @ self.w1 + self.b1

MyNet is quite simple: Just a class holding weights (w0 & w1) and biases (b0 & b1) as tensors.

The initial values of these tensors are simply uniform random numbers between $\frac{-1}{\sqrt{n}}$ and $\frac{1}{\sqrt{n}}$ with $n$ being the number of inputs (the default of torch.nn.Linear).

The forward pass in __call__ is just

  1. input times weight plus bias activated via .relu()(=hidden)
  2. hidden times weight plus bias(=output)

So simple you might have gotten bored: Let’s do some math to wake you up!

my_backward

def my_backward(env, net, bufs, entropy_coef=.01, value_coef=.5, device=DEVICE):
    n_steps, n_agents = bufs['act'].shape
    bs = n_steps * n_agents
    obs = env.get_obs(bufs['ram'].view(bs, -1))
    hidden = (obs @ net.w0 + net.b0).relu()
    output = hidden @ net.w1 + net.b1
    logp = output[:, :-1].log_softmax(dim=-1)
    p = logp.exp()
    act = bufs['act'].view(bs).long()
    adv = bufs['adv'].view(bs)
    adv_normed = (adv - adv.mean()) / (adv.std() + 1e-8)
    entropy = -(logp * p).sum(-1)
    dpolicy = -adv_normed[:, None] * (torch.eye(env.n_acts, device=device)[act] - p)
    dentropy = -entropy_coef * p * (logp + entropy[:, None])
    dvalue = -value_coef * adv
    doutput = torch.cat([dpolicy - dentropy, dvalue[:, None]], dim=1) / bs
    db1 = doutput.sum(0)
    dw1 = hidden.T @ doutput
    dh = doutput @ net.w1.T * (hidden > 0)
    db0 = dh.sum(0)
    dw0 = obs.T @ dh
    net.w0.grad, net.b0.grad, net.w1.grad, net.b1.grad = dw0, db0, dw1, db1

my_backward starts by repeating the forward pass of MyNet.__call__ because the backward pass needs the intermediate hidden activations (not just the output). The rest of the function — the last 11 lines — does by hand what loss.backward() did for us in cookie1.py: it calculates the gradients of the loss $L$

\[\mathcal{L}(z) = \underbrace{- \hat{A} \log \pi(a|z)}_{\text{Policy Loss }L_{\pi}} - c_E \underbrace{\left(-\sum_{i=1}^{K} \pi(i|z) \log \pi(i|z) \right)}_{\text{Entropy }L_E} + c_V \underbrace{\frac{1}{2} (\overbrace{V_{old} + A}^{\text{Return}} - V(z))^2}_{\text{Value Loss }L_V}\]

with $A$ being the advantage ($\hat{A}$=normalized advantage), $\pi$ being the predicted probabilities, $a$ being the taken act, $K$ being the number of possible acts (called n_acts in the code), $V$ being the value and $z$ being the raw output logits of the net.

Before we start doing math: Why is dvalue simply -value_coef * adv, i.e., why does the value loss shrink to .5 * adv**2 when it was .5 * (bufs['value'] + bufs['adv'] - value).pow(2) in cookie1.py?

  • We use A2C (see Part 1, “A2C?! Why not PPO?”) so the net parameters did not change between the rollout and my_backward: bufs['value'] is equal to value, canceling each other out!
  • Before you say “Why did you use the longer expression in cookie1.py then, idiot?!” just try it yourself: Autograd needs it 😉!

Let’s begin the calculation of the loss gradients wrt the raw logit vector $z$(=net output), starting with the value loss:

\[\begin{aligned} \nabla_z L_V &= \nabla_z \left( \frac{1}{2} (V_{old} + A - V(z))^2 \right) \\ &= \frac{2}{2} (V_{old} + A - V(z)) \cdot \nabla_z(V_{old} + A - V(z)) \\ &= (V_{old} + A - V(z)) \cdot (-\nabla_z V(z)) \\ &\overset{\mathclap{\nabla_z V(z) = 1}}{=} -(V_{old} + A - V(z)) \\ &\overset{\mathclap{V(z) = V_{old}}}{=} -A \end{aligned}\]

Hint: If you do not understand what happens in the first step google “chain rule” (and “product rule” while you’re at it—could be useful for the entropy gradient 😉)

In the loss, $L_V$ is scaled by $c_V$(=value_coef), so its gradient is scaled too:

dvalue = -value_coef * adv

Next, the gradient of the policy loss…

\[\begin{aligned} \nabla_z L_{\pi} &= \nabla_z \left( -\hat{A} \log \pi(a|z) \right) \\ &= -\hat{A} \nabla_z \log \left( \frac{e^{z_a}}{\sum_{j=1}^K e^{z_j}} \right) \\ &= -\hat{A} \nabla_z \left( z_a - \log \sum_{j=1}^K e^{z_j} \right) \\ &= -\hat{A} \left( \nabla_z z_a - \frac{1}{\sum_{j=1}^K e^{z_j}} \nabla_z \sum_{j=1}^K e^{z_j} \right) \\ &\overset{\mathclap{\nabla_z z_a = \mathbf{1}_a}}{=} -\hat{A} \left( \mathbf{1}_a - \frac{e^z}{\sum_{j=1}^K e^{z_j}} \right) \\ &= -\hat{A} (\mathbf{1}_a - \pi(z)) \end{aligned}\]

…which becomes the following line with $\mathbf{1}_a$ being the one-hot vector of the taken act (row act of the identity matrix torch.eye) and $\pi(z)$ being p:

dpolicy = -adv_normed[:, None] * (torch.eye(env.n_acts, device=device)[act] - p)

…and finally the gradient of the entropy $H$(=$L_E$=entropy):

\[\begin{aligned} \nabla_{z_k} L_E &= \nabla_{z_k} \left( -\sum_{i=1}^K \pi_i \log \pi_i \right) \\ &= -\sum_{i=1}^K \left( (\nabla_{z_k} \pi_i) \log \pi_i + \pi_i \nabla_{z_k} \log \pi_i \right) \\ &= -\sum_{i=1}^K \left( (\nabla_{z_k} \pi_i) \log \pi_i + \pi_i \frac{1}{\pi_i} \nabla_{z_k} \pi_i \right) \\ &= -\sum_{i=1}^K (\nabla_{z_k} \pi_i) (\log \pi_i + 1) \\ &\overset{\mathclap{\nabla_{z_k} \pi_i = \pi_i (\mathbf{1}_{i=k} - \pi_k)}}{=} -\sum_{i=1}^K \pi_i (\mathbf{1}_{i=k} - \pi_k) (\log \pi_i + 1) \\ &= -\left[ \sum_{i=1}^K \pi_i \mathbf{1}_{i=k} (\log \pi_i + 1) - \pi_k \sum_{i=1}^K \pi_i (\log \pi_i + 1) \right] \\ &= -\left[ \pi_k (\log \pi_k + 1) - \pi_k \left( \sum_{i=1}^K \pi_i \log \pi_i + \sum_{i=1}^K \pi_i \right) \right] \\ &\overset{\mathclap{\sum \pi_i \log \pi_i = -H \text{ and } \sum \pi_i = 1}}{=} -\Big[ \pi_k \log \pi_k + \pi_k - \pi_k (-H + 1) \Big] \\ &= -[ \pi_k \log \pi_k + \pi_k + \pi_k H - \pi_k ] \\ &= -\pi_k (\log \pi_k + H) \end{aligned}\]

Hint: If you are wondering where $\nabla_{z_k} \pi_i = \pi_i (\mathbf{1}_{i=k} - \pi_k)$ comes from, it’s the standard Jacobian of the softmax function!

Just like $L_V$, the entropy is scaled by its coefficient $c_E$(=entropy_coef):

dentropy = -entropy_coef * p * (logp + entropy[:, None])

The value gradient applies only to net parameters feeding into the net’s value output node (where $\nabla_z V(z) = 1$). Conversely, the gradients of the policy loss and entropy apply only to the act output nodes (where $\nabla_z V(z) = 0$). Following the signs in the loss ($L_\pi - c_E L_E + c_V L_V$), the gradient wrt the whole net output is the concatenation of dpolicy - dentropy and dvalue:

doutput = torch.cat([dpolicy - dentropy, dvalue[:, None]], dim=1) / bs

The / bs (with bs being the batch size) is there because we minimize the mean loss across the batch (loss.mean() in cookie1.py): Each of the bs samples contributes with a factor of 1 / bs to the gradient.

We need to propagate doutput backwards through the net (using the chain rule) starting with the biases of the last layer b1:

\[\frac{\partial \mathcal{L}}{\partial b_1} = \frac{\partial \mathcal{L}}{\partial z}\]

The chain rule tells us that the gradient wrt b1 is simply doutput. Summing doutput across the batch dimension gives us db1 = doutput.sum(0) (the / bs in doutput makes this sum the average gradient used for the optimizer step).

Let’s continue with the weights of the last layer w1:

\[\frac{\partial \mathcal{L}}{\partial W_1} = h^T \cdot \frac{\partial \mathcal{L}}{\partial z}\]

The chain rule tells us that the gradient wrt w1 is the transposed hidden tensor matrix multiplied with doutput: hidden.T @ doutput. The transpose swaps the hidden dimensions so that the inner sum of the matrix multiplication (yes, matrix multiplications are just weighted sums) sums across the batch dimension, just like .sum(0) did for the bias gradient.

To calculate the gradients of the first layer (dw0 & db0), we first need to know how the hidden layer contributed to the loss (just like we needed doutput to calculate dw1 & db1):

\[\frac{\partial \mathcal{L}}{\partial h} = \frac{\partial \mathcal{L}}{\partial z} \cdot W_1^T\]

Based on the chain rule, we backpropagate doutput through the last layer by matrix multiplication with $W_1^T$ to arrive at the post-activation hidden layer gradient doutput @ net.w1.T.

Multiplying it by (hidden > 0) gives us the pre-activation gradient dh = doutput @ net.w1.T * (hidden > 0): All hidden nodes that inputted non-positive values into the ReLU activation did not contribute to the loss. Or in terms of the chain rule: We multiply by 1 (derivative of ReLU for positive input values) for hidden > 0, and multiply by 0 otherwise (derivative of ReLU for non-positive input values).

Finally, the first layer’s gradients are calculated like the last layer’s using

  • dh instead of doutput
  • obs instead of hidden

resulting in:

db0 = dh.sum(0)
dw0 = obs.T @ dh

Nice, all gradients ([dw0, db0, dw1, db1]) are stored in the .grad of their parameter (just like loss.backward() does it) and are ready to be used by MyAdam to nudge the net parameters in a direction that reduces the loss.

If you really followed this, here have a cookie: 🍪

MyAdam

class MyAdam:
    def __init__(self, params, lr, betas=(.9, .999), eps=1e-8):
        self.params = params
        self.m = [torch.zeros_like(p) for p in params]
        self.v = [torch.zeros_like(p) for p in params]
        self.lr = lr
        self.betas = betas
        self.eps = eps
        self.t = 0

    def step(self):
        self.t += 1
        bc1 = 1 - self.betas[0] ** self.t
        bc2 = 1 - self.betas[1] ** self.t
        for i, p in enumerate(self.params):
            self.m[i].lerp_(p.grad, 1 - self.betas[0])
            self.v[i].lerp_(p.grad**2, 1 - self.betas[1])
            p.data -= self.lr * self.m[i] / bc1 / ((self.v[i] / bc2).sqrt() + self.eps)

Adam (Adaptive Moment Estimation) simply keeps track of two moving averages for each parameter: The respective gradients’ mean m (first moment) and uncentered variance v (second moment).

In the first blog we already used the following analogy to get an intuition for supervised learning: “…blindly stepping down a curved plane(=loss landscape) towards its valley(=optimum) based on the slope(=gradient) under your feet.” Using this analogy:

  • The first moment m carries you in the recently travelled direction even if you encounter tiny bumps with slopes that would send you in another direction if you only looked at the slope of your current step.
  • The second moment v measures the “roughness” of the recently encountered terrain and adapts the step size accordingly: Smaller steps in rougher terrain.

Since m and v start at zero, they are too small during the first steps. The bias corrections bc1 & bc2 scale them up, avoiding too-large parameter updates.

train & test

The train code at the end of cookie2.py is almost a copy of the ~20 lines at the end of cookie1.py but uses MyNet, my_backward and MyAdam (and the fast CEnv of course).

Running cookie1.py with use_c_env = True we get:

8025K steps/s | reward: 0.249: 100%|███████████| 40/40 [00:01<00:00, 34.99it/s]

Running cookie2.py we get:

8.5M steps/s | reward: 0.248: 100%|███████████| 40/40 [00:00<00:00, 40.99it/s]

Ok, same speed but the final reward is a bit lower… do we have a bug in cookie2.py or is it numerical imprecisions compounded during training?

To answer that question we define a test function in test/test_cookie2.py. It prints…

TEST 1: Rollout
  ram mismatches: 0.00%
  act mismatches: 0.00%
  reward mismatches: 0.00%
  done mismatches: 0.00%
  value median error: 0e+00
TEST 2: Backward
  w0 rel error: 5e-06
  b0 rel error: 4e-08
  w1 rel error: 4e-07
  b1 rel error: 4e-09
TEST 3: Adam (2 steps)
  w0 step rel error: 0e+00
  b0 step rel error: 0e+00
  w1 step rel error: 0e+00
  b1 step rel error: 0e+00

…showing that given the same net parameters and the same randomness (bufs['env_rand'] & bufs['act_rand']):

  • MyNet and Net produce matching bufs in rollout
  • my_backward and backward produce almost matching gradients (relative error of almost 0)
  • MyAdam and Adam produce almost matching parameter updates over two steps (relative error of almost 0)

That’s pretty good 🎉

To be sure that we did not hardcode some values in there, we can run 4 different configurations…

CONFIGS = {'default':  dict(n_steps=32, n_hidden=32, use_pixels=False),
           'pixels':   dict(n_steps=32, n_hidden=32, use_pixels=True),
           'steps16':  dict(n_steps=16, n_hidden=32, use_pixels=False),
           'hidden64': dict(n_steps=32, n_hidden=64, use_pixels=False)}

…either all in one go via python test/test_cookie2.py all or one certain config via e.g. python test/test_cookie2.py pixels.

Finally, the test function also saves all the PyTorch reference data as binary files. This setup saves us much headache in the coming rewrites: Instead of guessing why our C/CUDA code does not get the same reward, we can pinpoint the mismatches!

cookie2.c: No PyTorch

The whole rewrite of cookie1.py occupies ~300 lines in cookie2.c (its tests are in test/test_cookie2.c).

Let’s quickly explain things that a Python-only dev might stumble upon before we run it!

In contrast to Python, the user has to compile the C code before running it. Values that are defined like this #define N_HIDDEN 32 are searched-and-replaced (replacing N_HIDDEN with 32) before compilation such that the compiled machine code can be optimized for these values. This is a tradeoff: It can give a speedup for the defined value but changing it requires recompilation!

Also, we don’t have tensors with multiple dimensions in C. Our Net is simply a structure(=struct: basically a stripped-down class) of four pointers(=four memory addresses) to the four 1D f32(32-bit) float arrays: Weights w, biases b, and their respective gradients dw and db.

typedef struct { f32 *w, *b, *dw, *db; } Net;  // b and db sit right behind w and dw in memory

Similar to MyNet’s class attributes (w0, b0, w1, b1) in cookie2.py, dot notation and brackets are used to access a value (e.g. net.b[0]).

In C there are no operators for matrix multiplication ...@ self.w0 or vector addition ...+ self.b0. Instead we loop over the values in the flat arrays using the pointers(=memory start addresses) of these arrays. This is what it looks like:

static void layer_forward(f32 *w, f32 *b, f32 *input, f32 *output, i32 n_input, i32 n_output) {
    for (i32 i = 0; i < n_output; i++) {
        output[i] = b[i];
        for (i32 j = 0; j < n_input; j++) output[i] += input[j] * w[i * n_input + j];
    }
}

The “matrix structure” of the flat 1D weight array is enforced entirely by the index i * n_input + j.

You might ask “Why not have separate w0, b0, w1 and b1 to be closer to the Python code?”. Well, b is allocated directly behind w (and db behind dw), so net.w is also one flat array of all NET_SIZE parameters, and adam_step loops over it in a single for-loop:

void adam_step(Adam adam, Net net) {
    f32 bc1 = 1 - pow(adam.beta1, adam.t);
    f32 bc2 = 1 - pow(adam.beta2, adam.t);
    for (i32 i = 0; i < NET_SIZE; i++) {
        f32 grad = net.dw[i];
        adam.m[i] = adam.beta1 * adam.m[i] + (1 - adam.beta1) * grad;
        adam.v[i] = adam.beta2 * adam.v[i] + (1 - adam.beta2) * grad * grad;
        f32 m_hat = adam.m[i] / bc1;
        f32 v_hat = adam.v[i] / bc2;
        f32 update = adam.lr * m_hat / (sqrtf(v_hat) + adam.eps);
        net.w[i] -= update;
        net.dw[i] = 0.f;
    }
}

Quite readable, right? And, in contrast to everything we wrote in PyTorch, this code is very close to the hardware (no hidden opaqueness cost!).

Finally, in C we do have to allocate memory before we can use it. For example, to create an instance of the Env struct one can just pass n_agents (an i32: a 32-bit signed integer) to the respective struct field but must allocate memory (via calloc) that the ram struct pointer field can point to.

Env env = {.n_agents=n_agents,
           .ram =(Ram *)calloc(n_agents, sizeof(Ram))};

Since the program ends right after training, we don’t free that memory: the operating system reclaims all memory of a process when it exits.

train & test

To give our CPU the best fighting chance, we gcc compile with -O3 high optimization -march=native specific to our CPU (AMD Ryzen 9 5950X) and -ffast-math enabled:

gcc -O3 -march=native -ffast-math cookie2.c -o cookie2 -lm

Running it via ./cookie2 results in:

4.6M steps/s | reward: 0.248: 100%|##########| 40/40

4.6 Million steps per second: ~30% faster than using cookie1.py with DEVICE = 'cpu'. You might say…

Dyatlov from Chernobyl: "4.6 MILLION STEPS PER SECOND" - "NOT GREAT, NOT TERRIBLE."

…but wait!

cookie2.c does only use one CPU core while cookie1.py uses all 16 cores. So, if we rewrote cookie2.c to use all 16 cores, the speedup could be up to ~1.3×16≈20x…that’s pretty good!

We will not go into that rabbit hole…

If you wanna do it yourself, I cannot stop you 🐇

…and call it a day after checking if the tests in test/test_cookie2.c look good:

TEST 1: Rollout + GAE
  ram mismatches: 0.00%
  act mismatches: 0.00%
  reward mismatches: 0.00%
  done mismatches: 0.00%
  value median error: 7e-09
  adv median error: 0e+00
TEST 2: Backward
  dw0 rel error: 1e-06
  db0 rel error: 5e-06
  dw1 rel error: 4e-07
  db1 rel error: 1e-05
TEST 3: Adam (2 steps)
  w0 step rel error: 2e-06
  b0 step rel error: 2e-06
  w1 step rel error: 2e-06
  b1 step rel error: 1e-06

Nice, within numerical bounds cookie2.c does the same math as the PyTorch reference in cookie2.py ✅

Conclusion

In this blog post we prepared the CUDA rewrite that will follow in the next post by

  1. rewriting cookie1.py without PyTorch autograd (in cookie2.py) by replacing
    • Net with MyNet
    • .backward with my_backward
    • Adam with MyAdam
  2. translating cookie2.py into pure C (in cookie2.c)

Congrats if you read the whole thing, especially if you followed the my_backward chapter (most mathy we will get in this series of blog posts, I promise ✌️).

In Part 3, we will write our very first CUDA kernels to unlock the GPU. 🤓


<
Previous Post
RL in 100 Lines of PyTorch
>
Blog Archive
Archive of all previous blog posts