<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Badjessa Bahoumda</title>
    <description>The latest articles on DEV Community by Badjessa Bahoumda (@badjessab).</description>
    <link>https://dev.to/badjessab</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F4176213%2F6b8f8c76-7127-461b-92b4-a17bbfa9c0da.jpg</url>
      <title>DEV Community: Badjessa Bahoumda</title>
      <link>https://dev.to/badjessab</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/badjessab"/>
    <language>en</language>
    <item>
      <title>Rebuilding the AI Stack by Hand: A Scalar Autograd Engine</title>
      <dc:creator>Badjessa Bahoumda</dc:creator>
      <pubDate>Wed, 11 Nov 2026 16:49:44 +0000</pubDate>
      <link>https://dev.to/badjessab/rebuilding-the-ai-stack-by-hand-a-scalar-autograd-engine-1b51</link>
      <guid>https://dev.to/badjessab/rebuilding-the-ai-stack-by-hand-a-scalar-autograd-engine-1b51</guid>
      <description>&lt;p&gt;Sprint 1 of this series took two posts: in Part 1 we built a tokenizer, the part of the stack that turns text into numbers, and in Part 2 we made it faster. &lt;/p&gt;

&lt;p&gt;This is Sprint 2, and it is about learning. Once a network makes a guess and the guess is wrong, how does it know what to change?&lt;/p&gt;

&lt;p&gt;Here is the whole idea, in plain terms first. A network is a chain of simple arithmetic. Numbers come in, get multiplied and added in stages, and one final number comes out: the guess. We score the guess against the right answer, and that score is the error (the loss). Training is the work of shrinking that error by adjusting the hundreds of little numbers inside the network, called weights.&lt;/p&gt;

&lt;p&gt;The question is which weights to adjust, and by how much. The process that answers it is called backpropagation, and the way I ended up picturing it is simple: share out the blame for the error. Every part of the network gets told how much of the final error it is responsible for, in proportion to how much it contributed. Parts that contributed a lot get adjusted a lot. Parts that contributed nothing get left alone. &lt;/p&gt;

&lt;p&gt;The technical name for a share of blame is a &lt;strong&gt;gradient&lt;/strong&gt;, and that is the word I will use from here. It is all backpropagation computes: one gradient for every weight, in a single backward pass.&lt;/p&gt;

&lt;p&gt;By the end of this sprint, the engine trains a small network to 100% accuracy on a toy dataset of 200 points arranged in two moon shapes. Getting there took three bugs, and the third one was invisible to every test we had.&lt;/p&gt;

&lt;h2&gt;
  
  
  The build
&lt;/h2&gt;

&lt;p&gt;The engine is built around one class, &lt;code&gt;Value&lt;/code&gt;, which wraps a single number. Each &lt;code&gt;Value&lt;/code&gt; remembers which values produced it, and carries a small function (a closure) describing how to pass gradient back to them. That rule is specific to each operation. When two numbers are added, each one takes the full gradient that arrives. When two numbers are multiplied, each one takes the gradient multiplied by the &lt;em&gt;other&lt;/em&gt; number, because that is how much it actually influenced the result.&lt;/p&gt;

&lt;p&gt;Here is the multiplication rule, exactly as it sits in the engine. Look at the last part of each line inside the rule, the &lt;code&gt;+ self.grad&lt;/code&gt;: every share is &lt;em&gt;added&lt;/em&gt; to whatever is already there. That is the collecting, happening in code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;__mul__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;other&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;out&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Value&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;data&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;other&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;other&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"mul"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_backward&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;lambda&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
        &lt;span class="nb"&gt;setattr&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"grad"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;grad&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;other&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;data&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;grad&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="nb"&gt;setattr&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;other&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"grad"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;grad&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;data&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;other&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;grad&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;]&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;out&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Nothing flows backward while the guess is being made. The forward pass just builds the chain and leaves these rules behind, one per step. Afterwards, &lt;code&gt;backward()&lt;/code&gt; walks the chain in reverse, starting from the loss, and each rule splits the gradient between the numbers that fed into it. If a number was used in two places, it collects a share from both. That collecting is the whole trick.&lt;/p&gt;

&lt;p&gt;A tiny example, with real numbers. Take a = 2 and b = 3. Then c = a × b = 6, and d = c + a = 8. Working backward from d: d's gradient is 1. c fed into one addition, so c gets 1. b sits inside the multiplication, so b gets 1 × a = 2. And a is used twice: once in the addition (share 1) and once in the multiplication (share 1 × b = 3), so a ends with 4.&lt;/p&gt;

