<?xml version="1.0" encoding="UTF-8"?>
<rss  xmlns:atom="http://www.w3.org/2005/Atom" 
      xmlns:media="http://search.yahoo.com/mrss/" 
      xmlns:content="http://purl.org/rss/1.0/modules/content/" 
      xmlns:dc="http://purl.org/dc/elements/1.1/" 
      version="2.0">
<channel>
<title>Sairam Satwik Kondamudi</title>
<link>https://7wik.github.io/posts.html</link>
<atom:link href="https://7wik.github.io/posts.xml" rel="self" type="application/rss+xml"/>
<description>Notes on ML and reinforcement learning, mostly written while building things from scratch.</description>
<generator>quarto-1.11.9</generator>
<lastBuildDate>Tue, 01 Dec 2026 00:00:00 GMT</lastBuildDate>
<item>
  <title>DQN from first principles</title>
  <link>https://7wik.github.io/posts/dqn-first-principles/</link>
  <description><![CDATA[ 






<p>I’ve been reimplementing RL algorithms from scratch, roughly in the order of Sutton and Barto, on the way to the methods used for LLM post-training (PPO, GRPO and friends). This post is about DQN on CartPole: first in PyTorch, then again by hand in numpy. The numpy version scored worse than a random policy before it worked, and the way it got there taught me more than the version that worked first try.</p>
<section id="what-dqn-is" class="level2">
<h2 class="anchored" data-anchor-id="what-dqn-is">What DQN is</h2>
<p>DQN starts from tabular Q-learning. You keep a table of <img src="https://latex.codecogs.com/png.latex?Q(s,a)">, the expected return of taking action <img src="https://latex.codecogs.com/png.latex?a"> in state <img src="https://latex.codecogs.com/png.latex?s"> and acting well afterwards, and nudge each entry toward a one-step target:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0AQ(s,a)%20%5Cleftarrow%20Q(s,a)%20+%20%5Calpha%5C,%5Cbig%5B%5C,r%20+%20%5Cgamma%20%5Cmax_%7Ba'%7D%20Q(s',a')%20-%20Q(s,a)%5C,%5Cbig%5D%0A"></p>
<p>CartPole’s state is four continuous numbers (cart position and velocity, pole angle and angular velocity), so there is no table to keep. Instead, a neural network takes the state and outputs one Q value per action, and we train it by regression: push <img src="https://latex.codecogs.com/png.latex?Q(s,a)"> toward <img src="https://latex.codecogs.com/png.latex?y%20=%20r%20+%20%5Cgamma%20%5Cmax_%7Ba'%7D%20Q(s',a')">.</p>
<p>Done naively this is unstable, for two reasons, and DQN (Mnih et al., 2015) adds one fix for each. Consecutive transitions are strongly correlated, so transitions go into a <strong>replay buffer</strong> and training uses random batches from it. And the target <img src="https://latex.codecogs.com/png.latex?y"> is computed by the same network you are updating, so every step moves the goalposts. DQN computes <img src="https://latex.codecogs.com/png.latex?y"> with a <strong>target network</strong>, a frozen copy of the weights that gets re-synced every N steps.</p>
<p>Two smaller details matter in practice. The agent explores with ε-greedy, where ε decays from 1 to 0.05 over the first 10k steps. And when an episode ends because of CartPole’s 500-step time limit, the pole hasn’t actually fallen, so the target should still bootstrap from <img src="https://latex.codecogs.com/png.latex?s'">. The buffer stores <code>terminated</code>, not <code>done</code>.</p>
<div class="cell" data-layout-align="default">
<div class="cell-output-display">
<div>
<p></p><figure class="figure"><p></p>
<div>

<pre class="mermaid mermaid-js">flowchart LR
    E[CartPole] -- "s" --&gt; A["ε-greedy&lt;br/&gt;argmax Q(s, ·)"]
    A -- "a" --&gt; E
    E -- "(s, a, r, s', terminated)" --&gt; B[(replay buffer)]
    B -- "batch of 64" --&gt; L["loss = mean (Q(s,a) − y)²"]
    T["target net&lt;br/&gt;y = r + γ max Q⁻(s', ·)"] --&gt; L
    L -- "gradient" --&gt; N[Q-network]
    N -. "copy every 100 steps" .-&gt; T
</pre>
</div>
<p></p></figure><p></p>
</div>
</div>
</div>
</section>
<section id="first-pass-torch" class="level2">
<h2 class="anchored" data-anchor-id="first-pass-torch">First pass: torch</h2>
<p>I built it in PyTorch first: <a href="https://github.com/7wik/RL-basics/blob/main/src/rl_basics/dqn.py"><code>dqn.py</code></a>, with a three-layer MLP of 128 hidden units (<a href="https://github.com/7wik/RL-basics/blob/main/src/rl_basics/dqn.py#L25-L37">lines 25–37</a>). It learned. With the target network re-synced every 100 steps, the last-20-episode average was about 420 over two seeds (every 500 steps only got about 155). The <a href="https://github.com/7wik/RL-basics/blob/main/experiments/03_dqn.ipynb">notebook</a> has a side-by-side animation of a random policy and the trained one.</p>
<p>To be honest, though, I had editor autocomplete on, it filled in a lot, and autograd did the rest. It worked, but I couldn’t have told you what the gradient of the TD loss actually was.</p>
<p>The whole learning step, with autograd doing the hard part:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1">q_values_next <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> target_net(next_obs_batch).<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">max</span>(dim<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]</span>
<span id="cb1-2">targets <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> rewards_batch <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> gamma <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> q_values_next <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> terminated_batch)</span>
<span id="cb1-3">q_values_current <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> q_net(obs_batch).gather(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, actions_batch.unsqueeze(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)).squeeze(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb1-4">loss <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> criterion(q_values_current, targets.detach())</span>
<span id="cb1-5">loss.backward()</span></code></pre></div></div>
</section>
<section id="second-pass-by-hand-in-numpy" class="level2">
<h2 class="anchored" data-anchor-id="second-pass-by-hand-in-numpy">Second pass: by hand in numpy</h2>
<p>So I wrote it again in numpy: <a href="https://github.com/7wik/RL-basics/blob/main/src/rl_basics/dqn_np.py"><code>dqn_np.py</code></a>. The principles are the same: replay buffer, target network, ε-greedy, same TD target. This time the forward pass, the backward pass and the parameter update are mine.</p>
<p>I kept the first design deliberately small, just to check that the plumbing worked: <strong>two linear layers, no biases, a ReLU in between, and plain SGD.</strong> I remember wondering whether I even needed the biases and deciding I didn’t. Keep that in mind.</p>
<p>The part I found most interesting is the gradient of the loss with respect to the network’s outputs. The network outputs a Q value for both actions, but each transition only tells you about the action that was actually taken. So <code>dQ</code> is zero in the other column. The other action’s value still changes, through the shared hidden layer, just not directly.</p>
<div class="cell" data-layout-align="default">
<div class="cell-output-display">
<div>
<p></p><figure class="figure"><p></p>
<div>

<pre class="mermaid mermaid-js">flowchart LR
    X["s&lt;br/&gt;(4)"] -- "W1 (4×128)" --&gt; H["ReLU&lt;br/&gt;(128)"]
    H -- "W2 (128×2)" --&gt; Q["Q(s, left)&lt;br/&gt;Q(s, right)"]
</pre>
</div>
<p></p></figure><p></p>
</div>
</div>
</div>
<p>The first version:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> q_forward(net, X):</span>
<span id="cb2-2">    h <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.maximum(X <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">@</span> net[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"W1"</span>], <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb2-3">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> h <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">@</span> net[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"W2"</span>], h</span>
<span id="cb2-4"></span>
<span id="cb2-5"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> td_loss_grad(Q, actions, targets):</span>
<span id="cb2-6">    n <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(Q)</span>
<span id="cb2-7">    diff <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Q[np.arange(n), actions] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> targets</span>
<span id="cb2-8">    dQ <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.zeros_like(Q)</span>
<span id="cb2-9">    dQ[np.arange(n), actions] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> diff <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> n      <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># only the action that was taken</span></span>
<span id="cb2-10">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> np.mean(diff <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>), dQ</span>
<span id="cb2-11"></span>
<span id="cb2-12"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> q_backward(net, h, X, dQ):</span>
<span id="cb2-13">    dh <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> dQ <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">@</span> net[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"W2"</span>].T</span>
<span id="cb2-14">    dh[h <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>                                 <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># ReLU</span></span>
<span id="cb2-15">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> {<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"W1"</span>: X.T <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">@</span> dh, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"W2"</span>: h.T <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">@</span> dQ}</span>
<span id="cb2-16"></span>
<span id="cb2-17"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># in the training loop</span></span>
<span id="cb2-18"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> k <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> net:</span>
<span id="cb2-19">    net[k] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-=</span> lr <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> grads[k]                        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># SGD</span></span>
<span id="cb2-20">eps_diff <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (eps_end <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> eps_start) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> eps_decay_steps</span>
<span id="cb2-21">eps <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">max</span>(eps <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> eps_diff, eps_end)                 <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># linear ε decay</span></span></code></pre></div></div>
<p>The gradient check (finite differences against <code>q_backward</code>) passed, so I ran it.</p>
<div id="setup" class="cell" data-execution_count="1">
<details class="code-fold">
<summary>experiment harness: my train_dqn, with switches to put each bug back</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> warnings</span>
<span id="cb3-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> numpy <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> np, gymnasium <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> gym, matplotlib.pyplot <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> plt</span>
<span id="cb3-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> rl_basics.dqn_np <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> dqn</span>
<span id="cb3-4"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> rl_basics.optim <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> Adam</span>
<span id="cb3-5">warnings.simplefilter(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ignore"</span>)</span>
<span id="cb3-6"></span>
<span id="cb3-7"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> SGD:</span>
<span id="cb3-8">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, params, lr): <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.lr <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> lr</span>
<span id="cb3-9">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> step(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, params, grads):</span>
<span id="cb3-10">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> k <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> grads: params[k] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.lr <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> grads[k]</span>
<span id="cb3-11"></span>
<span id="cb3-12">_backward, _loss <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> dqn.q_backward, dqn.td_loss_grad</span>
<span id="cb3-13"></span>
<span id="cb3-14"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> run(lr<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">5e-4</span>, seed<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, opt<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"adam"</span>, bias<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>, eps_bug<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>):</span>
<span id="cb3-15">    qmax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []</span>
<span id="cb3-16">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> loss_spy(Q, a, y):</span>
<span id="cb3-17">        qmax.append(np.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">abs</span>(Q).<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">max</span>())</span>
<span id="cb3-18">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> _loss(Q, a, y)</span>
<span id="cb3-19">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> backward(net, h, X, dQ):</span>
<span id="cb3-20">        g <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> _backward(net, h, X, dQ)</span>
<span id="cb3-21">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> bias:                      <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># biases start at 0 and never move</span></span>
<span id="cb3-22">            g[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"b1"</span>], g[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"b2"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> g[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"b1"</span>], <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> g[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"b2"</span>]</span>
<span id="cb3-23">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> g</span>
<span id="cb3-24">    dqn.Adam <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Adam <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> opt <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"adam"</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> SGD</span>
<span id="cb3-25">    dqn.q_backward, dqn.td_loss_grad <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> backward, loss_spy</span>
<span id="cb3-26">    decay <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10_000</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> eps_bug <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10_000</span>   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># the sign bug: epsilon grows instead of decaying</span></span>
<span id="cb3-27">    _, R <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> dqn.train_dqn(gym.make(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"CartPole-v1"</span>), lr<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>lr, seed<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>seed, eps_decay_steps<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>decay)</span>
<span id="cb3-28">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> np.array(R), np.array(qmax, dtype<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>)[::<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>]</span>
<span id="cb3-29"></span>
<span id="cb3-30">BLUE, ORANGE, AQUA, GREY <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#257de0"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#f47230"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#00b894"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#8a8a8a"</span></span>
<span id="cb3-31">plt.rcParams.update({</span>
<span id="cb3-32">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"figure.dpi"</span>: <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">110</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"font.size"</span>: <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"axes.spines.top"</span>: <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"axes.spines.right"</span>: <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>,</span>
<span id="cb3-33">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"axes.edgecolor"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#bbbbbb"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"axes.grid"</span>: <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"grid.color"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#ececec"</span>,</span>
<span id="cb3-34">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"axes.titlesize"</span>: <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">11</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"axes.titleweight"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bold"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"axes.titlelocation"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"left"</span>,</span>
<span id="cb3-35">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"lines.linewidth"</span>: <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.8</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"legend.frameon"</span>: <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>,</span>
<span id="cb3-36">})</span>
<span id="cb3-37"></span>
<span id="cb3-38"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> rolling(R, w<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>):</span>
<span id="cb3-39">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> np.convolve(R, np.ones(w) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> w, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"valid"</span>)</span>
<span id="cb3-40"></span>
<span id="cb3-41"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> curve(R, w<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>):</span>
<span id="cb3-42">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> np.cumsum(R)[w <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>:], rolling(R, w)</span>
<span id="cb3-43"></span>
<span id="cb3-44"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> note(ax, x, y, text):</span>
<span id="cb3-45">    ax.text(x, y, text, fontsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">8.5</span>, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#555555"</span>)</span></code></pre></div></div>
</details>
</div>
</section>
<section id="the-first-run-an-overflow-warning" class="level2">
<h2 class="anchored" data-anchor-id="the-first-run-an-overflow-warning">The first run: an overflow warning</h2>
<p>The first full run printed <code>RuntimeWarning: overflow encountered in square</code>, in the loss. My first instinct was to divide by the batch size, until I noticed I already was.</p>
<p>Printing the largest |Q| in each batch was more useful: 4, then 90, then 330, then 8,780, then nan. There is a simple sanity bound here. The reward is +1 per step and γ = 0.99, so no state can be worth more than <img src="https://latex.codecogs.com/png.latex?1/(1-%5Cgamma)%20=%20100">. Once Q goes past that, it isn’t learning values anymore, it’s feeding on its own overestimates. The overflow was a symptom. The real problem was divergence.</p>
<p>The obvious next move was a lower learning rate, so I tried three:</p>
<div id="cell-fig-eps" class="cell" data-execution_count="2">
<details class="code-fold">
<summary>code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb4-1">eps <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {lr: run(lr, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sgd"</span>, bias<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>, eps_bug<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> lr <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> [<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-4</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">5e-5</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2e-5</span>]}</span>
<span id="cb4-2"></span>
<span id="cb4-3">fig, (a, b) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.subplots(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, figsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">9</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">3.4</span>))</span>
<span id="cb4-4"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> (lr, c, ls) <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> [(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-4</span>, BLUE, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"-"</span>), (<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">5e-5</span>, ORANGE, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"--"</span>), (<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2e-5</span>, AQUA, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">":"</span>)]:</span>
<span id="cb4-5">    R, q <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> eps[lr]</span>
<span id="cb4-6">    a.plot(rolling(R), color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>c, ls<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>ls, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"lr </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>lr<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:g}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb4-7">    b.plot(np.arange(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(q)) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>, q, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>c, ls<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>ls)</span>
<span id="cb4-8">a.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">set</span>(title<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Return"</span>, xlabel<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"episode"</span>, ylabel<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"return (rolling 20)"</span>)</span>
<span id="cb4-9">b.axhline(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>GREY, lw<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, ls<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"--"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> note(b, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">170</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"max possible Q = 100"</span>)</span>
<span id="cb4-10">b.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">set</span>(title<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Max |Q| in each batch"</span>, xlabel<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"gradient update"</span>, yscale<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"log"</span>)</span>
<span id="cb4-11">a.legend(loc<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"upper right"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> fig.tight_layout()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> plt.show()</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div id="fig-eps" class="quarto-float quarto-figure quarto-figure-center anchored">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-eps-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://7wik.github.io/posts/dqn-first-principles/index_files/figure-html/fig-eps-output-1.png" width="992" height="363" class="figure-img">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-eps-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;1: Three learning rates, identical returns. Max |Q| (right) shows the networks really were different.
</figcaption>
</figure>
</div>
</div>
</div>
</section>
<section id="lowering-the-learning-rate-changed-nothing.-literally-nothing." class="level2">
<h2 class="anchored" data-anchor-id="lowering-the-learning-rate-changed-nothing.-literally-nothing.">Lowering the learning rate changed nothing. Literally nothing.</h2>
<p>The right panel says what I expected: a lower learning rate only delays the blow-up.</p>
<p>The left panel is the strange one. The three return curves are not just similar, they are <em>identical</em>: the same 2,237 episodes and the same last-20 average of 25, including the run whose network was nan for half of training. That can only happen if the network never gets to choose an action. And about 22 steps per episode is exactly what CartPole gives a random policy.</p>
<p>When a setting that should matter produces identical numbers, the setting isn’t connected to the part of the code you think it is.</p>
</section>
<section id="the-bug-ε-was-going-up" class="level2">
<h2 class="anchored" data-anchor-id="the-bug-ε-was-going-up">The bug: ε was going up</h2>
<p>Go back to the two ε lines in the first version. <code>eps_end - eps_start</code> is negative, and <code>eps - eps_diff</code> subtracts a negative number. ε started at 1.0 and went <em>up</em>, so every action was random. The network trained on the buffer, and diverged, but never drove the cart. With the same seed, the random actions and therefore the episodes were identical across runs.</p>
<p>The fix is one sign:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb5-1">eps_diff <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (eps_start <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> eps_end) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> eps_decay_steps</span></code></pre></div></div>
</section>
<section id="fixed.-now-its-worse-than-random." class="level2">
<h2 class="anchored" data-anchor-id="fixed.-now-its-worse-than-random.">Fixed. Now it’s worse than random.</h2>
<p>With ε decaying properly, the network finally acts, and the return drops to about 10 (orange in the figure below). Random gets about 22.</p>
<p>Doing worse than random is informative. It means the agent pushes the same way every time, so the greedy policy has collapsed to a single action. The Q values now stayed between 10 and 50, so this wasn’t divergence. It looked more like something the network could not represent.</p>
</section>
<section id="the-second-bug-no-biases" class="level2">
<h2 class="anchored" data-anchor-id="the-second-bug-no-biases">The second bug: no biases</h2>
<p>It was the biases. Without them, a ReLU network is positively homogeneous: <img src="https://latex.codecogs.com/png.latex?Q(c%5C,s)%20=%20c%5C,Q(s)"> for any <img src="https://latex.codecogs.com/png.latex?c%20%3E%200">, and in particular <img src="https://latex.codecogs.com/png.latex?Q(0)%20=%200">. The upright, centred state is <img src="https://latex.codecogs.com/png.latex?s%20%5Capprox%200">, which is exactly where a good agent spends its time. There, both Q values, and the difference between them, are forced toward zero, when that state should be worth close to 100.</p>
<p>Before rewriting anything, I checked this by appending a constant 1 to every observation, which is a bias in disguise, and leaving the code otherwise unchanged. The return went from 11 to between 410 and 470. Then I added real biases. That’s <code>b1</code> and <code>b2</code> in the forward pass and two lines in the backward pass, since a bias gradient is just the upstream gradient summed over the batch.</p>
<p>The torch version never had this problem because <code>nn.Linear</code> includes a bias by default. Writing it by hand, I had removed something the framework had been quietly giving me.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb6-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> q_forward(net, X):</span>
<span id="cb6-2">    h <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.maximum(X <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">@</span> net[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"W1"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> net[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"b1"</span>], <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb6-3">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> h <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">@</span> net[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"W2"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> net[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"b2"</span>], h</span>
<span id="cb6-4"></span>
<span id="cb6-5"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># q_backward, additionally:</span></span>
<span id="cb6-6">db2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> dQ.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>(axis<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb6-7">db1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> dh.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>(axis<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span></code></pre></div></div>
<div id="cell-fig-bias" class="cell" data-execution_count="3">
<details class="code-fold">
<summary>code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb7-1">bias <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {(b, s): run(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">5e-4</span>, s, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sgd"</span>, bias<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>b) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> b <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> [<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>] <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> s <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)}</span>
<span id="cb7-2"></span>
<span id="cb7-3">fig, ax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.subplots(figsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">7.5</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">3.6</span>))</span>
<span id="cb7-4"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> b, c, name <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> [(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>, ORANGE, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"no biases"</span>), (<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>, BLUE, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"with biases"</span>)]:</span>
<span id="cb7-5">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> s <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>):</span>
<span id="cb7-6">        x, y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> curve(bias[(b, s)][<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>])</span>
<span id="cb7-7">        ax.plot(x, y, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>c, lw<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.4</span>, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>name <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> s <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>)</span>
<span id="cb7-8">    ax.annotate(name, (x[<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], y[<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]), xytext<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>), textcoords<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"offset points"</span>, va<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"center"</span>, fontsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">9</span>)</span>
<span id="cb7-9">ax.axhline(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">22</span>, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>GREY, lw<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, ls<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"--"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> note(ax, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30000</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">34</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"random policy ≈ 22"</span>)</span>
<span id="cb7-10">ax.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">set</span>(title<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Return"</span>, xlabel<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"environment steps"</span>, ylabel<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"return (rolling 20)"</span>, xlim<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">56000</span>))</span>
<span id="cb7-11">ax.legend(loc<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"upper left"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> fig.tight_layout()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> plt.show()</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div id="fig-bias" class="quarto-float quarto-figure quarto-figure-center anchored">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-bias-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://7wik.github.io/posts/dqn-first-principles/index_files/figure-html/fig-bias-output-1.png" width="807" height="385" class="figure-img">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-bias-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;2: Plain SGD, lr 5e-4, 3 seeds each. The only difference is two bias vectors.
</figcaption>
</figure>
</div>
</div>
</div>
</section>
<section id="then-sgd-vs-adam" class="level2">
<h2 class="anchored" data-anchor-id="then-sgd-vs-adam">Then: SGD vs Adam</h2>
<p>With everything working, I wrote Adam (about ten lines) and swapped it in for SGD, expecting a clear win. It wasn’t that simple.</p>
<p>At a learning rate of 1e-3, SGD’s Q values ran away in two of three seeds while Adam’s stayed bounded. Adam’s step is roughly the learning rate no matter how large the gradient is, which breaks the loop of big error, big step, bigger error. At 5e-4, Adam reached a return of 200 about twice as fast and with much less variation across seeds, but it plateaued lower than SGD. Its Q values also overshot 100 earlier, which is the overestimation that Double DQN is meant to fix.</p>
<p>Comparing the two at the same learning rate isn’t entirely fair, since SGD’s step is the learning rate times the gradient and Adam’s is roughly the learning rate itself. The honest summary is that Adam didn’t make this DQN better, it made it harder to break.</p>
<div id="cell-fig-adam" class="cell" data-execution_count="4">
<details class="code-fold">
<summary>code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb8-1">div <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {(o, s): run(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-3</span>, s, o) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> o <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sgd"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"adam"</span>] <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> s <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)}</span>
<span id="cb8-2">spd <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sgd"</span>, s): bias[(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>, s)] <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> s <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)}</span>
<span id="cb8-3">spd.update({(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sgd"</span>, s): run(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">5e-4</span>, s, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sgd"</span>) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> s <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>)})</span>
<span id="cb8-4">spd.update({(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"adam"</span>, s): run(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">5e-4</span>, s, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"adam"</span>) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> s <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>)})</span>
<span id="cb8-5"></span>
<span id="cb8-6">grid <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.linspace(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2000</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">50000</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">200</span>)</span>
<span id="cb8-7">fig, (a, b) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.subplots(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, figsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">3.6</span>))</span>
<span id="cb8-8"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> o, c, name <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> [(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sgd"</span>, ORANGE, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"SGD"</span>), (<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"adam"</span>, BLUE, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Adam"</span>)]:</span>
<span id="cb8-9">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> s <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>):</span>
<span id="cb8-10">        q <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> div[(o, s)][<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb8-11">        a.plot(np.arange(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(q)) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>, q, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>c, lw<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.3</span>, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>name <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> s <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>)</span>
<span id="cb8-12">    ys <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.array([np.interp(grid, <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>curve(spd[(o, s)][<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>])) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> s <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>)])</span>
<span id="cb8-13">    b.fill_between(grid, ys.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">min</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>), ys.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">max</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>), color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>c, alpha<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.15</span>, lw<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb8-14">    b.plot(grid, ys.mean(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>), color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>c, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>name)</span>
<span id="cb8-15">a.axhline(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>GREY, lw<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, ls<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"--"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> note(a, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30000</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">60</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"max possible Q = 100"</span>)</span>
<span id="cb8-16">a.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">set</span>(title<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Max |Q|, lr 1e-3"</span>, xlabel<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"gradient update"</span>, yscale<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"log"</span>)</span>
<span id="cb8-17">b.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">set</span>(title<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Return, lr 5e-4"</span>, xlabel<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"environment steps"</span>, ylabel<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"return (rolling 20)"</span>)</span>
<span id="cb8-18">a.legend(loc<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"upper left"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> b.legend(loc<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"upper left"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> fig.tight_layout()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> plt.show()</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div id="fig-adam" class="quarto-float quarto-figure quarto-figure-center anchored">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-adam-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://7wik.github.io/posts/dqn-first-principles/index_files/figure-html/fig-adam-output-1.png" width="1085" height="385" class="figure-img">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-adam-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;3: Left: max |Q| at lr 1e-3 (3 seeds). Right: return at lr 5e-4, mean and min–max over 5 seeds.
</figcaption>
</figure>
</div>
</div>
</div>
</section>
<section id="what-id-tell-myself-before-starting" class="level2">
<h2 class="anchored" data-anchor-id="what-id-tell-myself-before-starting">What I’d tell myself before starting</h2>
<ul>
<li><strong>Know your bounds.</strong> If max Q goes above <img src="https://latex.codecogs.com/png.latex?1/(1-%5Cgamma)">, it’s diverging, whatever the warning says.</li>
<li><strong>Identical results across different settings</strong> mean the setting is disconnected from the code you think it controls.</li>
<li><strong>Worse than random</strong> usually means the policy has collapsed, so look at what the network can represent.</li>
<li><strong>Writing it by hand</strong> shows you what the framework was doing for you. Here, that was biases.</li>
<li><strong>Change one thing at a time.</strong> The constant-1 experiment took one line and answered the question faster than any amount of staring at the code.</li>
</ul>
<p>Next up is PPO in numpy, and then GRPO.</p>


</section>

 ]]></description>
  <category>reinforcement learning</category>
  <category>numpy</category>
  <category>debugging</category>
  <guid>https://7wik.github.io/posts/dqn-first-principles/</guid>
  <pubDate>Tue, 01 Dec 2026 00:00:00 GMT</pubDate>
</item>
<item>
  <title>Nearest Neighbor classifier</title>
  <link>https://7wik.github.io/posts/nearest-neighbor-classifier/</link>
  <description><![CDATA[ 






<p>This post is about(probably) one of the most simple algorithms of ML- Nearest Neighbor classifier. To begin with, it’s a known fact that the whole concept of ML relies on a crucial idea called the “plug-in principle”. <a href="https://towardsdatascience.com/an-introduction-to-the-bootstrap-method-58bcb51b4d60">This blog</a> is a nice read for the people interested in learning the basics of statistical foundations of ML. Nearest Neighbor algorithm is one of the many algorithms that branched out of this principle.</p>
<section id="problem-setup" class="level1">
<h1>Problem setup</h1>
<p>we are given a training set <img src="https://latex.codecogs.com/png.latex?S%20=%20%5C%7B(X_1,%20Y_1),%20(X_2,%20Y_2),......,%20(X_n,%20Y_n)%5C%7D"> and a testset <img src="https://latex.codecogs.com/png.latex?T%20=%20%5C%7BX_1',%20X_2',......,%20X_m'%5C%7D">, we’re supposed to train/ develop/ learn a model using the points in <img src="https://latex.codecogs.com/png.latex?S"> and predict the corresponding <img src="https://latex.codecogs.com/png.latex?Y_i%20%5Cforall%20X_i%20%5Cin%20T">. Here <img src="https://latex.codecogs.com/png.latex?X_i%20%5Cin%20%5Cmathbb%7BR%7D%5Ed"> and <img src="https://latex.codecogs.com/png.latex?Y_i%20%5Cin%20%5C%7B0,1,2,...,8,9%5C%7D">.</p>
</section>
<section id="assumption-in-nearest-neighbor-classifier" class="level1">
<h1>Assumption in Nearest Neighbor classifier</h1>
<p>This algorithm assumes that are the <img src="https://latex.codecogs.com/png.latex?X_i%20%5Cin%20S"> having identical <img src="https://latex.codecogs.com/png.latex?Y_is"> exist in a cluster, i.e., any point in the dataset has the label equivalent to the label possessed by the point ‘closest’ to it. There are many metrics to assess this ‘closeness’.</p>
</section>
<section id="further-setup-for-this-post" class="level1">
<h1>Further setup for this post</h1>
<p>The most commonly used metric is the <img src="https://latex.codecogs.com/png.latex?%5Cell_2-norm">(Of course, it doesn’t make sense to use this metric for every problem). This makes sense in this setup because we have already defined that our inputs belong to the Euclidean space. This post will be primarily focused on simplifying/ optimizing the implementation of nn-classifier when using the Euclidean distance metric. This optimization is based on a mathematical trick.</p>
</section>
<section id="details" class="level1">
<h1>Details</h1>
<p>So, if we want to assign label to every point in the test data, we need to find the <img src="https://latex.codecogs.com/png.latex?%5Cell%7B%7D_2-distance"> between every vector/input and every vector/ point in the test data. Oh yeah, this seems like quite cumbursome, but yes, it’s certainly inevitable(like Thanos!). If you want to do the below operation, I’m telling you it’s going to take a lot of time.</p>
<pre><code>for x_j,y_j in S:
    for t_i in T:
        distance = np.square(x_j-t_i).sum()</code></pre>
<p>Instead, let’s skip the part using 2 for loops- as numpy has some cool array-operations that can optimize our implementation. We should use the below identity for finding the euclidean distance between two vectors <img src="https://latex.codecogs.com/png.latex?x_j,%20t_i">:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%20%20%20%20%7C%7Ct_i%20-%20x_j%7C%7C%5E2_2%20=%20(t_i%20-%20x_j)%5ET(t_i%20-%20x_j)%20=%20t_i%5ETt_i%20+%20x_j%5ETx_j%20-2t_i%5ETx_j%0A"></p>
<p>For the last term we need to compute the product of the matrices(as we’re dealing with matrices in our implementation not individual vectors). We can’t escape doing the product of the two big arrays <img src="https://latex.codecogs.com/png.latex?X,%20T"> for the last term, so instead I focused on optimizing the way we find the first two terms: ## Optmization -1 If we observe carefully, the first and second terms: <img src="https://latex.codecogs.com/png.latex?t_i%5ETt_i,%20x_j%5ETx_j"> involve taking the dot product of the vectors with themselves. So we can simply take the product <img src="https://latex.codecogs.com/png.latex?S%5ET.dot(S)"> and <img src="https://latex.codecogs.com/png.latex?T%5ET.dot(T)">, and pick the diagonal elements from the obtained matrices.</p>
<pre><code>    t_square = (test.dot(test.transpose())).diagonal()
    x_square = (X.dot(X.transpose())).diagonal()</code></pre>
<p>We can see that this still involves multiplying big matrices, below is the further optimization. ## Optimization -2 If we notice carefully, the first two terms represent square of lengths of every vector as <img src="https://latex.codecogs.com/png.latex?x_j%5ETx_j=%7C%7Cx_j%7C%7C_2%5E2">. We can simply square the indivdual elements in <img src="https://latex.codecogs.com/png.latex?S,%20T"> and sum along the axis=1. This will also give the lengths of vectors as in the earlier results.</p>
<pre><code>    t_square = np.square(test).sum(-1)
    x_square = np.square(X).sum(-1)</code></pre>
<p>To test the efficacy of these steps, I did a simple experiment: I picked the MNIST dataset, For each <img src="https://latex.codecogs.com/png.latex?n%20%5Cin%20%5C%7B1000,%202000,%204000,%208000%5C%7D">: <!-- \begin{itemize} --> 1. Draw n points from data, together with their corresponding labels, uniformly at random. 1. Use these n points as the training data and testdata as the test points; compute the fraction of test examples on which the nearest neighbor classifier predicts the label incorrectly (i.e., the test error rate) <!-- \end{itemize} --> This is the plot of the learning curve when using the nearest neighbor algorithm <img src="https://7wik.github.io/posts/nearest-neighbor-classifier/learning_curve.jpg" title="learning_curve" class="img-fluid" alt="learning_curve"> I carried out the above two steps 10 times for every <img src="https://latex.codecogs.com/png.latex?n">. The first optimization step took <strong>222.86</strong> seconds, and the second optimization took <strong>111.9936</strong>. That means, a simple understanding of what norm is, has <strong>reduced our runtime by alomst half</strong>. I have uploaded these two implementations on my github account- <a href="https://github.com/7wik/Nearest-neighbor-classifier/blob/main/nn.py">Optimization-1</a>, <a href="https://github.com/7wik/Nearest-neighbor-classifier/blob/main/nn2.py">Optimization-2</a>. Please keep checking this blog for further cool posts.</p>


</section>

 ]]></description>
  <category>numpy</category>
  <category>classical ML</category>
  <guid>https://7wik.github.io/posts/nearest-neighbor-classifier/</guid>
  <pubDate>Tue, 08 Dec 2020 00:00:00 GMT</pubDate>
</item>
<item>
  <title>Class conditional and class generic disentangled representations</title>
  <link>https://7wik.github.io/posts/conditional-disentangled-representations/</link>
  <description><![CDATA[ 






<p>During my internship at IIT-H, I came across disentangled representations while going through the ICML paper <a href="https://arxiv.org/pdf/1802.05983.pdf">Disentangling by factorising</a>. In this work by Kim et al, Factor-VAE, modeling of the disentangled representations is done by encouraging the marginal distribution of representation to be factorial. They achieved this by minimizing the total correlation(TC) of the latent units- where we define the TC of a set of random variables <img src="https://latex.codecogs.com/png.latex?z_1,z_2,...z_n"> as</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%20%20TC(z_1,z_2,...,z_n)=%20KL(p(z_1,z_2,...,z_n)%7C%7C%5Cprod_%7Bi=1%7D%5E%7Bn%7Dp(z_i))%0A"> (Here <img src="https://latex.codecogs.com/png.latex?KL"> stands for Kullback-leibler divergence). They estimated TC by using <a href="http://yosinski.com/mlss12/media/slides/MLSS-2012-Sugiyama-Density-Ratio-Estimation-in-Machine-Learning.pdf">density ratio estimation</a>.<br>
# Problem</p>
<p>Factor-VAE learns a generalised set of factors of variation for all the classes in a dataset,i.e, using Factor-VAE, we can model only those factors which are common to all the classes. But, what if we want to learn class specific factors? or if we want to understand the class-specific properties? using Factor-VAE, we are forced to learn as many models as there are classes which is quite cumbersome, thus, it’s not desirable. In order to address this problem, we proposed a solution.</p>
<section id="assumptions-and-approach" class="level1">
<h1>Assumptions and approach</h1>
<p>We assume that we have a dataset <img src="https://latex.codecogs.com/png.latex?%5Cmathbb%7BD%7D"> of samples <img src="https://latex.codecogs.com/png.latex?(x,y)"> with <img src="https://latex.codecogs.com/png.latex?n"> classes where <img src="https://latex.codecogs.com/png.latex?x"> is our observation and <img src="https://latex.codecogs.com/png.latex?y"> is it’s one-hot encoded class label belonging to<img src="https://latex.codecogs.com/png.latex?%5C%7By%20%5Cin%20%5C%7B0,1%5C%7D%5E%7Bn%7D%20%5Cmid%20%5Csum_i(y_i)=1%5C%7D">. We consider a VAE kind of setup for our experiments and problem solving. Since we are interested in learning disentangled representations which take the class information into consideration, the obvious choice is to explicitly condition the encoder with the class label for learning representations with cues from the class label.</p>
</section>
<section id="naive-model" class="level1">
<h1>naive-model</h1>
<p>We consider the set of latent variables to be denoted by <img src="https://latex.codecogs.com/png.latex?%5Ctextbf%7Bz%7D"> and we define a posterior <img src="https://latex.codecogs.com/png.latex?q_%7B%5Cphi%7D(z%7Cx,y)">, a prior <img src="https://latex.codecogs.com/png.latex?p(z%7Cy)"> and likelihood <img src="https://latex.codecogs.com/png.latex?p_%7B%5Ctheta%7D(x%7Cz,y)"> This model’s framework is similar to a fully supervised conditional VAE setup, where we try to optimize the variational lower bound</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%20%20p(x%7Cy)%20%5Cgeq%20E_%7Bq_%7B%5Ctheta%7D(z%7Cx,y)%7D%5Bp(x%7Cz,y)%5D%20-%20KL(q_%7B%5Ctheta%7D(z%7Cx,y)%7C%7Cp(z))%20%20%20%20%20%20%0A"></p>
<p>But in our case since we want to learn disentangled representations, like in <a href="https://openreview.net/references/pdf?id=Sy2fzU9gl"><img src="https://latex.codecogs.com/png.latex?%5Cbeta-">VAE</a>, we have an additional weight on the KL-divergence term to ensure disentanglement of the variables. The problem with this objective is quite clear, similar to that of <img src="https://latex.codecogs.com/png.latex?%5Cbeta-">VAE’s the additional weight that we put on KL-divergence term is adding on to minimizing the mutual information between <img src="https://latex.codecogs.com/png.latex?z"> and the joint variable <img src="https://latex.codecogs.com/png.latex?(x,y)"> w.r.t the variational joint distribution as well. Hence, even though the <img src="https://latex.codecogs.com/png.latex?z"> gets disentangled, the latent code’s knowledge about the data is minimized in every step. This can be easily shown following the <a href="https://arxiv.org/pdf/1706.00531.pdf">Makhzani et al</a> and proof in <a href="https://arxiv.org/pdf/1802.05983.pdf">Factor-VAE</a>.</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cbegin%7Baligned%7D%0A%20%20E_%7B(x,y)%5Csim%20D(x,y)%7D%5BKL(q_%7B%5Ctheta%7D(z%7Cx,y)%7C%7Cp(z))%5D%20=%20I(z;(x,y))+KL(q(z)%7C%7Cp(z))%0A%5Cend%7Baligned%7D%0A"></p>
<p>We generally take standard gaussian as <img src="https://latex.codecogs.com/png.latex?p(z)">, so the representation <img src="https://latex.codecogs.com/png.latex?q(z)"> gets disentangled because of the weight term. To restrict the problem aroused by <img src="https://latex.codecogs.com/png.latex?I(z;(x,y))">, we can put a cap on the <img src="https://latex.codecogs.com/png.latex?KL"> term in this objective with a gradually increasing positive term <img src="https://latex.codecogs.com/png.latex?C_z"> and modify our objective similar to that of <a href="https://arxiv.org/pdf/1804.03599.pdf">burgess et al’s</a>. Using an approach like this simply narrows down our intent for learning meaningful representations. We expect to learn factors both which are and which are not affected by class-information. To solve this problem, we can use the following model, the details of which are explained in the next subsection.</p>
</section>
<section id="proposed-model" class="level1">
<h1>Proposed Model</h1>
<p><img src="https://7wik.github.io/posts/conditional-disentangled-representations/model-2.jpg" title="Proposed model" class="img-fluid" alt="Proposed model"> We propose a model which is a modification to the previous model’s framework which allows us to model both class-dependent and class-independent factors. Let <img src="https://latex.codecogs.com/png.latex?%5Ctextbf%7Bz%7D">,<img src="https://latex.codecogs.com/png.latex?%5Ctextbf%7Bw%7D"> denote the set of class-dependent and class-independent variables respectively. We define a joint posterior <img src="https://latex.codecogs.com/png.latex?q_%7B%5Cphi%7D(z,w%7Cx,y)">, a prior <img src="https://latex.codecogs.com/png.latex?p(z,w%7Cy)"> and likelihood <img src="https://latex.codecogs.com/png.latex?p_%7B%5Ctheta%7D(x%7Cz,w,y)">. With this premise, the conventional <img src="https://latex.codecogs.com/png.latex?%5Cbeta">-VAE kind of objective is,</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%20%20%20%20L(%5Ctheta,%5Cphi)=%20E_%7Bq_%7B%5Cphi%7D(z,w%7Cx,y)%7D%5Bp_%7B%5Ctheta%7D(x%7Cz,w,y)%5D-%5Cbeta%20.KL(q_%7B%5Cphi%7D(z,w%7Cx,y)%7C%7Cp(z,w%7Cy))%0A"></p>
<p>Since we have assumed that <img src="https://latex.codecogs.com/png.latex?z%20%5Cperp%20y"> and <img src="https://latex.codecogs.com/png.latex?z%20%5Cperp%20w">, we rewrite this objective as</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%20%20%20%20L(%5Ctheta,%5Cphi)=%20E_%7Bq_%7B%5Cphi%7D(z,w%7Cx,y)%7D%5Bp_%7B%5Ctheta%7D(x%7Cz,w,y)%5D-%5Cbeta%20.KL(q_%7B%5Cphi%7D(z%7Cx)%7C%7Cp(z%7Cy))%20-%20%5Cgamma%20.KL(q_%7B%5Cphi%7D(w%7Cx,y)%7C%7Cp(w%7Cy))%0A"></p>
<p>Taking inspiration from <a href="https://arxiv.org/pdf/1804.03599.pdf">burgess et al</a>, we put a cap on the KL-divergence terms so that there is not much information about the data lost. With this our modified objective is</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cbegin%7Baligned%7D%0A%20%20L_%7BVAE%7D=%20E_%7Bq_%7B%5Cphi%7D(z,w%7Cx,y)%7D%5Bp_%7B%5Ctheta%7D(x%7Cz,w,y)%5D-%5Cbeta%7CKL(q_%7B%5Cphi%7D(z%7Cx)%7C%7Cp(z%7Cy))%20-%20C_z%7C%20-%20%5Cgamma%7CKL(q_%7B%5Cphi%7D(w%7Cx,y)%7C%7Cp(w%7Cy))%20-%20C_w%7C%0A%5Cend%7Baligned%7D%0A"></p>
</section>
<section id="minimizing-class-dependence" class="level1">
<h1>Minimizing class dependence</h1>
<p>We have assumed that <img src="https://latex.codecogs.com/png.latex?z%20%5Cperp%20y"> and we wanted most information related to <img src="https://latex.codecogs.com/png.latex?y"> to dwell in <img src="https://latex.codecogs.com/png.latex?w">, so we explicitly minimize the mutual information between <img src="https://latex.codecogs.com/png.latex?z"> and <img src="https://latex.codecogs.com/png.latex?y">. We do this by making use of a classifier network. If <img src="https://latex.codecogs.com/png.latex?z%20%5Cperp%20y">, the classifier misclassifies a given <img src="https://latex.codecogs.com/png.latex?z">. For this purpose, we define an augmented loss to be maximized by the network using a binary-cross-entropy.</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cbegin%7Baligned%7D%0A&amp;%20%20%20L_%7Bclass%7D(z)=%20y.log(%5Csigma(h_%7B%5Cpsi%7D(z)))%20+%20(1-y).log(1-%5Csigma(h_%7B%5Cpsi%7D(z)))%0A%5Cend%7Baligned%7D%0A"></p>
<p>Since the classifier must also be capable of predicting the correct class label given <img src="https://latex.codecogs.com/png.latex?z">, the classifier’s parameters are also to be trained to achieve the below defined objective- <img src="https://latex.codecogs.com/png.latex?%5Cbegin%7Balignat%7D%7B2%7D%0A%5Cmin_%7B%5Cpsi%7D%20%20%20%20%20%20%20%20%5Cquad%20&amp;&amp;%20%20L_%7Bclass%7D%0A%5Cend%7Balignat%7D"> So, our overall objective is to solve the below multi-step optimization problem where we train the parameters of encoder and decoder by solving the maximization problem in the first-step and train the parameters of the classifier in the next step while solving the minimization problem-</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cbegin%7Baligned%7D%0A%20%20&amp;%20%20%5Cmax_%7B%5Ctheta,%5Cphi%7D%20%5Cquad%20&amp;&amp;%20L(%5Ctheta,%5Cphi)+%20L_%7Bclass%7D%0A%5Cend%7Baligned%7D%0A"></p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cbegin%7Baligned%7D%0A%20%20&amp;%20%20%5Cmin_%7B%5Cpsi%7D%20%20%5Cquad%20&amp;&amp;%20L_%7Bclass%7D%0A%5Cend%7Baligned%7D%0A"></p>
</section>
<section id="results-and-experiments" class="level1">
<h1>Results and experiments</h1>
<p>I tested this model on 3 datasets: MNIST, Fashion-MNIST, CelebA. I noticed some pretty good results on MNIST and FMNIST where I was able to generate multiple class-dependent features. ## Qualitative results ### Class-specific factors(W|y) I have clearly pointed out factors we identified for each class. We can understand what each factor corresponds to by traversing between -5 and 5 along a particular dimension of the latent <img src="https://latex.codecogs.com/png.latex?w"> and by keeping the values across all other dimesnions to be constant. The reconstructions along each row correspond to the samething done(Images in Red correspond to original images and the ones in green are their reconstructions). The qualitative results are shown below: <img src="https://7wik.github.io/posts/conditional-disentangled-representations/w-fmnist.jpg" title="W FMNIST" class="img-fluid" alt="W FMNIST"> The above image depicts the various class-specific factors that are observed in Fashion-MNIST dataset. <img src="https://7wik.github.io/posts/conditional-disentangled-representations/mnist-grid.jpg" title="MNIST" class="img-fluid" alt="W MNIST"> The above image depicts the various class-specific factors that are observed in MNIST dataset. ### Generic factors of variation(Z) The below results depict the factor that was learnt by the model. Each row corresponds to reconstructions observed while varying one particular dimension of the latent representation <img src="https://latex.codecogs.com/png.latex?z"> between -5 and 5. We noticed that, for a particular dimension, same factor can be seen to be varying for all the classes which is what was intended. <img src="https://7wik.github.io/posts/conditional-disentangled-representations/z-grid.jpg" title="z-common factor" class="img-fluid" alt="Z GRID"> Above image corresponds to the factor that is common to all the classes in that dataset.</p>
<p>Each block corresponds to reconstructions observed while varying one particular dimension of the latent representation <img src="https://latex.codecogs.com/png.latex?z"> between -5 and 5. We noticed that, for that particular dimension, either no common factor or some meaningless variation can be seen to be varying for all the classes which is what was intended. <img src="https://7wik.github.io/posts/conditional-disentangled-representations/z-comparison-unchanged.jpg" title="z-unaffected factors" class="img-fluid" alt="Z UNCHANGED GRID"></p>
<section id="quantitative-results" class="level2">
<h2 class="anchored" data-anchor-id="quantitative-results">Quantitative results</h2>
<p>To check the extent to which our objective has helped in channeling the class-information from <img src="https://latex.codecogs.com/png.latex?z"> to <img src="https://latex.codecogs.com/png.latex?w">, we have trained separate classifiers(with same capacity) on samples from <img src="https://latex.codecogs.com/png.latex?z"> and <img src="https://latex.codecogs.com/png.latex?w%7Cy"> respectively to predict their respective class labels with and without using <img src="https://latex.codecogs.com/png.latex?L_%7Bclass%7D"> on the datasets MNIST,Fashion-MNIST and CelebA. The accuracies we are mentioning here are the average accuracies of <img src="https://latex.codecogs.com/png.latex?3"> runs. We took this average to avoid misjudgment caused due to randomization. It can be clearly observed that in all the <img src="https://latex.codecogs.com/png.latex?3"> datasets that we have tested upon, the case when using <img src="https://latex.codecogs.com/png.latex?L_%7Bclass%7D"> is helping <img src="https://latex.codecogs.com/png.latex?w"> in achieving higher accuracy in predicting the true label. This gives enough validation to our intent for the class-specific information to reside in <img src="https://latex.codecogs.com/png.latex?w"> and non-class specific information to be in <img src="https://latex.codecogs.com/png.latex?z">.</p>
<table class="caption-top table">
<colgroup>
<col style="width: 19%">
<col style="width: 33%">
<col style="width: 20%">
<col style="width: 26%">
</colgroup>
<thead>
<tr class="header">
<th>Dataset</th>
<th style="text-align: center;">Method</th>
<th style="text-align: center;">Accuracy on z</th>
<th style="text-align: right;">Accuracy on w</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Fmnist</td>
<td style="text-align: center;">without L-class</td>
<td style="text-align: center;">0.337</td>
<td style="text-align: right;">0.47</td>
</tr>
<tr class="even">
<td>Fmnist</td>
<td style="text-align: center;">with L-class</td>
<td style="text-align: center;">0.32</td>
<td style="text-align: right;"><strong>0.68</strong></td>
</tr>
<tr class="odd">
<td>Mnist</td>
<td style="text-align: center;">without L-class</td>
<td style="text-align: center;">0.37</td>
<td style="text-align: right;">0.31</td>
</tr>
<tr class="even">
<td>Mnist</td>
<td style="text-align: center;">with L-class</td>
<td style="text-align: center;">0.30</td>
<td style="text-align: right;"><strong>0.45</strong></td>
</tr>
<tr class="odd">
<td>CelebA</td>
<td style="text-align: center;">without L-class</td>
<td style="text-align: center;">0.63</td>
<td style="text-align: right;">0.68</td>
</tr>
<tr class="even">
<td>CelebA</td>
<td style="text-align: center;">with L-class</td>
<td style="text-align: center;">0.685</td>
<td style="text-align: right;"><strong>0.745</strong></td>
</tr>
</tbody>
</table>


</section>
</section>

 ]]></description>
  <category>generative models</category>
  <category>research</category>
  <guid>https://7wik.github.io/posts/conditional-disentangled-representations/</guid>
  <pubDate>Tue, 01 Oct 2019 00:00:00 GMT</pubDate>
</item>
</channel>
</rss>