&lt;p&gt;At real scale, the backward walk first lines the chain up in topological order, meaning every value is visited only after everything that depends on it. We built that ordering with a loop and an explicit stack rather than recursion, because Python gives up around 1,000 nested calls and real chains run far deeper than that. Here is the walk itself. Keep an eye on the &lt;code&gt;visited&lt;/code&gt; set: it becomes important in the third bug below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;backward&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;topo&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
    &lt;span class="n"&gt;worklist&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kc"&gt;False&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
    &lt;span class="n"&gt;visited&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kt"&gt;set&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="n"&gt;worklist&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;processed&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;worklist&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;pop&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="n"&gt;processed&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;grad&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
            &lt;span class="n"&gt;worklist&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kc"&gt;True&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="n"&gt;worklist&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;extend&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kc"&gt;False&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_prev&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;processed&lt;/span&gt; &lt;span class="ow"&gt;and&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="n"&gt;visited&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;topo&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="n"&gt;visited&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;topo&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;reverse&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="c1"&gt;# then: set this node's grad to 1.0 and fire each _backward in order&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Three small building blocks sit on top. A &lt;code&gt;Neuron&lt;/code&gt; takes its inputs, multiplies each by a weight, adds them up, and squashes the result with &lt;code&gt;tanh&lt;/code&gt; so the numbers stay in a tame range. A &lt;code&gt;Layer&lt;/code&gt; is a row of neurons all looking at the same inputs. An &lt;code&gt;MLP&lt;/code&gt; stacks layers, so &lt;code&gt;MLP(2, [4, 4, 1])&lt;/code&gt; is a network with 2 inputs, two hidden layers of 4, and 1 output: 37 weights in total.&lt;/p&gt;

&lt;p&gt;Training is then just a loop:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Run the inputs forward and get a guess.&lt;/li&gt;
&lt;li&gt;Score the guess against the right answers. That score is the loss.&lt;/li&gt;
&lt;li&gt;Zero every weight's gradient.&lt;/li&gt;
&lt;li&gt;Call &lt;code&gt;backward()&lt;/code&gt; to share out the blame.&lt;/li&gt;
&lt;li&gt;Nudge each weight a small step against its gradient: &lt;code&gt;p.data -= lr * p.grad&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Repeat.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;And here is that same loop as it actually runs in the training script. Four things happen per round: guess, wipe, blame, nudge.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;step&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;steps&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;loss&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;acc&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;loss_and_acc&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;   &lt;span class="c1"&gt;# forward pass + score the guess&lt;/span&gt;
    &lt;span class="n"&gt;mlp&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;zero_grad&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;              &lt;span class="c1"&gt;# wipe last round's gradients&lt;/span&gt;
    &lt;span class="n"&gt;loss&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;backward&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;              &lt;span class="c1"&gt;# share out the blame&lt;/span&gt;
    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;p&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="n"&gt;mlp&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;parameters&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;p&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;data&lt;/span&gt; &lt;span class="o"&gt;-=&lt;/span&gt; &lt;span class="n"&gt;lr&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;p&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;grad&lt;/span&gt;    &lt;span class="c1"&gt;# nudge each weight against its gradient&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Step 3 looks like housekeeping but it matters. Gradients accumulate on purpose, because a value used in several places has to collect every share. So if you do not zero them between rounds, last round's gradients leak into this round's adjustments. &lt;br&gt;
In step 5, &lt;code&gt;lr&lt;/code&gt; is the learning rate, the step size: the gradient says which direction is downhill, the learning rate says how far to trust it. Ours was 0.1.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fklen7g50csruiecr2mm9.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fklen7g50csruiecr2mm9.gif" alt="A small network making a guess, then sharing the blame for its error, connection by connection" width="800" height="589"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  The numbers
&lt;/h2&gt;

&lt;p&gt;Before the bugs, the evidence that the engine is correct. We built a chain by repeating one operation N times and compared the engine's gradient against the answer calculus gives for it, at every size:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;== graph-size sweep: y = x; repeat N: y = y * w + b ==
       N  forward (s)  backward (s)        dy/dx
     100        0.000         0.000         1.11
    1000        0.002         0.002         2.72
    5000        0.011         0.007         148
   20000        0.049         0.038      4.8e+08
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The last column matches the analytic answer (1.001^N) at every row, and a 20,000-deep chain runs without the recursion problem described above. One full forward-plus-backward pass of the moons network (two hidden layers of 16, so 337 weights) takes 2.88 ms. All timings are from my Mac mini.&lt;/p&gt;

&lt;h2&gt;
  
  
  Where it broke
&lt;/h2&gt;

&lt;p&gt;Three bugs are worth writing about, because each one passed the tests before it failed somewhere more expensive.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The share that got counted twice.&lt;/strong&gt; The first bug showed up in the simplest possible case: one number used twice in the same step, added to itself. With a = 2, b = a + a = 4, and c = b × b = 16, the gradient for a should end at 16. Mine returned 72. My addition rule was written like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;grad&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;grad&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;grad&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;   &lt;span class="c1"&gt;# wrong&lt;/span&gt;
&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;grad&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;grad&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;grad&lt;/span&gt;         &lt;span class="c1"&gt;# right&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The first version re-read the gradient it had just written and multiplied it again on the second slot. The fix is one line and completely boring, which is usually the sign of the right fix.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;17 weights that were secretly 4.&lt;/strong&gt; The second bug was stranger. Training kept crashing inside the power operation, with numbers so large the program gave up. The power operation was not the bug; it was where values that had already grown enormous finally exploded. A quick count told the real story: the network claimed to have 17 weights, but only 4 of them were actually different objects. The cause was one line:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nc"&gt;Value&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;random&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;uniform&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;n_in&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Multiplying a list copies the reference, not the object, so every weight in the neuron was literally the same &lt;code&gt;Value&lt;/code&gt;, doing several jobs at once: collecting gradient from every place it was used, then getting nudged once per list entry. A few hundred rounds of that and the values ran away. Building each &lt;code&gt;Value&lt;/code&gt; inside the loop fixed it. A quieter bug sat in the same file: a neuron computed its &lt;code&gt;tanh()&lt;/code&gt; result and threw it away instead of returning it, so that step was silently doing nothing.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The plateau.&lt;/strong&gt; With those fixed, all 38 tests passed, and training still did not work. On moons, the loss fell from 2.3830 and then flatlined at 0.4376, accuracy stuck at 0.880, and tripling the steps changed nothing. &lt;/p&gt;

&lt;p&gt;The bug was in &lt;code&gt;backward()&lt;/code&gt; itself: my topological walk kept no record of which nodes it had already visited (no visited set), so a value that fans out into two different operations could enter the walk twice and fire its rule before all of its gradient had arrived. Part of the blame was simply never delivered. A tiny check exposes it: with a = 2, h = a + 1, and y = h × 2 + h × 3, the gradient for a should be exactly 5. Mine returned 7 on some runs and 8 on others, depending on set ordering. &lt;/p&gt;

&lt;p&gt;No test had caught it because every test reused a value inside one operation, and real networks fan out constantly: every hidden unit feeds several outputs. Adding the visited set, so each node is processed exactly once and only after its full gradient has landed, fixed the check to exactly 5.0, and the moons run went from the plateau to this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;step 0   loss 2.3830   accuracy 0.295
step 10  loss 0.1309   accuracy 0.980
step 20  loss 0.0836   accuracy 0.990
step 49  loss 0.0433   accuracy 1.000
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The lesson from that one stayed with me: the training loop will faithfully follow an incomplete gradient for hundreds of steps. It has no way to know the answer it was given is missing a piece.&lt;/p&gt;

&lt;h2&gt;
  
  
  How this differs from production
&lt;/h2&gt;

&lt;p&gt;PyTorch, the tool production training actually runs on, is the same algorithm. Same backward walk, same topological order, same gradients that accumulate until you zero them. Forgetting the zeroing step is a classic production bug too, for exactly the reason it appears in our loop.&lt;/p&gt;

&lt;p&gt;The difference is representation, not the idea. PyTorch operates on tensors, whole tables of numbers at once, with the arithmetic in compiled code on fast hardware, so the cost of an operation is paid once per table instead of once per number. Our engine pays Python overhead per number, which is why a few hundred weights is its comfortable size. What production adds on top (graphics cards, lower-precision arithmetic, spreading the gradient computation across machines) is engineering around the same reverse pass.&lt;/p&gt;

&lt;p&gt;One design choice is worth naming. Building the graph as the forward pass runs, the way our &lt;code&gt;Value&lt;/code&gt; does, is what PyTorch calls define-by-run. The alternative is to capture the whole graph before running it, which is JAX's approach: less flexible to debug, but the whole graph can be optimized at once, fusing operations together. After a weekend of debugging a hand-built graph, both sides of that trade-off make sense to me.&lt;/p&gt;

&lt;p&gt;Next in the series: the transformer block, where this MLP comes back as the feed-forward half of every layer, and the network starts generating text instead of just sorting points into two moons.&lt;/p&gt;

&lt;p&gt;Check out the code for this in this repo -&lt;a href="https://github.com/Badjessa-git/ai-stack-sprints/tree/main/sprint-02-autograd-engine" rel="noopener noreferrer"&gt;https://github.com/Badjessa-git/ai-stack-sprints/tree/main/sprint-02-autograd-engine&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  References
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Karpathy, &lt;a href="https://github.com/karpathy/micrograd" rel="noopener noreferrer"&gt;micrograd&lt;/a&gt; and the accompanying video, &lt;em&gt;The spelled-out intro to neural networks and backpropagation&lt;/em&gt; — the reference this sprint was modelled on.&lt;/li&gt;
&lt;li&gt;PyTorch, &lt;a href="https://pytorch.org/docs/stable/notes/autograd.html" rel="noopener noreferrer"&gt;Autograd mechanics&lt;/a&gt; — how the production version of this engine is documented, accumulating gradients included.&lt;/li&gt;
&lt;li&gt;Raschka, &lt;em&gt;Build a Large Language Model (From Scratch)&lt;/em&gt; — the reference we will lean on for the transformer sprint.&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>ai</category>
      <category>python</category>
      <category>machinelearning</category>
      <category>programming</category>
    </item>
    <item>
      <title>Rebuilding the AI Stack by Hand: Optimizing the Tokenizer</title>
      <dc:creator>Badjessa Bahoumda</dc:creator>
      <pubDate>Sat, 07 Nov 2026 20:32:18 +0000</pubDate>
      <link>https://dev.to/badjessab/rebuilding-the-ai-stack-by-hand-part-2-optimizing-the-tokenizer-lim</link>
      <guid>https://dev.to/badjessab/rebuilding-the-ai-stack-by-hand-part-2-optimizing-the-tokenizer-lim</guid>
      <description>&lt;p&gt;&lt;em&gt;Continue Sprint 1 of a series on rebuilding the modern AI stack from first principles. The code and tests for this sprint can be found here &lt;a href="https://github.com/Badjessa-git/ai-stack-sprints/tree/main/sprint-01-bpe-tokenizer" rel="noopener noreferrer"&gt;https://github.com/Badjessa-git/ai-stack-sprints/tree/main/sprint-01-bpe-tokenizer&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;In the first part of this series, we ended up with a working BPE tokenizer. For this part in our series, we explore two questions:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Can we make this faster without changing the outputs?&lt;/li&gt;
&lt;li&gt;How do production systems run tokenizers at scale? What are the trade-offs?&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Before optimizing anything, we profiled v1 to see where the time was actually going;&lt;/p&gt;

&lt;p&gt;In training, about 37% of the time was spent recounting every pair from scratch after each merge, and about 45% was spent on the merges themselves. Picking the most frequent pair was under 2%. &lt;/p&gt;

&lt;p&gt;In decode, almost all of the time was spent searching backwards through the merges for every token being expanded. &lt;/p&gt;

&lt;p&gt;We also had one rule for everything below: v2 had to produce the exact same output as v1, same merges and same encodings, or the numbers would mean nothing.&lt;/p&gt;

&lt;h2&gt;
  
  
  Optimizations
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;train(): our stats dictionary is being sorted every round.&lt;/strong&gt; In our v1 tokenizer, we sorted the stats dictionary on every round just to find the pair with the maximum count. Python's sorted function uses the &lt;a href="https://en.wikipedia.org/wiki/Timsort" rel="noopener noreferrer"&gt;Timsort&lt;/a&gt; algorithm, which has a time complexity of O(n log n). &lt;br&gt;
We don't really need to apply a sorting algorithm when we're looking for the maximum value. We can simply walk through the dictionary, keeping track of the maximum value seen so far.&lt;/p&gt;

&lt;p&gt;On its own, the new selection measured cheaper. Timed on a representative pair sheet (~1,183 distinct pairs), per selection round:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;- sorted(...) approach: 0.312 ms
- Built-in max(): 0.101 ms
- Champion loop: 0.044 ms
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The operation itself got ~7x cheaper.&lt;/p&gt;

&lt;p&gt;However, this was not where train spent most of its time. This search was about 2% of the train step. We did make some improvement, but there was still more headroom.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;decode(): trading time complexity for space complexity at our pair lookup step.&lt;/strong&gt; As part of our decode function, we need to figure out the pair of numbers that resulted in the new id. In v1, this is how we approached it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;matching_key&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;next&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;val&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;merges&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;items&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;val&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;token_id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;At each step we search through our merges to find which pair produced that id. This is a cost of O(n) that is paid at every level of our recursion.&lt;/p&gt;

&lt;p&gt;The fix here was simple: we built a lookup table where we store the pair of numbers that made a specific id.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;merges&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;left&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;right&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;id&lt;/span&gt;
&lt;span class="n"&gt;new_token_ids&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;merge_pair&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
                &lt;span class="n"&gt;token_ids&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;token_ids&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;pair&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;left&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;right&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;new_id&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="nb"&gt;id&lt;/span&gt;
            &lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;__byte_lookup_table&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nb"&gt;id&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;left&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;right&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;## &amp;lt;-- Lookup table&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then in our recursive decode function, we replace the scan with a simple lookup, which has a time complexity of O(1), removing the continuous scan done previously.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;left&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;right&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;__byte_lookup_table&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;token_id&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Comparing the decode run, we now see a 12.5x improvement in the decode step:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;corpus: 139,380 bytes (sprint corpus x30)
sanity check: merges and encodings identical ✓

v1 (frozen) : decode[30000 tokens] 0.124s
v2 (current): decode[30000 tokens] 0.010s

speedup (v1 / v2): decode 12.53x
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;train(): update the count of the pairs only affected by the merge instead of recounting everything.&lt;/strong&gt; During every iteration of the loop in v1, we rebuilt our count map using &lt;code&gt;get_stats&lt;/code&gt;. While that is a reasonable choice, rebuilding the count map every iteration feels wasteful, since only a subset of pairs are affected after a merge.&lt;/p&gt;

&lt;p&gt;Here's a diagram to describe how it was done:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fi4b1wwvdjxwmbuss76n1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fi4b1wwvdjxwmbuss76n1.png" alt="One merge round in six steps: v1 recounts all pairs after a merge, v2 updates only the pairs the merge touched" width="800" height="1357"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;As a result, we saw a 1.44x improvement in our training steps. The max-scan change from the first point contributed to this as well, but not significantly. Most of this gain is the counting.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;python3 part2/compare.py
corpus: 139,380 bytes &lt;span class="o"&gt;(&lt;/span&gt;sprint corpus x30&lt;span class="o"&gt;)&lt;/span&gt;
sanity check: merges and encodings identical ✓

v1 &lt;span class="o"&gt;(&lt;/span&gt;frozen&lt;span class="o"&gt;)&lt;/span&gt; : train 2.448s
v2 &lt;span class="o"&gt;(&lt;/span&gt;current&lt;span class="o"&gt;)&lt;/span&gt;: train 1.705s
speedup &lt;span class="o"&gt;(&lt;/span&gt;v1 / v2&lt;span class="o"&gt;)&lt;/span&gt;: train 1.44x
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  How this differs from production tokenizers
&lt;/h2&gt;

&lt;p&gt;Production tokenizers split the text before BPE ever runs. GPT-style tokenizers use a regex to break the text into chunks (words, numbers, punctuation), and merges never cross those boundaries. Ours runs BPE over the raw byte stream, so a merge can swallow a space and half of the next word. SentencePiece, which the Llama family uses, does it differently and treats the space as just another character.&lt;/p&gt;

&lt;p&gt;They are also not written in Python. OpenAI's tiktoken and Hugging Face's &lt;code&gt;tokenizers&lt;/code&gt; run the same BPE algorithm, but with a Rust core behind a Python API. Our decode win came from a better data structure. Theirs comes from that, plus a much smaller constant factor on every step, and batch parallelism on top.&lt;/p&gt;

&lt;p&gt;The vocabulary sizes are on a different scale too. We trained to 512. GPT-2 uses ~50k, GPT-4 uses ~100k, and GPT-4o uses ~200k. Every entry in the vocabulary costs real parameters. A 100k vocabulary at a dimension of 4,096 is roughly 400M parameters in the embedding table alone, and the rarer tokens get trained less. So vocabulary size is a trade-off, not just a case of bigger being better: bigger vocabularies shorten sequences, but they cost memory and training quality.&lt;/p&gt;

&lt;p&gt;The counting is structured differently as well. Production trainers count pairs over a frequency table of distinct chunks, instead of one long token stream, so a merge only touches the chunks that contain that pair. Our incremental counting in change 3 had to track positions on the raw stream, which is exactly the bookkeeping their approach avoids.&lt;/p&gt;

&lt;p&gt;So yes, it got faster without changing a single output: 1.44x on training, 12.5x on decode. Production is mostly the same algorithm, with the bookkeeping done up front and the hot loop written in Rust. Next in the series: teaching the model to learn, with a scalar autograd engine.&lt;/p&gt;

&lt;h2&gt;
  
  
  References
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;OpenAI, &lt;a href="https://github.com/openai/tiktoken" rel="noopener noreferrer"&gt;tiktoken&lt;/a&gt; — the Rust-core tokenizer library; the source for the cl100k (~100k, GPT-4) and o200k (~200k, GPT-4o) vocabulary sizes and the regex pretokenization patterns.&lt;/li&gt;
&lt;li&gt;Hugging Face, &lt;a href="https://github.com/huggingface/tokenizers" rel="noopener noreferrer"&gt;tokenizers&lt;/a&gt; — production tokenizer library with a Rust core behind Python bindings.&lt;/li&gt;
&lt;li&gt;Kudo &amp;amp; Richardson, &lt;a href="https://github.com/google/sentencepiece" rel="noopener noreferrer"&gt;SentencePiece&lt;/a&gt; (2018) — the other production family; treats whitespace as a character. Used with a 32k vocabulary in &lt;a href="https://arxiv.org/abs/2307.09288" rel="noopener noreferrer"&gt;Llama 2&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;Sennrich, Haddow &amp;amp; Birch, &lt;a href="https://arxiv.org/abs/1508.07909" rel="noopener noreferrer"&gt;Neural Machine Translation of Rare Words with Subword Units&lt;/a&gt; (2016), and the &lt;a href="https://github.com/rsennrich/subword-nmt" rel="noopener noreferrer"&gt;subword-nmt&lt;/a&gt; implementation — BPE for production use, counting pairs over word-frequency tables rather than a raw token stream.&lt;/li&gt;
&lt;li&gt;Radford et al., GPT-2 (2019) — the ~50k (50,257) byte-level BPE vocabulary.&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>ai</category>
      <category>python</category>
      <category>machinelearning</category>
      <category>programming</category>
    </item>
    <item>
      <title>Rebuilding the AI Stack by Hand: Building a BPE Tokenizer</title>
      <dc:creator>Badjessa Bahoumda</dc:creator>
      <pubDate>Sun, 11 Oct 2026 03:15:33 +0000</pubDate>
      <link>https://dev.to/badjessab/rebuilding-the-ai-stack-by-hand-part-1-building-a-bpe-tokenizer-48m2</link>
      <guid>https://dev.to/badjessab/rebuilding-the-ai-stack-by-hand-part-1-building-a-bpe-tokenizer-48m2</guid>
      <description>&lt;p&gt;&lt;em&gt;Sprint 1 of a series on rebuilding the modern AI stack from first principles. The code and tests for this sprint are in the &lt;a href="https://github.com/Badjessa-git/ai-stack-sprints" rel="noopener noreferrer"&gt;ai-stack-sprints repository&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Why I'm doing this
&lt;/h2&gt;

&lt;p&gt;I realized that I hadn't manually coded in a while. AI-driven development lets me move much faster, but I still believe coding by hand and understanding systems are valuable skills — and I could feel both dulling as AI took over more development work.&lt;/p&gt;

&lt;p&gt;I had also been using LLMs for a while without understanding how they work. So I'm rebuilding the modern AI stack on my Mac mini, one piece at a time. I don't need to build GPT-5. My goal is to end up with something I can ping and get a response from.&lt;/p&gt;

&lt;p&gt;The rules are simple:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Every two weeks — or earlier if I have time — I'll complete a sprint and publish a post about it.&lt;/li&gt;
&lt;li&gt;AI sets up the scaffolding, benchmarks, and tests because I'm only doing this on weekends.&lt;/li&gt;
&lt;li&gt;All implementation code has to be written manually: no autocomplete and no AI-generated code.&lt;/li&gt;
&lt;li&gt;I can use the web for syntax, but I'll try to solve each problem myself first.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This is the first sprint: a tokenizer.&lt;/p&gt;

&lt;p&gt;LLMs don't see the letters you type into a prompt composer. A tokenizer translates text into token IDs that a model can process, and translates token IDs back into text when the model responds.&lt;/p&gt;

&lt;h2&gt;
  
  
  What I thought a tokenizer did
&lt;/h2&gt;

&lt;p&gt;I didn't think much about tokenization before starting this. I knew it helped LLMs process input, but I had never looked at it closely.&lt;/p&gt;

&lt;p&gt;The closest thing I had built was in my &lt;a href="https://wizardchess3d.vercel.app/" rel="noopener noreferrer"&gt;multiplayer 3D chess game&lt;/a&gt;, where game-state messages arrived as JSON, were parsed into event types and payloads, and were translated into updated state. Different problem, similar shape: convert one representation into another before the system can use it.&lt;/p&gt;

&lt;p&gt;My naive model was that tokenization split text by a delimiter, transformed the pieces for efficiency, and sent them to the model's brain.&lt;/p&gt;

&lt;p&gt;Instead, this implementation never starts with a delimiter. It starts with raw bytes and learns which adjacent sequences occur often enough to become units of their own.&lt;/p&gt;

&lt;h2&gt;
  
  
  Building v1: count pairs, merge, repeat
&lt;/h2&gt;

&lt;p&gt;The goal was to complete the round trip:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;text -&amp;gt; tokens -&amp;gt; original text
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I started with two helper functions:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;get_stats&lt;/code&gt; counts each adjacent pair in a list of token IDs. The pairs overlap: in &lt;code&gt;[1, 2, 1]&lt;/code&gt;, both &lt;code&gt;(1, 2)&lt;/code&gt; and &lt;code&gt;(2, 1)&lt;/code&gt; count.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;merge_pair&lt;/code&gt; returns a new list with every non-overlapping occurrence of a chosen pair replaced by a new token ID.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Together, they answer BPE's two central questions: &lt;em&gt;Which pair occurs most often?&lt;/em&gt; and &lt;em&gt;What happens when we merge it everywhere?&lt;/em&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Training
&lt;/h3&gt;

&lt;p&gt;Training begins by encoding the text as UTF-8 bytes. The base vocabulary contains all 256 possible byte values, IDs 0 through 255. ASCII is included, but not the limit: characters outside ASCII become sequences of UTF-8 bytes.&lt;/p&gt;

&lt;p&gt;The requested vocabulary must be at least 256. Each learned merge receives the next available ID, starting at 256.&lt;/p&gt;

&lt;p&gt;The loop is:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Count the adjacent pairs in the current token list.&lt;/li&gt;
&lt;li&gt;Pick the most frequent pair.&lt;/li&gt;
&lt;li&gt;Record it in &lt;code&gt;self.merges&lt;/code&gt; as &lt;code&gt;(left, right) -&amp;gt; new_id&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Replace that pair throughout the token list.&lt;/li&gt;
&lt;li&gt;Repeat until reaching the target vocabulary or running out of pairs frequent enough to merge.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Vocabulary size is the merge budget: 256 permits no learned merges; 512 permits up to 256.&lt;/p&gt;

&lt;p&gt;At the end, &lt;code&gt;self.merges&lt;/code&gt; is the learned rulebook. Encoding applies it to new text; decoding expands token IDs back into bytes and decodes them as UTF-8.&lt;/p&gt;

&lt;h2&gt;
  
  
  Where it broke: decoding is not a one-pass operation
&lt;/h2&gt;

&lt;p&gt;Decoding was the most challenging part of the tokenizer.&lt;/p&gt;

&lt;p&gt;Encoding was comparatively straightforward: iterate through the merges in learned order and call &lt;code&gt;merge_pair&lt;/code&gt; for each rule — one pass through the token sequence per rule.&lt;/p&gt;

&lt;p&gt;My first decoding attempt was also iterative. For each input token that was the result of a merge, I replaced it once with the two IDs that created it. After one pass, I expected to have bytes that could be converted back into a string.&lt;/p&gt;

&lt;p&gt;Here's the example that exposed the problem:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;tok&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;BPETokenizer&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;tok&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;train&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="s2"&gt;"the quick brown fox jumps over the lazy dog. "&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="mi"&gt;30&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;vocab_size&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;320&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;encoding&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;tok&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;encode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"the quick brown fox jumps over the lazy dog"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;encoding&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Training stopped after 44 merges — IDs 256 through 299 — because no remaining pair met the minimum frequency. A few of those merges were:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;116&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;104&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;256&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;  &lt;span class="c1"&gt;# "th"&lt;/span&gt;
    &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;256&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;101&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;257&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;  &lt;span class="c1"&gt;# "the"&lt;/span&gt;
    &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;257&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;32&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;258&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;   &lt;span class="c1"&gt;# "the "&lt;/span&gt;
    &lt;span class="c1"&gt;# ... more merges ...&lt;/span&gt;
    &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;291&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;111&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;292&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;292&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;103&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;293&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The entire sentence encoded to only two tokens:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;258&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;293&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But expanding each of those tokens once produced:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;257&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;32&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;292&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;103&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That was not a list of bytes. Token 257 still represented &lt;code&gt;"the"&lt;/code&gt;, and token 292 represented almost the entire remainder of the sentence. Because 257 and 292 are greater than 255, they could not be placed in a &lt;code&gt;bytes&lt;/code&gt; object at all. I was left holding a partially expanded sequence.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F1h8wl7t70r59ck2ybbwy.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F1h8wl7t70r59ck2ybbwy.gif" alt="Decoder with iterative approach" width="800" height="300"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Recursion was the missing idea
&lt;/h3&gt;

&lt;p&gt;A merged token can contain another merged token. Expanding it once therefore doesn't finish the job; it merely reveals the next layer.&lt;/p&gt;

&lt;p&gt;The fix was to treat every merged token as a small tree. The private &lt;code&gt;__decode_single&lt;/code&gt; function returns an ID below 256 as a byte; otherwise, it finds the pair that created the ID and recursively expands both children until every leaf is a byte.&lt;/p&gt;

&lt;p&gt;Then &lt;code&gt;decode&lt;/code&gt; concatenates the bytes from every input token and decodes them as UTF-8. For the sentence above, recursion eventually produces the original 43 bytes.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Ft8ry6f4yjh539un5a0qy.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Ft8ry6f4yjh539un5a0qy.gif" alt="Using Recursing to decode" width="800" height="604"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The lesson from the bug was precise: &lt;strong&gt;a token is not decoded merely because it has been replaced once. It is decoded when every value underneath it has reached a byte.&lt;/strong&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  The numbers
&lt;/h2&gt;

&lt;p&gt;I benchmarked three vocabulary sizes on the same small corpus. At only 4,646 bytes, the results reveal the shape of the trade-off better than they predict production performance.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;corpus: 4,644 chars / 4,646 bytes
vocab= 256  merges=  0  tokens= 4,646  ratio=100.00%  bytes/token=1.00  train=0.00s  encode=0.000s
vocab= 384  merges=128  tokens= 2,346  ratio=50.50%  bytes/token=1.98  train=0.10s  encode=0.041s
vocab= 512  merges=256  tokens= 1,882  ratio=40.51%  bytes/token=2.47  train=0.18s  encode=0.070s
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;At vocabulary 256, there are no learned merges, so every byte remains its own token: 4,646 tokens.&lt;/p&gt;

&lt;p&gt;At vocabulary 512, the same text takes 1,882 tokens — &lt;strong&gt;59.5% fewer tokens than the byte-level baseline&lt;/strong&gt;. Shorter sequences mean less input for a model to process per request.&lt;/p&gt;

&lt;p&gt;The diminishing returns were just as interesting:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The first 128 merges reduced the token count by 2,300.&lt;/li&gt;
&lt;li&gt;The next 128 merges reduced it by only 464.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;BPE is greedy: frequent pairs are merged first, so later merges chase rarer patterns. Vocabulary size is a trade-off, not a case of “bigger is always better.”&lt;/p&gt;

&lt;h2&gt;
  
  
  Why a dictionary — and why this version is slow
&lt;/h2&gt;

&lt;p&gt;I used dictionaries in two central places.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;get_stats&lt;/code&gt; uses an adjacent pair as a dictionary key so it can count occurrences as it scans the sequence. &lt;code&gt;self.merges&lt;/code&gt; uses that same pair as a key and maps it to the new token ID.&lt;/p&gt;

&lt;p&gt;The merges dictionary provides a second, less obvious benefit: Python dictionaries preserve insertion order. Because merges are inserted in the order they are learned, insertion order is also their rank. During encoding, the dictionary is both the rulebook and the priority list.&lt;/p&gt;

&lt;p&gt;The trade-off appears in decoding. &lt;code&gt;self.merges&lt;/code&gt; points forward, from a pair to a token ID. Decoding needs the reverse direction. My implementation searches for the pair when it needs it. I could build a reverse dictionary or precomputed token-to-bytes table, making lookups faster at the cost of extra memory and a duplicate representation. For a first pass, I left it out.&lt;/p&gt;

&lt;p&gt;Training makes a similar trade. Each round, my code recounts every pair from scratch and sorts the counts to find the winner. If &lt;strong&gt;M&lt;/strong&gt; is the number of merges and &lt;strong&gt;N&lt;/strong&gt; is the current sequence length, repeated full scans cost roughly &lt;strong&gt;M × N&lt;/strong&gt;, plus sorting.&lt;/p&gt;

&lt;p&gt;That is more than necessary. When a pair is merged, only pairs immediately around each merge site change; counts elsewhere remain valid. An optimized implementation could update only those neighbors, but it would need considerably more bookkeeping to track changing counts and winners correctly.&lt;/p&gt;

&lt;p&gt;The encoder makes the same simplicity trade: it scans the whole token sequence once for every learned merge rule.&lt;/p&gt;

&lt;p&gt;Finally, a larger vocabulary shortens sequences, but with diminishing compression gains, while steadily increasing training work, the size of the model's embedding and output layers, and the number of rare tokens it must learn.&lt;/p&gt;

&lt;p&gt;Those trade-offs are acceptable for a 4,646-byte learning corpus and a few hundred merges. They would not be acceptable unchanged at production scale.&lt;/p&gt;

&lt;h2&gt;
  
  
  Next: Part 2
&lt;/h2&gt;

&lt;p&gt;This version is correct, but deliberately naive.&lt;/p&gt;

&lt;p&gt;In Part 2, I'll optimize it: avoid sorting every pair count merely to find the maximum, precompute the lookups decoding needs, and rerun the same tests and benchmark to see what actually improves. I'll also revisit the production-scale trade-offs — and what I misunderstood when I started — with the complete v1-to-v2 comparison in hand.&lt;/p&gt;

</description>
      <category>ai</category>
      <category>python</category>
      <category>machinelearning</category>
      <category>programming</category>
    </item>
  </channel>
</rss>
