<?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>Timoth Dev</title>
<link>https://timothdev.com/blog.html</link>
<atom:link href="https://timothdev.com/blog.xml" rel="self" type="application/rss+xml"/>
<description>All posts by Timoth Dev: machine learning, healthcare tech, hardware projects and the things I&#39;ve built.</description>
<generator>quarto-1.10.19</generator>
<lastBuildDate>Thu, 05 Nov 2026 00:00:00 GMT</lastBuildDate>
<item>
  <title>CruxTok Architecture</title>
  <dc:creator>Timoth Dev</dc:creator>
  <link>https://timothdev.com/posts/cruxtok-architecture/</link>
  <description><![CDATA[ 






<p>CruxTok is a discrete text tokenizer built on the multiscale residual VQ-VAE from <a href="../../posts/next-concept-modeling/index.html">Next-Concept Modeling</a>. NCM builds each coarse level by averaging fixed windows of the text. CruxTok replaces that with learned attention, so each code can choose which words it reads. Why I tried this, and what came out of it, is in <a href="../../posts/cruxtok/index.html">CruxTok: Letting the First Level Choose What Matters</a>.</p>
<p>The diagrams show the tokenizer exactly as it was trained for the <a href="https://doi.org/10.5281/zenodo.23956631">preprint</a>: 48-token windows of XSum news summaries, GPT-2 token ids, and vectors of width 384. The code and configs are on <a href="https://github.com/Zilch123/CruxTok">GitHub</a>.</p>
<section id="the-whole-tokenizer" class="level2">
<h2 class="anchored" data-anchor-id="the-whole-tokenizer">The whole tokenizer</h2>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://timothdev.com/posts/cruxtok-architecture/overview.svg" class="img-fluid figure-img" alt="Token ids go to an encoder, then levels 1 to 9 in sequence, each producing codes and adding to a running sum read by the decoder."></p>
<figcaption>Token ids pass through an encoder, then nine levels in order. Each level receives what the earlier levels failed to capture and adds to a running sum, which the decoder reads at a cutoff level.</figcaption>
</figure>
</div>
</section>
<section id="slots-rise-with-level" class="level2">
<h2 class="anchored" data-anchor-id="slots-rise-with-level">Slots rise with level</h2>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://timothdev.com/posts/cruxtok-architecture/slots-per-level.svg" class="img-fluid figure-img" alt="Nine bars. Slots per level are 4, 6, 10, 14, 20, 26, 32, 40 and 48, and total codes reach 200, or 2,400 bits."></p>
<figcaption>Each bar spans the same 48 tokens, with one block per slot, showing where each slot starts. Slots rise from 4 to 48. Each slot picks one 12-bit code from its level’s codebook.</figcaption>
</figure>
</div>
<p>Level 1 is only 4 codes for the whole sentence, so at most it can hold the gist.</p>
</section>
<section id="inside-one-level" class="level2">
<h2 class="anchored" data-anchor-id="inside-one-level">Inside one level</h2>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://timothdev.com/posts/cruxtok-architecture/one-level.svg" class="img-fluid figure-img" alt="Four bands. Pool: queries attend to the residual, with a learnable prior added to the scores before softmax. Quantize: nearest code from the codebook with a straight-through estimator. Expand: positions attend to the code vectors, again with a prior. Update: add to the running sum and subtract from H with stop-gradient to form the next residual."></p>
<figcaption>One level pools the residual into slots, snaps each slot to its nearest code, expands the codes back to 48 positions, and adds the result to the running sum. Only the number of slots changes across levels 1 to 8.</figcaption>
</figure>
</div>
<p>The prior is added to the raw scores before the softmax: <img src="https://latex.codecogs.com/png.latex?%5Ctext%7Battention%7D%20=%20%5Ctext%7Bsoftmax%7D(qk%5E%5Ctop/8%20+%20B)">. It starts each slot as a soft Gaussian centred on NCM’s window for that slot. It is the same for every input, so it carries no information about the text itself.</p>
<p>The prior is soft on purpose. At level 1, about a quarter of each slot’s starting weight already falls outside its own window, and the queries are free to move it further. Adding a prior this way is studied in <a href="https://arxiv.org/abs/2601.15380">You Need Better Attention Priors</a>.</p>
<p>Queries and keys are RMS-normalised per head before the dot product. Without that, the attention logits grew to about <img src="https://latex.codecogs.com/png.latex?10%5E7"> and training diverged.</p>
</section>
<section id="the-last-level" class="level2">
<h2 class="anchored" data-anchor-id="the-last-level">The last level</h2>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://timothdev.com/posts/cruxtok-architecture/last-level.svg" class="img-fluid figure-img" alt="Levels 1 to 8 go through pool, codebook and expand. Level 9 goes straight from the residual to the codebook to its output."></p>
<figcaption>Levels 1 to 8 pool, quantize and expand. Level 9 has one slot per token, so it skips pooling and expansion and quantizes each position directly.</figcaption>
</figure>
</div>


</section>

 ]]></description>
  <category>Research</category>
  <category>GenAI</category>
  <category>NLP</category>
  <category>Machine Learning</category>
  <guid>https://timothdev.com/posts/cruxtok-architecture/</guid>
  <pubDate>Thu, 05 Nov 2026 00:00:00 GMT</pubDate>
  <media:content url="https://timothdev.com/posts/cruxtok-architecture/overview.svg" medium="image" type="image/svg+xml"/>
</item>
<item>
  <title>CruxTok: Letting the First Level Choose What Matters</title>
  <dc:creator>Timoth Dev</dc:creator>
  <link>https://timothdev.com/posts/cruxtok/</link>
  <description><![CDATA[ 






<p>This continues my <a href="../../posts/next-concept-modeling/index.html">Next-Concept Modeling</a> post. The preprint is out on <a href="https://doi.org/10.5281/zenodo.23956631">Zenodo</a>, and the code, configs and evaluation outputs are on <a href="https://github.com/Zilch123/CruxTok">GitHub</a>.</p>
<p><img src="https://timothdev.com/posts/cruxtok/cruxtok-overview.png" class="img-fluid" alt="Top: NCM averages fixed chunks of words into 4 codes, while CruxTok's 4 codes each attend to the words they pick. Middle: a real level-1 reconstruction, where CruxTok keeps 'footballer out with an injury' and NCM's version is unrelated. Bottom: an LLM judge picks CruxTok in 57% and 63% of items, against 9% and 8% for NCM."></p>
<section id="the-idea" class="level2">
<h2 class="anchored" data-anchor-id="the-idea">The idea</h2>
<p>NCM trains an encoder-decoder tokenizer and freezes it. Then it trains a generator to predict the encoder’s codes, level by level, the way some image models grow a picture from 4x4 to 512x512. The first level is only a handful of codes for the whole sentence, so it should hold the crux: who did what, and what happened.</p>
<p>But NCM builds that first level by averaging fixed chunks of the text. Each code covers its own 12 tokens, whatever they say. If the important words sit in one chunk and filler sits in another, both chunks get one code each.</p>
<p>To capture the crux, a code has to prioritise. That is exactly what attention does. In “Attention Is All You Need”, the scores from <img src="https://latex.codecogs.com/png.latex?QK%5E%5Ctop"> decide how much each value counts, so to me it could just as well be called “Priority Is All You Need”.</p>
<p>CruxTok swaps NCM’s averaging for that. Each level has a small set of learned queries, and each query attends over all the words, guided by a soft prior that starts near NCM’s chunk. Everything else follows NCM. The <a href="../../posts/cruxtok-architecture/index.html">architecture post</a> has the full diagrams.</p>
</section>
<section id="the-setup" class="level2">
<h2 class="anchored" data-anchor-id="the-setup">The setup</h2>
<ul>
<li><strong>Data.</strong> XSum news summaries, cut to 48 tokens.</li>
<li><strong>Levels.</strong> Nine levels, from 4 codes at level 1 to 48 at level 9. Each code is one of 4,096 entries in its level’s codebook.</li>
<li><strong>Baselines.</strong> NCM’s own tokenizer, plus an NCM tokenizer given extra encoder and decoder depth so it has the same parameter count as CruxTok.</li>
<li><strong>Runs.</strong> Two training runs of CruxTok with different seeds, 30,000 steps each.</li>
</ul>
</section>
<section id="level-1-rebuilds-much-more-of-the-sentence" class="level2">
<h2 class="anchored" data-anchor-id="level-1-rebuilds-much-more-of-the-sentence">Level 1 rebuilds much more of the sentence</h2>
<p>I decoded 1,000 test summaries from level 1 alone and asked an LLM judge which reconstruction kept more of the who, what, where and outcome. The judge saw each pair in both orders, and a side only won if both orders agreed.</p>
<table class="caption-top table">
<thead>
<tr class="header">
<th>Level 1, against the same-size NCM</th>
<th>Run 1</th>
<th>Run 2</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Judge picks CruxTok</td>
<td>57%</td>
<td>63%</td>
</tr>
<tr class="even">
<td>Judge picks NCM</td>
<td>9%</td>
<td>8%</td>
</tr>
<tr class="odd">
<td>Tie or order disagreement</td>
<td>34%</td>
<td>29%</td>
</tr>
</tbody>
</table>
<p>An embedding model agrees. The level-1 reconstruction’s similarity to the original rises from 0.34 to 0.45. With three levels, CruxTok gets 60% of tokens exactly right, against at most 47% for the NCM baselines.</p>
<p>The examples are still rough. In the image above, CruxTok turns a West Ham striker with a hamstring injury into a Newcastle midfielder with an ankle injury. Names, places and numbers are often wrong. But the type of event usually survives, while NCM’s level 1 is mostly unrelated text.</p>
</section>
<section id="the-attention-does-move" class="level2">
<h2 class="anchored" data-anchor-id="the-attention-does-move">The attention does move</h2>
<p>If the queries just stayed on their starting prior, CruxTok would be NCM with extra parameters. They don’t. At level 1, the attention after training is narrower than the starting prior, about 15 tokens wide against 21. It also changes from sentence to sentence, which fixed chunks never do.</p>
<p>This shows that the attention moves. It does not show that it moves toward meaning.</p>
</section>
<section id="similar-meanings-still-dont-get-similar-codes" class="level2">
<h2 class="anchored" data-anchor-id="similar-meanings-still-dont-get-similar-codes">Similar meanings still don’t get similar codes</h2>
<p>The second thing I hoped for was a meaning-organised code space. Two sentences that mean the same thing should get similar first-level codes. That is what would make level 1 easy for a generator to predict.</p>
<p>It didn’t happen. On STS-B, a sentence-similarity benchmark, I scored how well code similarity tracks human similarity ratings, as a Spearman correlation.</p>
<table class="caption-top table">
<thead>
<tr class="header">
<th>Level 3 codes</th>
<th>STS-B Spearman</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>NCM, same size</td>
<td>0.28</td>
</tr>
<tr class="even">
<td>CruxTok, two runs</td>
<td>0.02 and 0.03</td>
</tr>
<tr class="odd">
<td>Word overlap alone</td>
<td>0.57</td>
</tr>
</tbody>
</table>
<p>The deeper NCM baseline is clearly better here, and simple word overlap beats every tokenizer.</p>
<p>So rebuilding a sentence well and grouping similar meanings together turned out to be two different goals. Learned attention gets the first one, not the second.</p>
</section>
<section id="a-training-snag" class="level2">
<h2 class="anchored" data-anchor-id="a-training-snag">A training snag</h2>
<p>CruxTok kept blowing up in bf16 training. The attention weights grew about 50-fold and the logits reached about <img src="https://latex.codecogs.com/png.latex?10%5E7">. RMS-normalising the queries and keys in each head, a known fix for this failure, removed it. With learned pooling, every level also needs its own gradient path. When I tried to skip that for the deeper levels, their outputs collapsed to almost zero.</p>
</section>
<section id="whats-next" class="level2">
<h2 class="anchored" data-anchor-id="whats-next">What’s next</h2>
<p>This is one dataset of short sentences, with a reduced training budget. The big open question is untested: does a more decodable first level actually make coarse-to-fine generation better? That needs a generator trained on top, which is the next step.</p>
<p>The full details, numbers and limitations are in the <a href="https://doi.org/10.5281/zenodo.23956631">preprint</a>.</p>


</section>

 ]]></description>
  <category>Research</category>
  <category>GenAI</category>
  <category>NLP</category>
  <category>Machine Learning</category>
  <guid>https://timothdev.com/posts/cruxtok/</guid>
  <pubDate>Thu, 05 Nov 2026 00:00:00 GMT</pubDate>
  <media:content url="https://timothdev.com/posts/cruxtok/cruxtok-overview.png" medium="image" type="image/png" height="180" width="144"/>
</item>
<item>
  <title>Matrix Multiplication Is Not Really Multiplication</title>
  <dc:creator>Timoth Dev</dc:creator>
  <link>https://timothdev.com/posts/matrix-multiplication-is-transformation/</link>
  <description><![CDATA[ 






<p>The name “matrix multiplication” sets you up to think of <img src="https://latex.codecogs.com/png.latex?3%20%5Ctimes%204%20=%2012">. A better way to read <img src="https://latex.codecogs.com/png.latex?Ax"> is: <strong>the matrix <img src="https://latex.codecogs.com/png.latex?A"> takes the vector <img src="https://latex.codecogs.com/png.latex?x"> and moves it somewhere else.</strong> The matrix is a function, and the vector is its input.</p>
<p>Seen this way, a lot of what happens inside an LLM gets simpler.</p>
<section id="what-can-a-matrix-do" class="level2">
<h2 class="anchored" data-anchor-id="what-can-a-matrix-do">What can a matrix do?</h2>
<p>Take a shape made of 2D points and multiply every point by the same matrix. Here is an F, because an F shows you when something has been mirrored. The dashed outline is the original.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://timothdev.com/posts/matrix-multiplication-is-transformation/transformations.png" class="img-fluid figure-img"></p>
<figcaption>The same F after six different 2×2 matrices. Each matrix is shown under its plot.</figcaption>
</figure>
</div>
<p>The first thing to notice is scale. The matrix with 2 on the diagonal doubles everything, so it behaves exactly like multiplying by 2. Ordinary multiplication is just the simplest thing a matrix can do.</p>
<p>Negative numbers on the diagonal are more interesting:</p>
<ul>
<li>One negative value mirrors the shape. Look at the F in the Flip plot: it reads backwards, and no rotation can do that.</li>
<li>Two negative values give a half turn. This is the only real rotation a 2D diagonal matrix can make, apart from doing nothing.</li>
</ul>
<p>For any other angle you need numbers off the diagonal. The 45° rotation has them, and so does the shear, which is a mix of the two directions.</p>
<p>This is also why the order matters. With numbers, <img src="https://latex.codecogs.com/png.latex?3%20%5Ctimes%204%20=%204%20%5Ctimes%203">. With matrices, rotating and then shearing is not the same as shearing and then rotating, so <img src="https://latex.codecogs.com/png.latex?AB"> and <img src="https://latex.codecogs.com/png.latex?BA"> are usually different. Multiplying two matrices really means <em>do one move, then the other</em>.</p>
</section>
<section id="rectangular-matrices-change-the-dimension" class="level2">
<h2 class="anchored" data-anchor-id="rectangular-matrices-change-the-dimension">Rectangular matrices change the dimension</h2>
<p>All the matrices above are square, so 2 numbers go in and 2 come out. The shape of the matrix tells you the sizes:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cunderbrace%7BA%7D_%7Bn%20%5Ctimes%20m%7D%20%5C;%20%5Cunderbrace%7Bx%7D_%7Bm%20%5Ctimes%201%7D%20=%20%5Cunderbrace%7By%7D_%7Bn%20%5Ctimes%201%7D%0A"></p>
<p>So <img src="https://latex.codecogs.com/png.latex?m"> numbers go in and <img src="https://latex.codecogs.com/png.latex?n"> numbers come out. More rows than columns (a tall matrix) goes up in dimension. More columns than rows (a wide matrix) goes down.</p>
<p>Here is a tall one, taking 2D to 3D:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cbegin%7Bbmatrix%7D%201%20&amp;%200%20%5C%5C%200%20&amp;%201%20%5C%5C%202%20&amp;%203%20%5Cend%7Bbmatrix%7D%0A%5Cbegin%7Bbmatrix%7D%20x%20%5C%5C%20y%20%5Cend%7Bbmatrix%7D%0A=%0A%5Cbegin%7Bbmatrix%7D%20x%20%5C%5C%20y%20%5C%5C%202x%20+%203y%20%5Cend%7Bbmatrix%7D%0A"></p>
<p>The point <img src="https://latex.codecogs.com/png.latex?(1,%201)"> becomes <img src="https://latex.codecogs.com/png.latex?(1,%201,%205)">. Do this to a whole grid of points and you get this:</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://timothdev.com/posts/matrix-multiplication-is-transformation/2d-to-3d.png" class="img-fluid figure-img"></p>
<figcaption>A 2D grid of points on the left. On the right, the same points after the 3×2 matrix. They now have 3 coordinates, but they all sit on one flat sheet.</figcaption>
</figure>
</div>
<p>Each point now has 3 numbers, but the third one is computed from the other two, so nothing new has been added. The points can’t leave the flat sheet <img src="https://latex.codecogs.com/png.latex?z%20=%202x%20+%203y">. A tall matrix gives the data more numbers, but on its own it doesn’t give it more freedom.</p>
<p>Going down has the opposite problem. A wide matrix can throw information away for good. If the matrix just drops <img src="https://latex.codecogs.com/png.latex?z">, then <img src="https://latex.codecogs.com/png.latex?(1,%201,%205)"> and <img src="https://latex.codecogs.com/png.latex?(1,%201,%200)"> both land on <img src="https://latex.codecogs.com/png.latex?(1,%201)">, and nothing can tell you afterwards which one you started with.</p>
</section>
<section id="so-is-this-what-an-llm-does" class="level2">
<h2 class="anchored" data-anchor-id="so-is-this-what-an-llm-does">So is this what an LLM does?</h2>
<p>It’s easy to say that an LLM takes data and maps it from lower to higher dimensions. That’s only half right. It goes up, but it also goes down, several times.</p>
<p>Here is a very small model trained on one job: <strong>next-word prediction</strong>. You give it a word, and it scores every word it knows on how likely that word is to come next. An LLM does the same job each time it writes a word.</p>
<p>The model only knows 6 words, taken from one sentence: <em>the cat sat on the mat.</em> It has the same steps as a Transformer but much smaller sizes, and it leaves out attention, so it only ever sees one word. Here it is after training, given “cat”:</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://timothdev.com/posts/matrix-multiplication-is-transformation/llm-dimensions.png" class="img-fluid figure-img"></p>
<figcaption>The toy model given “cat”. The word starts as 6 numbers, goes down to 3, up to 12, back down to 3, and up to 6 scores. “sat” gets the highest score. The matrix shape is written above each arrow.</figcaption>
</figure>
</div>
<p><strong>Input: 6 numbers.</strong> One slot per word the model knows. “cat” is written as a 1 in its slot and 0 everywhere else, which is called a one-hot vector.</p>
<p><strong>Embedding: 6 down to 3.</strong> You might expect this step to go up, but a one-hot vector is already longer than what comes out. Multiplying by the embedding matrix picks out one column, so this is a wide matrix going <em>down</em>.</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">embed <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> nn.Embedding(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)</span>
<span id="cb1-2"></span>
<span id="cb1-3">one_hot <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.zeros(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>)</span>
<span id="cb1-4">one_hot[<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> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>                                  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># "cat"</span></span>
<span id="cb1-5"></span>
<span id="cb1-6">out <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> embed.weight.T <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">@</span> one_hot                  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># shape: [3]</span></span>
<span id="cb1-7">torch.equal(out, embed(torch.tensor(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)))        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># True</span></span></code></pre></div></div>
<p><code>nn.Embedding</code> is that multiplication with a shortcut, since it can look the column up directly.</p>
<p><strong>Feed-forward: 3 up to 12, then back to 3.</strong> Here is the tall matrix. A Transformer has one of these in every layer:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Ctext%7BFFN%7D(x)%20=%20%5Cmax(0,%20xW_1%20+%20b_1)W_2%20+%20b_2%0A"></p>
<p><strong>Output: 3 up to 6.</strong> The last matrix gives one score per word the model knows. A softmax turns those into probabilities. For “cat”, “sat” gets a probability of 1.00. For “the”, the model splits it, 0.50 on “cat” and 0.50 on “mat”, because the sentence has both.</p>
<p>A real model has the same steps with bigger sizes. The input size is simply how many tokens the model knows. These are the sizes from the original Transformer in <a href="https://arxiv.org/abs/1706.03762"><em>Attention Is All You Need</em></a>:</p>
<table class="caption-top table">
<thead>
<tr class="header">
<th>Step</th>
<th style="text-align: right;">Small model</th>
<th style="text-align: right;">Original Transformer</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>One-hot input (tokens it knows)</td>
<td style="text-align: right;">6</td>
<td style="text-align: right;">37,000</td>
</tr>
<tr class="even">
<td>Embedding</td>
<td style="text-align: right;">3</td>
<td style="text-align: right;">512</td>
</tr>
<tr class="odd">
<td>Inside the feed-forward</td>
<td style="text-align: right;">12</td>
<td style="text-align: right;">2,048</td>
</tr>
<tr class="even">
<td>Back to model size</td>
<td style="text-align: right;">3</td>
<td style="text-align: right;">512</td>
</tr>
<tr class="odd">
<td>Output scores</td>
<td style="text-align: right;">6</td>
<td style="text-align: right;">37,000</td>
</tr>
</tbody>
</table>
<p>Attention moves dimensions too. From the <a href="../../posts/attention-is-matrix-multiplication/index.html">previous post</a>, <img src="https://latex.codecogs.com/png.latex?Q">, <img src="https://latex.codecogs.com/png.latex?K"> and <img src="https://latex.codecogs.com/png.latex?V"> come out of matrix multiplications. In the paper, each of the 8 heads takes 512 down to 64.</p>
</section>
<section id="where-does-the-more-information-come-from" class="level2">
<h2 class="anchored" data-anchor-id="where-does-the-more-information-come-from">Where does the “more information” come from?</h2>
<p>Going up sounds like it should add information, but a tall matrix adds no freedom. Here is that same result at the sizes the Transformer uses. Rank counts how many independent directions the data really has.</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">up <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> nn.Linear(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">512</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2048</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>)</span>
<span id="cb2-2">x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.randn(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5000</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">512</span>)</span>
<span id="cb2-3">h <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> up(x)</span>
<span id="cb2-4"></span>
<span id="cb2-5">h.shape                                     <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># [5000, 2048]</span></span>
<span id="cb2-6">torch.linalg.matrix_rank(h)                 <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># 512</span></span>
<span id="cb2-7">torch.linalg.matrix_rank(torch.relu(h))     <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># 2048</span></span></code></pre></div></div>
<p>After the tall matrix, each vector has 2,048 numbers but only 512 directions. It’s the flat sheet again, with more dimensions. After the ReLU, all 2,048 directions are in use. That’s the <img src="https://latex.codecogs.com/png.latex?%5Cmax(0,%20%5Ccdot)"> in the formula above. It bends the flat sheet, and each of the 2,048 numbers can now switch on or off on its own.</p>
<p>A smaller picture helps here. Take the 2D sheet from earlier. A matrix can tilt it, but it stays flat. Roll it into a cylinder and it now uses all 3 directions, even though it’s still the same sheet. No matrix can do that, because rolling needs a non-linear function.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://timothdev.com/posts/matrix-multiplication-is-transformation/sheet-to-cylinder.png" class="img-fluid figure-img"></p>
<figcaption>The same 2D sheet twice, with the same colours. On the left a tall matrix has tilted it, and it uses 2 directions. On the right it has been rolled into a cylinder with cos and sin, and it uses 3.</figcaption>
</figure>
</div>
<p>ReLU doesn’t make cylinders. It bends with sharp creases rather than smooth curves, but the idea is the same: bending lets the data use the extra room.</p>
<p>Without that ReLU, the whole feed-forward block would collapse. A 512 × 2048 matrix times a 2048 × 512 matrix is just a single 512 × 512 matrix, so the detour through 2,048 would give you nothing new.</p>
<p>Information also comes from the matrix itself. A word ID on its own says almost nothing. The 512 numbers that come out of the embedding were already stored in the matrix, and training put them there.</p>
</section>
<section id="what-training-is-doing" class="level2">
<h2 class="anchored" data-anchor-id="what-training-is-doing">What training is doing</h2>
<p>At the Transformer’s sizes, the embedding matrix alone holds 37,000 × 512 = 18,944,000 numbers. Each of the feed-forward matrices has 512 × 2,048 = 1,048,576 more, in every layer, for both encoder and decoder.</p>
<p>The architecture only fixes the shapes, meaning how many numbers go in and come out at each step. Training picks the numbers inside. So training an LLM is a search for the transformations that take “the words so far” to “good scores for the next word”. The 6-word model does the same search, with far fewer numbers.</p>
</section>
<section id="source" class="level2">
<h2 class="anchored" data-anchor-id="source">Source</h2>
<ul>
<li>Vaswani, Shazeer, Parmar, Uszkoreit, Jones, Gomez, Kaiser, Polosukhin. <a href="https://arxiv.org/abs/1706.03762"><em>Attention Is All You Need.</em></a> NeurIPS 2017, arXiv:1706.03762. The sizes come from this paper: <img src="https://latex.codecogs.com/png.latex?d_%7Bmodel%7D%20=%20512">, <img src="https://latex.codecogs.com/png.latex?d_%7Bff%7D%20=%202048">, 8 heads with <img src="https://latex.codecogs.com/png.latex?d_k%20=%2064">, and a 37,000 token vocabulary for its English to German task.</li>
</ul>


</section>

 ]]></description>
  <category>Deep Learning</category>
  <category>NLP</category>
  <category>GenAI</category>
  <guid>https://timothdev.com/posts/matrix-multiplication-is-transformation/</guid>
  <pubDate>Sat, 31 Oct 2026 00:00:00 GMT</pubDate>
  <media:content url="https://timothdev.com/posts/matrix-multiplication-is-transformation/llm-dimensions.png" medium="image" type="image/png" height="86" width="144"/>
</item>
<item>
  <title>What Makes a Query a Query? Attention Is Just Matrix Multiplication</title>
  <dc:creator>Timoth Dev</dc:creator>
  <link>https://timothdev.com/posts/attention-is-matrix-multiplication/</link>
  <description><![CDATA[ 






<p>This is the Transformer from <a href="https://arxiv.org/abs/1706.03762"><em>Attention Is All You Need</em></a> (Vaswani et al., 2017):</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://timothdev.com/posts/attention-is-matrix-multiplication/transformer-architecture.png" class="img-fluid figure-img" style="width:70.0%"></p>
<figcaption>The Transformer architecture. Figure 1 from Vaswani et al., 2017.</figcaption>
</figure>
</div>
<p>For a very intuitive visual walkthrough, try the <a href="https://poloclub.github.io/transformer-explainer/">Transformer Explainer</a>.</p>
<p>The diagram looks like a lot, but the orange boxes are all the same operation: <strong>attention</strong>. Zoom into one and you get this:</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://timothdev.com/posts/attention-is-matrix-multiplication/scaled-dot-product-attention.png" class="img-fluid figure-img" style="width:45.0%"></p>
<figcaption>Scaled dot-product attention. Figure 2 (left) from Vaswani et al., 2017.</figcaption>
</figure>
</div>
<p>Two matrix multiplications, a scale, an optional mask and a softmax. That’s the core of every modern LLM.</p>
<p>I understood the formula fairly quickly. What took me longer was a much simpler question: <strong>what makes the query the query?</strong> Q, K and V come out of three linear layers that look exactly alike. Why does one of them end up “asking” and another one “answering”? This post is how I worked that out. The short answer is that it’s basic linear algebra, and specifically how matrix multiplication pairs rows with columns.</p>
<section id="what-is-attention-trying-to-do" class="level2">
<h2 class="anchored" data-anchor-id="what-is-attention-trying-to-do">What is attention trying to do?</h2>
<p>Take the sentence:</p>
<blockquote class="blockquote">
<p>the animal crossed the street because it was tired</p>
</blockquote>
<p>To understand “it”, the model has to work out that “it” means the animal and not the street. So each word needs a way to look at the other words and pull in information from the ones that matter.</p>
<p>The paper describes attention as mapping a <strong>query</strong> and a set of <strong>key-value pairs</strong> to an output, where the weight on each value comes from how well the query matches the corresponding key. In plain terms:</p>
<ul>
<li><strong>Query:</strong> what this word is looking for.</li>
<li><strong>Key:</strong> what each word offers, used for matching.</li>
<li><strong>Value:</strong> what each word actually hands over once it’s picked.</li>
</ul>
<p>And the formula:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Ctext%7BAttention%7D(Q,%20K,%20V)%20=%20%5Ctext%7Bsoftmax%7D%5Cleft(%5Cfrac%7BQK%5E%5Ctop%7D%7B%5Csqrt%7Bd_k%7D%7D%5Cright)V%0A"></p>
</section>
<section id="where-do-q-k-and-v-come-from" class="level2">
<h2 class="anchored" data-anchor-id="where-do-q-k-and-v-come-from">Where do Q, K and V come from?</h2>
<p>This is where my question started. Every word begins as an embedding vector. Stack them up and you get a matrix <img src="https://latex.codecogs.com/png.latex?X">, one row per word. Then:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0AQ%20=%20XW_Q%20%5Cqquad%20K%20=%20XW_K%20%5Cqquad%20V%20=%20XW_V%0A"></p>
<p>Three weight matrices with the same shape, all filled with random numbers at the start, all applied to the same <img src="https://latex.codecogs.com/png.latex?X">. In PyTorch it’s three identical lines:</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"><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.w_q <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> nn.Linear(d_model, d_k, 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>)</span>
<span id="cb1-2"><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.w_k <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> nn.Linear(d_model, d_k, 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>)</span>
<span id="cb1-3"><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.w_v <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> nn.Linear(d_model, d_k, 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>)</span></code></pre></div></div>
<p>Nothing in these lines says “query” or “key”. So what makes <code>w_q</code> a query maker?</p>
<p>I knew the weights are learned with backprop and cross-entropy loss. But learned <em>into what</em>? If they start out the same, something has to push them in different directions. The only thing that treats them differently is the formula. So the answer has to be in <strong>where each one sits in the formula</strong>.</p>
</section>
<section id="rows-ask-columns-answer" class="level2">
<h2 class="anchored" data-anchor-id="rows-ask-columns-answer">Rows ask, columns answer</h2>
<p>Look at <img src="https://latex.codecogs.com/png.latex?QK%5E%5Ctop">. In matrix multiplication, each entry of the result is <strong>a row of the first matrix dotted with a column of the second</strong>.</p>
<ul>
<li><img src="https://latex.codecogs.com/png.latex?Q"> has one row per word. Row 6 is the query vector for “it”.</li>
<li><img src="https://latex.codecogs.com/png.latex?K%5E%5Ctop"> is <img src="https://latex.codecogs.com/png.latex?K"> flipped, so it has one <em>column</em> per word. Column 1 is the key vector for “animal”.</li>
<li>Entry (6, 1) of the result is “it”’s query dotted with “animal”’s key: one number for <em>how much “it” cares about “animal”</em>.</li>
</ul>
<p>To fill row 6, the multiplication keeps the query of “it” fixed and runs it across every column, one key at a time. That’s exactly what a search does: one question checked against every label in an index. The query is the row because it’s the thing that stays fixed while the keys go past.</p>
<p>To make this concrete I built a toy version with weights set by hand, so the numbers are easy to read. Each word has 5 features (noun, living, place, pronoun, other) and <img src="https://latex.codecogs.com/png.latex?d_k%20=%202">. I gave “it” a query that says <em>I’m looking for a living thing</em>, and gave “animal” and “street” keys that say <em>I’m living</em> and <em>I’m a place</em>. In a real model nobody sets these. They’re learned.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://timothdev.com/posts/attention-is-matrix-multiplication/qk-scores.png" class="img-fluid figure-img"></p>
<figcaption>The query matrix times the transposed key matrix. Row 6 (“it”) has a query of [4, 0]. It only matches column 1 (“animal”), whose key is [1, 0], so the score is 4 × 1 / √2 = 2.83. Every other word scores 0.</figcaption>
</figure>
</div>
<p>Every entry of the score matrix answers one question: <em>how well does row word’s question match column word’s label?</em></p>
<section id="the-small-detail-i-was-missing" class="level3">
<h3 class="anchored" data-anchor-id="the-small-detail-i-was-missing">The small detail I was missing</h3>
<p>Here’s what bothered me next. A dot product is symmetric: <img src="https://latex.codecogs.com/png.latex?q%20%5Ccdot%20k%20=%20k%20%5Ccdot%20q">. So if I swap the code to compute <img src="https://latex.codecogs.com/png.latex?KQ%5E%5Ctop"> instead, is anything different?</p>
<p>There is a difference, and it isn’t in the dot product. It’s in what happens to the rows afterwards:</p>
<ol type="1">
<li><strong>Softmax runs along each row.</strong> Each row gets turned into weights that sum to 1. So each <em>row word</em> spreads its attention over the <em>column words</em>.</li>
<li><strong>The output has one row per row word.</strong> Multiplying by <img src="https://latex.codecogs.com/png.latex?V"> gives row 6 of the output to “it”. The row word is the one that gets updated.</li>
</ol>
<p>So the query is whatever lands on the rows, because the rows are the ones that receive the result. If you swapped the names and computed <code>K @ Q.T</code>, the network would still train fine. The layer called <code>w_k</code> would just learn to make queries, and <code>w_q</code> would learn to make keys. The names are labels for us. <strong>Algebraic position is what gives each layer its role</strong>, and backprop then trains each layer for the role its position gives it.</p>
</section>
</section>
<section id="why-divide-by-d_k" class="level2">
<h2 class="anchored" data-anchor-id="why-divide-by-d_k">Why divide by √d_k?</h2>
<p>The paper explains this one. If the parts of <img src="https://latex.codecogs.com/png.latex?q"> and <img src="https://latex.codecogs.com/png.latex?k"> are random with mean 0 and variance 1, their dot product has variance <img src="https://latex.codecogs.com/png.latex?d_k">. With <img src="https://latex.codecogs.com/png.latex?d_k%20=%2064"> (the size the paper uses per head) the scores get large, and softmax becomes almost one-hot. When that happens the gradients become tiny and learning slows down. Dividing by <img src="https://latex.codecogs.com/png.latex?%5Csqrt%7Bd_k%7D"> brings the variance back to 1.</p>
</section>
<section id="the-mask-no-peeking-at-the-next-word" class="level2">
<h2 class="anchored" data-anchor-id="the-mask-no-peeking-at-the-next-word">The mask: no peeking at the next word</h2>
<p>For predicting the next word, a word can’t be allowed to look at words that come after it. Otherwise the model would just copy the answer. That’s the “Mask (opt.)” box. Before the softmax, every score above the diagonal is set to <img src="https://latex.codecogs.com/png.latex?-%5Cinfty">, and <img src="https://latex.codecogs.com/png.latex?e%5E%7B-%5Cinfty%7D%20=%200">.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://timothdev.com/posts/attention-is-matrix-multiplication/attention-weights.png" class="img-fluid figure-img"></p>
<figcaption>Attention weights after masking and softmax. Every row sums to 1 and nothing above the diagonal gets any weight. “It” can see 7 words (itself and the 6 before it) and puts 0.74 of its attention on “animal”.</figcaption>
</figure>
</div>
<p>Row 6 is the one I set up, and you can check it by hand: “animal” scores 2.83 and the other six visible words score 0, so the weight on “animal” is <img src="https://latex.codecogs.com/png.latex?e%5E%7B2.83%7D%20/%20(e%5E%7B2.83%7D%20+%206)%20=%200.74">.</p>
<p>The other rows are flat because I only gave “it” a real query. They spread their attention evenly over everything they’re allowed to see. In a trained model every row would have its own pattern.</p>
<p>This matrix is the <strong>attention matrix</strong>. I think of it as a priority table: row by row, it says how much each word should pull from every other word.</p>
</section>
<section id="so-whats-the-value" class="level2">
<h2 class="anchored" data-anchor-id="so-whats-the-value">So what’s the value?</h2>
<p>My first guess was that the key is what the word means and the value is some category the word belongs to. It’s actually the other way round:</p>
<ul>
<li>The <strong>key</strong> is a label, tuned for matching. It only needs whatever helps queries find the right word.</li>
<li>The <strong>value</strong> is the content, what actually gets handed over once the word is picked.</li>
</ul>
<p>They’re kept separate because the two jobs are different. What makes a word <em>easy to find</em> is not the same as what’s <em>useful to pass on</em>. (These descriptions are intuitions. In a real model keys and values are learned vectors without readable meanings.)</p>
<p>The last matrix multiplication, attention weights × <img src="https://latex.codecogs.com/png.latex?V">, is a weighted average. Row 6 of the output is 0.74 × value of “animal” plus 0.04 × each of the other six visible values. In my toy each value is just the word’s own features, so you can read the result directly:</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://timothdev.com/posts/attention-is-matrix-multiplication/it-output.png" class="img-fluid figure-img"></p>
<figcaption>The value vector of “it” before attention is just “pronoun”. After attention, the output for “it” is mostly “noun” (0.78) and “living” (0.74), because it pulled most of its content from “animal”.</figcaption>
</figure>
</div>
<p>Before attention, “it” was only a pronoun. After attention, its vector mostly says <em>living noun</em>. It has taken on the meaning of “animal”, and that’s what goes on to the next layer.</p>
</section>
<section id="the-whole-thing-in-code" class="level2">
<h2 class="anchored" data-anchor-id="the-whole-thing-in-code">The whole thing in code</h2>
<p>Put together, it’s about ten lines:</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="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> torch</span>
<span id="cb2-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> torch.nn <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> nn</span>
<span id="cb2-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> torch.nn.functional <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> F</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;">class</span> SelfAttention(nn.Module):</span>
<span id="cb2-6">    <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>, d_model, d_k):</span>
<span id="cb2-7">        <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">super</span>().<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>()</span>
<span id="cb2-8">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.w_q <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> nn.Linear(d_model, d_k, 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>)</span>
<span id="cb2-9">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.w_k <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> nn.Linear(d_model, d_k, 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>)</span>
<span id="cb2-10">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.w_v <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> nn.Linear(d_model, d_k, 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>)</span>
<span id="cb2-11">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.d_k <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> d_k</span>
<span id="cb2-12"></span>
<span id="cb2-13">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> forward(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, x, causal<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>
<span id="cb2-14">        Q, K, V <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>.w_q(x), <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.w_k(x), <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.w_v(x)            <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># same x, three projections</span></span>
<span id="cb2-15">        scores <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Q <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">@</span> K.transpose(<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><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> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.d_k <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.5</span>          <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># rows ask, columns answer</span></span>
<span id="cb2-16">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> causal:</span>
<span id="cb2-17">            n <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> x.size(<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>
<span id="cb2-18">            future <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.triu(torch.ones(n, n, dtype<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>torch.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">bool</span>, device<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>x.device), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb2-19">            scores <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> scores.masked_fill(future, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"-inf"</span>))      <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># no peeking ahead</span></span>
<span id="cb2-20">        weights <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> F.softmax(scores, 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="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># each row sums to 1</span></span>
<span id="cb2-21">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> weights <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">@</span> V                                          <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># weighted mix of values</span></span></code></pre></div></div>
<p>Each line matches a box in the attention diagram above, from bottom to top.</p>
</section>
<section id="what-i-take-from-this" class="level2">
<h2 class="anchored" data-anchor-id="what-i-take-from-this">What I take from this</h2>
<ol type="1">
<li><strong>It’s mostly linear algebra.</strong> Three matrix multiplications make Q, K and V. One more makes the scores, and a last one mixes the values. The only non-linear step inside the box is the softmax.</li>
<li><strong>Roles come from position, not from the layers.</strong> <code>w_q</code>, <code>w_k</code> and <code>w_v</code> start out the same. The formula decides which one ends up on the rows, which one gets transposed into columns and which one sits outside the softmax, and training does the rest.</li>
<li><strong>Rows are the askers.</strong> Softmax normalises each row and each row of the output belongs to one word, so whatever lands on the rows plays the query.</li>
</ol>
<p>Two extensions from the paper fit the same picture. <strong>Multi-head attention</strong> runs 8 of these side by side with smaller <img src="https://latex.codecogs.com/png.latex?d_k">, so each head can learn a different kind of question. In <strong>cross-attention</strong> (the middle orange box on the decoder side), the queries come from the decoder and the keys and values come from the encoder output. There the roles also differ in where their inputs come from, not just in where they sit in the formula.</p>
</section>
<section id="source" class="level2">
<h2 class="anchored" data-anchor-id="source">Source</h2>
<ul>
<li>Vaswani, Shazeer, Parmar, Uszkoreit, Jones, Gomez, Kaiser, Polosukhin. <a href="https://arxiv.org/abs/1706.03762"><em>Attention Is All You Need.</em></a> NeurIPS 2017, arXiv:1706.03762. Both diagrams in this post are from the paper.</li>
</ul>


</section>

 ]]></description>
  <category>Deep Learning</category>
  <category>NLP</category>
  <category>GenAI</category>
  <guid>https://timothdev.com/posts/attention-is-matrix-multiplication/</guid>
  <pubDate>Fri, 30 Oct 2026 00:00:00 GMT</pubDate>
  <media:content url="https://timothdev.com/posts/attention-is-matrix-multiplication/qk-scores.png" medium="image" type="image/png" height="62" width="144"/>
</item>
<item>
  <title>Diffusion Models: Destroy Slowly, Rebuild One Step at a Time</title>
  <dc:creator>Timoth Dev</dc:creator>
  <link>https://timothdev.com/posts/diffusion-original-paper/</link>
  <description><![CDATA[ 






<p>Diffusion models started with a 2015 paper, <a href="https://arxiv.org/abs/1503.03585"><em>Deep Unsupervised Learning using Nonequilibrium Thermodynamics</em></a> by Sohl-Dickstein et al.&nbsp;The abstract says the idea is to “slowly destroy structure” in the data and then learn to restore it. This post is about what that actually means.</p>
<section id="the-problem" class="level2">
<h2 class="anchored" data-anchor-id="the-problem">The problem</h2>
<p>Modelling a complex distribution like “all natural images” directly is hard. Modelling pure Gaussian noise is easy. The paper connects the two with a long chain of tiny steps, where each step is simple enough to learn.</p>
</section>
<section id="destroy-structure-slowly" class="level2">
<h2 class="anchored" data-anchor-id="destroy-structure-slowly">Destroy structure slowly</h2>
<p>Take a real image. Add a small amount of Gaussian noise. Repeat about 1,000 times.</p>
<p><img src="https://latex.codecogs.com/png.latex?%0Ax_t%20=%20%5Csqrt%7B1%20-%20%5Cbeta_t%7D%5C,%20x_%7Bt-1%7D%20+%20%5Csqrt%7B%5Cbeta_t%7D%5C,%20%5Cepsilon,%20%5Cqquad%20%5Cepsilon%20%5Csim%20%5Cmathcal%7BN%7D(0,%20I)%0A"></p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cbeta_t"> is a small number that sets how much noise goes in at step <img src="https://latex.codecogs.com/png.latex?t">. After enough steps, the image is pure static.</p>
<p><strong>Nothing is learned here.</strong> It is a fixed recipe, like ink spreading out in water.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://timothdev.com/posts/diffusion-original-paper/forward-diffusion.png" class="img-fluid figure-img"></p>
<figcaption>2,000 points on a spiral, noised step by step. By t = 200 the spiral is gone, and by t = 1000 it is plain Gaussian noise.</figcaption>
</figure>
</div>
</section>
<section id="learn-to-build-it-back" class="level2">
<h2 class="anchored" data-anchor-id="learn-to-build-it-back">Learn to build it back</h2>
<p>Undoing all the noise in one go is impossible. From pure static, too many different images are possible.</p>
<p>Undoing <em>one</em> tiny step is a different story. The paper points out that when <img src="https://latex.codecogs.com/png.latex?%5Cbeta"> is small, the reverse of a step has the same form as the forward step: also roughly Gaussian. So a neural net only has to look at <img src="https://latex.codecogs.com/png.latex?x_t"> and the step number <img src="https://latex.codecogs.com/png.latex?t">, and output the mean and variance of <img src="https://latex.codecogs.com/png.latex?x_%7Bt-1%7D">.</p>
<p>That turns a hard problem (estimating a probability distribution) into plain regression, done once per step.</p>
<p>To generate a new image:</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">x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> random_noise()</span>
<span id="cb1-2"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> t <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>(T, <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;">1</span>):</span>
<span id="cb1-3">    x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> sample(model(x, t))   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># remove one small step of noise</span></span>
<span id="cb1-4"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> x</span></code></pre></div></div>
</section>
<section id="why-not-predict-the-clean-image-directly" class="level2">
<h2 class="anchored" data-anchor-id="why-not-predict-the-clean-image-directly">Why not predict the clean image directly?</h2>
<p>From heavy noise, many clean images fit. A single prediction averages them, and the result is a blurry mush. A small step commits only a little, so the structure appears gradually across the whole chain.</p>
</section>
<section id="does-training-walk-through-all-1000-steps" class="level2">
<h2 class="anchored" data-anchor-id="does-training-walk-through-all-1000-steps">Does training walk through all 1,000 steps?</h2>
<p>No.&nbsp;Training picks a random image and a random <img src="https://latex.codecogs.com/png.latex?t">, noises the image to level <img src="https://latex.codecogs.com/png.latex?t">, and teaches the net to undo that one step. It learns every noise level at once. The 1,000 steps in a row only happen at generation time.</p>
</section>
<section id="is-this-just-a-vae" class="level2">
<h2 class="anchored" data-anchor-id="is-this-just-a-vae">Is this just a VAE?</h2>
<p>Close, but the encoder is fixed instead of learned. The <a href="../../posts/vae-and-svd/index.html">VAE post</a> covers the VAE side.</p>
<table class="caption-top table">
<thead>
<tr class="header">
<th></th>
<th>VAE</th>
<th>Diffusion (2015)</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Encoder</td>
<td>Learned</td>
<td>Fixed noise process</td>
</tr>
<tr class="even">
<td>Latent size</td>
<td>Smaller than the input</td>
<td>Same as the input</td>
</tr>
<tr class="odd">
<td>Latent layers</td>
<td>1 or a few</td>
<td>About 1,000</td>
</tr>
<tr class="even">
<td>Decoder</td>
<td>One pass</td>
<td>The denoiser, once per step</td>
</tr>
<tr class="odd">
<td>Objective</td>
<td>ELBO</td>
<td>Also an ELBO-style bound</td>
</tr>
</tbody>
</table>
<p>Fixing the encoder was deliberate. Training the encoder is a known pain point in VAEs, so the paper keeps the forward process simple enough that the reverse has the same form.</p>
<p>Diffusion is also like a denoising autoencoder: corrupt the input, train the net to clean it. A denoising autoencoder uses one noise level. Diffusion uses many, from barely noisy to pure static, and <img src="https://latex.codecogs.com/png.latex?t"> tells the net which one it is at. That range is what lets it start from pure noise and get all the way back to an image.</p>
<p>In one line: <strong>diffusion is a hierarchical VAE with a fixed noise encoder, trained like a denoising autoencoder at many noise levels.</strong></p>
</section>
<section id="what-came-after" class="level2">
<h2 class="anchored" data-anchor-id="what-came-after">What came after</h2>
<p>The 2015 paper worked, but the samples were not great. <a href="https://arxiv.org/abs/2006.11239">DDPM</a> (Ho et al., 2020) kept the same idea, had the net predict the added noise <img src="https://latex.codecogs.com/png.latex?%5Cepsilon"> instead, and used a U-Net. That version led to Stable Diffusion and similar models. Latent diffusion adds compression back, but as a separate step: a VAE first shrinks the image, and diffusion runs in that smaller space.</p>
</section>
<section id="source" class="level2">
<h2 class="anchored" data-anchor-id="source">Source</h2>
<ul>
<li>Sohl-Dickstein, Weiss, Maheswaranathan, Ganguli. <a href="https://arxiv.org/abs/1503.03585"><em>Deep Unsupervised Learning using Nonequilibrium Thermodynamics.</em></a> ICML 2015, arXiv:1503.03585.</li>
<li>The figure uses a linear <img src="https://latex.codecogs.com/png.latex?%5Cbeta"> schedule from 0.0001 to 0.02 over 1,000 steps. These are DDPM’s values, chosen for illustration, not the 2015 paper’s.</li>
</ul>


</section>

 ]]></description>
  <category>Deep Learning</category>
  <category>GenAI</category>
  <category>Machine Learning</category>
  <guid>https://timothdev.com/posts/diffusion-original-paper/</guid>
  <pubDate>Thu, 29 Oct 2026 00:00:00 GMT</pubDate>
  <media:content url="https://timothdev.com/posts/diffusion-original-paper/forward-diffusion.png" medium="image" type="image/png" height="33" width="144"/>
</item>
<item>
  <title>Next-Concept Modeling: Writing a Sentence Coarse-to-Fine</title>
  <dc:creator>Timoth Dev</dc:creator>
  <link>https://timothdev.com/posts/next-concept-modeling/</link>
  <description><![CDATA[ 






<p>This continues my last two posts. In <a href="../../posts/vae-and-svd/index.html">VAE vs SVD</a> I compressed data into a few learned numbers. In <a href="../../posts/vq-vae/index.html">VQ-VAE</a> those numbers became integers from a learned codebook, so an image turns into a grid of tokens that a second model can generate.</p>
<p><a href="https://arxiv.org/abs/2610.14162">Next-Concept Modeling</a> (NCM), a new paper from Stanford and Together AI, takes that idea back to text. It asks: why does an LLM have to write one token at a time?</p>
<section id="the-problem-one-token-per-pass" class="level2">
<h2 class="anchored" data-anchor-id="the-problem-one-token-per-pass">The problem: one token per pass</h2>
<p>An LLM produces a 48-token answer in 48 forward passes, and each pass reads all the model’s weights from memory again. Google’s <a href="https://research.google/blog/looking-back-at-speculative-decoding/">speculative decoding post</a> puts numbers on why that hurts: accelerators can do hundreds of operations per byte they read, but a transformer during decoding needs only about 10. Most of the compute waits on memory.</p>
<p>NCM writes the way you’d draw a face: outline first, then detail everywhere at once.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://timothdev.com/posts/next-concept-modeling/passes-ar-vs-ncm.png" class="img-fluid figure-img"></p>
<figcaption>Top: an autoregressive model produces one token per forward pass. Bottom: NCM produces one level per pass. The first level has a few codes covering the whole sentence (the gist), and every later level adds detail across the whole sentence in parallel.</figcaption>
</figure>
</div>
<p>The paper calls the information in the coarse levels a <em>concept</em>, which is where the name comes from: predict the next concept, not the next token.</p>
<p>So how do you get levels that go from gist to detail? With a VQ-VAE where the codebooks are stacked.</p>
</section>
<section id="stage-1-stack-the-codebooks" class="level2">
<h2 class="anchored" data-anchor-id="stage-1-stack-the-codebooks">Stage 1: stack the codebooks</h2>
<section id="residual-quantise-whats-left-over" class="level3">
<h3 class="anchored" data-anchor-id="residual-quantise-whats-left-over">Residual: quantise what’s left over</h3>
<p>In the VQ-VAE post, one codebook of 8 vectors described the arc with an error of 0.040. Residual quantisation does it in rounds instead:</p>
<ol type="1">
<li>Snap each point to the nearest of 4 codes.</li>
<li>Look at what’s <strong>left over</strong> (the point minus its code), and snap that to the nearest of another 4 codes.</li>
<li>Repeat with the new leftover.</li>
</ol>
<p>Same arc, same 400 points:</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://timothdev.com/posts/next-concept-modeling/residual-vq-arc.png" class="img-fluid figure-img"></p>
<figcaption>Residual quantisation with 3 levels of 4 codes each. Level 1 gives a rough position, and each later level corrects what the previous ones missed. The error drops from 0.111 to 0.034 to 0.010.</figcaption>
</figure>
</div>
<p>Each level is a small correction on top of the levels before it. Level 1 alone is rough, but it already tells you roughly <em>where</em> the point is. After three levels, each point is stored as 3 integers (6 bits) and the error is 0.010. That’s a quarter of what 8 codes managed in the VQ-VAE post.</p>
<p>This is the key property NCM needs: <strong>the early codes are the gist, and the later codes are detail.</strong></p>
</section>
<section id="multiscale-early-levels-are-also-short" class="level3">
<h3 class="anchored" data-anchor-id="multiscale-early-levels-are-also-short">Multiscale: early levels are also short</h3>
<p>For text, NCM adds one more thing. Early levels don’t just carry less detail, they also have <strong>fewer positions</strong>. In my toy version (below), a 48-character sentence is described by:</p>
<ul>
<li><strong>Level 1:</strong> 3 codes for the whole sentence, so roughly <em>what it’s about</em>.</li>
<li><strong>Levels 2 to 4:</strong> 6, 12 and 24 codes, each storing what the earlier levels missed.</li>
<li><strong>Level 5:</strong> 48 codes, one per position, enough to rebuild the exact text.</li>
</ul>
<p>That’s the grid in the first figure. NCM learns this tokenizer, a <strong>multiscale residual VQ-VAE</strong>, before anything else.</p>
<p>One training trick makes the early levels useful. With <strong>nested dropout</strong>, training randomly keeps only the first few levels and drops the rest. The decoder has to make the best of whatever it gets, so the coarse levels are forced to carry real information. Otherwise the model could leave everything to the last level.</p>
<p>The paper’s tokenizer is close to lossless. 99.99% of tokens come back exactly on OpenWebText, 99.86% on LM1B and 100% on Sudoku boards.</p>
</section>
</section>
<section id="stage-2-generate-one-level-per-pass" class="level2">
<h2 class="anchored" data-anchor-id="stage-2-generate-one-level-per-pass">Stage 2: generate one level per pass</h2>
<p>In the VQ-VAE post, the second stage was a model that generates the code grid. NCM does the same, but <strong>level by level instead of token by token</strong>:</p>
<ol type="1">
<li>Start with nothing and predict all the codes of level 1 in <strong>one</strong> forward pass.</li>
<li>Add them to the reconstruction.</li>
<li>Look at the reconstruction so far and predict <strong>all</strong> the codes of level 2 in one pass.</li>
<li>Repeat until the last level, then decode to text.</li>
</ol>
<p>The number of passes is the number of levels, not the number of tokens. And early passes are cheap, since level 1 has only a handful of positions.</p>
<p>One more trick is <em>conditioning corruption</em>. During training, some of the earlier-level codes the generator conditions on are swapped for random ones. At generation time, the model then copes better with its own mistakes from earlier levels.</p>
<p>The example I found most intuitive is the paper’s translation one. After step 1 the output is mush: <em>“However, it is a important to the the the and the.”</em> By step 6 it has the right shape. By step 11 it matches the reference. The coarse steps decide what to say and the fine steps fix the words.</p>
</section>
<section id="does-it-work" class="level2">
<h2 class="anchored" data-anchor-id="does-it-work">Does it work?</h2>
<p>The main experiments use models of about 100M parameters, so this is a research result, not a new LLM. Most comparisons are against <strong>diffusion language models</strong>, which also write in parallel but need many passes over the full sequence.</p>
<ul>
<li><strong>LM1B:</strong> better text quality than the best diffusion model (DUO), <strong>21× faster</strong>.</li>
<li><strong>Summarisation (XSum):</strong> ROUGE-L 28.0 with 8 passes, against 26.6 for the best diffusion baseline at 128 passes. About <strong>31× faster</strong>.</li>
<li><strong>Translation (WMT14 German→English):</strong> BLEU 22.6 with 11 passes, behind the best diffusion model (24.8) and a normal autoregressive model (25.2). Generating several candidates and picking the best (MBR decoding) brings NCM to 25.2.</li>
<li><strong>Training cost:</strong> on LM1B, about 4.9× fewer training tokens than the baselines, with lower perplexity.</li>
</ul>
<p>Sudoku is where coarse-to-fine helps most. A later level can fix a mistake an earlier level made. An autoregressive model commits to each cell and can never go back.</p>
<table class="caption-top table">
<caption>Percent of Sudoku boards solved completely. Numbers from the paper.</caption>
<thead>
<tr class="header">
<th>Method</th>
<th>Easy</th>
<th>Medium</th>
<th>Hard</th>
<th>Passes</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Autoregressive (greedy)</td>
<td>14.6</td>
<td>5.1</td>
<td>1.0</td>
<td>128</td>
</tr>
<tr class="even">
<td>DUO (diffusion)</td>
<td>96.3</td>
<td>84.7</td>
<td>58.4</td>
<td>128</td>
</tr>
<tr class="odd">
<td>FMLM+ (strongest baseline)</td>
<td>97.7</td>
<td>92.8</td>
<td>81.3</td>
<td>16</td>
</tr>
<tr class="even">
<td><strong>NCM</strong></td>
<td><strong>99.5</strong></td>
<td><strong>96.5</strong></td>
<td><strong>86.1</strong></td>
<td><strong>12</strong></td>
</tr>
</tbody>
</table>
<p>The authors also list the limits. Every output goes through all levels even if it’s short. The tokenizer and generator are trained separately. Scaling is only shown up to 725M parameters. And there are occasional glitches between coarse levels.</p>
</section>
<section id="a-toy-version-you-can-run" class="level2">
<h2 class="anchored" data-anchor-id="a-toy-version-you-can-run">A toy version you can run</h2>
<p>I wrote a small version to see the mechanism for myself. It trains in a few minutes on CPU or a free Colab GPU, on made-up sentences like <em>“the happy fox slept under the tree.”</em>, with levels of 3, 6, 12, 24 and 48 codes.</p>
<p><a href="https://colab.research.google.com/github/Zilch123/ncm-notes/blob/main/NCM_toy_walkthrough.ipynb" class="btn btn-outline-secondary">Open the notebook in Colab</a> <a href="https://github.com/Zilch123/ncm-notes/blob/main/NCM_toy_walkthrough.ipynb" class="btn btn-outline-secondary">View it on GitHub</a></p>
<p>The generation loop is the whole idea in a few lines, with one forward pass per level:</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"><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> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.levels)):</span>
<span id="cb1-2">    idx <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> sample(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.forward_level(x, k), temperature, top_k)   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># all positions of level k at once</span></span>
<span id="cb1-3">    z_hat <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>.rvq.add_level(z_hat, idx, k)                    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># add this level's detail</span></span>
<span id="cb1-4">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> k <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;">&lt;</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.levels):</span>
<span id="cb1-5">        x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> down(z_hat, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.levels[k <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="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># the next "concept"</span></span></code></pre></div></div>
<p>The notebook decodes the sentence after each level, so you can watch it come into focus. It’s a toy, so it says nothing about real language, but it shows the mechanism clearly.</p>
</section>
<section id="what-i-take-from-this" class="level2">
<h2 class="anchored" data-anchor-id="what-i-take-from-this">What I take from this</h2>
<p>The chain from these three posts is shorter than I expected. SVD compresses with straight axes. A VAE learns curved ones. A VQ-VAE turns them into tokens. Stack the codebooks from coarse to fine, and you can generate a sentence the way you’d draw a face, in a few passes instead of one per token.</p>
<p>The idea itself isn’t new for images. Next-scale prediction (<a href="https://arxiv.org/abs/2404.02905">VAR</a>) already does this, because shrinking an image gives you a natural coarse version. Text has no obvious way to shrink, so NCM has to learn its levels. That’s what the multiscale residual VQ-VAE is for.</p>
<p>It’s early and small-scale. But it questions the one-token-per-pass habit in a way that’s easy to picture.</p>
</section>
<section id="sources" class="level2">
<h2 class="anchored" data-anchor-id="sources">Sources</h2>
<ul>
<li>Kumbong, Khare, et al.&nbsp;<a href="https://arxiv.org/abs/2610.14162"><em>Next-Concept Modeling: Fast, Parallel Coarse-to-Fine Text Generation.</em></a> arXiv:2610.14162, Oct 2026. Code: <a href="https://github.com/HazyResearch/ncm">HazyResearch/ncm</a>.</li>
<li>van den Oord, Vinyals, Kavukcuoglu. <a href="https://arxiv.org/abs/1711.00937"><em>Neural Discrete Representation Learning.</em></a> NeurIPS 2017.</li>
<li>Tian, Jiang, Yuan, Peng, Wang. <a href="https://arxiv.org/abs/2404.02905"><em>Visual Autoregressive Modeling: Scalable Image Generation via Next-Scale Prediction.</em></a> arXiv:2404.02905, 2024.</li>
<li>Leviathan, Kalman, Matias. <a href="https://research.google/blog/looking-back-at-speculative-decoding/"><em>Looking back at speculative decoding.</em></a> Google Research blog, Dec 2024.</li>
<li>My notes and toy notebook: <a href="https://github.com/Zilch123/ncm-notes">Zilch123/ncm-notes</a>.</li>
</ul>


</section>

 ]]></description>
  <category>GenAI</category>
  <category>NLP</category>
  <category>Machine Learning</category>
  <guid>https://timothdev.com/posts/next-concept-modeling/</guid>
  <pubDate>Tue, 27 Oct 2026 00:00:00 GMT</pubDate>
  <media:content url="https://timothdev.com/posts/next-concept-modeling/passes-ar-vs-ncm.png" medium="image" type="image/png" height="68" width="144"/>
</item>
<item>
  <title>VQ-VAE: Giving a VAE a Vocabulary</title>
  <dc:creator>Timoth Dev</dc:creator>
  <link>https://timothdev.com/posts/vq-vae/</link>
  <description><![CDATA[ 






<p>In my <a href="../../posts/vae-and-svd/index.html">last post on VAEs</a>, I went from SVD to a VAE step by step: straight axes, then curved axes, then a latent space packed into a Gaussian so you can sample from it. Every latent there is a list of real numbers.</p>
<p>LLMs work differently. They predict the next token from a fixed vocabulary, and each token is just an integer. So I wondered: what if the latent of a VAE were a token too? Could an image become a grid of integers, so it could be generated the same way text is?</p>
<p>That’s what a <strong>VQ-VAE</strong> (vector-quantised VAE, <a href="https://arxiv.org/abs/1711.00937">van den Oord et al., 2017</a>) does.</p>
<section id="how-i-picture-it-xgboost" class="level2">
<h2 class="anchored" data-anchor-id="how-i-picture-it-xgboost">How I picture it: XGBoost</h2>
<p>XGBoost makes a rough guess, looks at the error that’s left (the residual), and fits the next tree to that error. Round after round, the error shrinks.</p>
<p>A VQ-VAE encoder feels similar to me. It outputs a vector, and that vector is compared with its nearest entry in a <strong>codebook</strong>, a learned list of vectors. The gap between the two is a residual. Each training step uses it to nudge the encoder, along with the error in the rebuilt image, and the outputs settle close to the codebook. With squared error, this link is direct: the gradient is just the residual times 2.</p>
<p>The analogy has a limit. XGBoost adds a new tree each round and keeps the old ones fixed. A plain VQ-VAE has one encoder and updates its weights in place, and the codebook moves too. The closer match to boosting is the residual VQ-VAE at the end of this post, which stacks codebooks, each one fitting what the last one left behind.</p>
</section>
<section id="the-one-change-snap-to-a-codebook" class="level2">
<h2 class="anchored" data-anchor-id="the-one-change-snap-to-a-codebook">The one change: snap to a codebook</h2>
<p>A VQ-VAE keeps the encoder and decoder. It adds a <strong>codebook</strong>: a list of <img src="https://latex.codecogs.com/png.latex?K"> learned vectors, each with an index from 0 to <img src="https://latex.codecogs.com/png.latex?K-1">.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://timothdev.com/posts/vq-vae/vq-vae-diagram.png" class="img-fluid figure-img"></p>
<figcaption>The VQ-VAE pipeline. The encoder outputs a vector per position. Each one is replaced by its nearest codebook vector, so what’s stored is a grid of integers. The decoder rebuilds the input from the codebook vectors.</figcaption>
</figure>
</div>
<ol type="1">
<li>The encoder turns the input into a grid of vectors, <img src="https://latex.codecogs.com/png.latex?z_e">.</li>
<li>Each vector is replaced by the <strong>closest</strong> vector in the codebook. All you need to store is which one, an integer.</li>
<li>Those codebook vectors, <img src="https://latex.codecogs.com/png.latex?z_q">, go to the decoder, which rebuilds the input.</li>
</ol>
<p>The codebook is a vocabulary that the model learns by itself. The middle grid of integers is the “sentence” that describes the image.</p>
</section>
<section id="the-arc-again" class="level2">
<h2 class="anchored" data-anchor-id="the-arc-again">The arc again</h2>
<p>Here’s the same 2D arc from the VAE post (the same 400 points), this time with a codebook of 8 vectors. Each point is stored as just one integer from 0 to 7:</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://timothdev.com/posts/vq-vae/arc-codebook.png" class="img-fluid figure-img"></p>
<figcaption>The arc from the VAE post described by 8 codebook vectors (stars). Each point is replaced by its nearest code.</figcaption>
</figure>
</div>
<p>Each point is described with very little information in all three methods, but in different ways:</p>
<table class="caption-top table">
<thead>
<tr class="header">
<th>Method</th>
<th>What stores one point</th>
<th>Error</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>SVD</td>
<td>1 real number, along a straight line</td>
<td>0.129</td>
</tr>
<tr class="even">
<td>Autoencoder</td>
<td>1 real number, along a learned curve</td>
<td>0.006</td>
</tr>
<tr class="odd">
<td>Vector quantisation</td>
<td>1 integer out of 8 (3 bits)</td>
<td>0.040</td>
</tr>
</tbody>
</table>
<p>The SVD connection carries on, just in a different form. SVD gives you a few <strong>directions</strong> and stores how far along each one you are. A codebook gives you a few <strong>points</strong> and stores which one you’re nearest to. If that sounds like k-means, it is. The codebook is basically k-means clustering that runs inside the network and gets learned together with the encoder. (For this figure I literally ran k-means.)</p>
</section>
<section id="two-problems-two-small-tricks" class="level2">
<h2 class="anchored" data-anchor-id="two-problems-two-small-tricks">Two problems, two small tricks</h2>
<p><strong>Problem 1: “nearest” has no gradient.</strong> Picking the closest code is an argmin, so a tiny change to the encoder output usually changes nothing, and when it does, the output jumps. Backprop can’t get through that.</p>
<p>The fix is the <strong>straight-through estimator</strong>. On the forward pass, use the snapped vector. On the backward pass, pretend the snapping never happened and copy the decoder’s gradient straight back to the encoder (the dashed red arrow in the diagram). In PyTorch it’s one line:</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">z_q <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> z_e <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> (z_q <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> z_e).detach()   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># forward: z_q, backward: gradient flows to z_e</span></span></code></pre></div></div>
<p><strong>Problem 2: the codebook gets no gradient either</strong>, because of that same shortcut. So the loss gets two extra terms that pull the codes and the encoder outputs towards each other:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cmathcal%7BL%7D%20=%20%5Cunderbrace%7B%5ClVert%20x%20-%20%5Chat%7Bx%7D%20%5CrVert%5E2%7D_%7B%5Ctext%7Breconstruction%7D%7D%20+%20%5Cunderbrace%7B%5ClVert%20%5Ctext%7Bsg%7D%5Bz_e%5D%20-%20e%20%5CrVert%5E2%7D_%7B%5Ctext%7Bmove%20codes%20to%20encoder%20outputs%7D%7D%20+%20%5Cbeta%5C,%5Cunderbrace%7B%5ClVert%20z_e%20-%20%5Ctext%7Bsg%7D%5Be%5D%20%5CrVert%5E2%7D_%7B%5Ctext%7Bkeep%20the%20encoder%20near%20its%20code%7D%7D%0A"></p>
<p><img src="https://latex.codecogs.com/png.latex?%5Ctext%7Bsg%7D"> means stop-gradient (<code>.detach()</code>), so each term moves only one side. The second term moves each code towards the encoder outputs assigned to it, which is the k-means update again. The third, the <em>commitment</em> loss, stops the encoder outputs from drifting away from the codes. The paper uses <img src="https://latex.codecogs.com/png.latex?%5Cbeta%20=%200.25">.</p>
<p>The whole quantiser is a few lines:</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">dist <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.cdist(z_e, codebook)                 <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># distance to every code</span></span>
<span id="cb2-2">idx <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> dist.argmin(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="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># the integers we store</span></span>
<span id="cb2-3">z_q <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> codebook[idx]</span>
<span id="cb2-4">loss <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> ((z_e.detach() <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> z_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;">2</span>).mean() <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.25</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> ((z_e <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> z_q.detach()) <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>).mean()</span>
<span id="cb2-5">z_q <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> z_e <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> (z_q <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> z_e).detach()                  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># straight-through</span></span></code></pre></div></div>
</section>
<section id="where-did-the-kl-term-go" class="level2">
<h2 class="anchored" data-anchor-id="where-did-the-kl-term-go">Where did the KL term go?</h2>
<p>In the VAE post, the KL term was what made sampling possible. Here it’s gone. The paper’s reasoning: the encoder picks exactly one code, and if the prior is uniform over <img src="https://latex.codecogs.com/png.latex?K"> codes, the KL works out to the constant <img src="https://latex.codecogs.com/png.latex?%5Clog%20K">. A constant has no gradient, so it’s dropped.</p>
<p>So how do you generate? In two stages:</p>
<ol type="1">
<li>Train the VQ-VAE. Now every image has a grid of integers.</li>
<li>Train a <em>second</em> model to generate those integer grids, the same way a language model generates tokens. The paper used a PixelCNN. Today it’s often a transformer (<a href="../../posts/attention-is-matrix-multiplication/index.html">which is mostly matrix multiplication</a>).</li>
</ol>
<p>Sample a grid of integers, look up the codes, decode, and you get a new image.</p>
<p>This is what made VQ-VAE so useful. Images become sequences of tokens. In the paper, 128×128 colour ImageNet images become 32×32 grids of codes with <img src="https://latex.codecogs.com/png.latex?K%20=%20512">, about 42.6× fewer bits, and the decoder can still rebuild them.</p>
</section>
<section id="next-next-concept-modeling" class="level2">
<h2 class="anchored" data-anchor-id="next-next-concept-modeling">Next: Next-Concept Modeling</h2>
<p>Next-Concept Modeling (NCM) is built on a variant called a <strong>multiscale residual VQ-VAE</strong>. <em>Residual</em> means you quantise, look at what’s left over, and quantise that again with another codebook, as many times as you like. <em>Multiscale</em> means the first levels use very few codes for the gist and later levels use more for the detail. That coarse-to-fine stack is what lets NCM write a whole sentence in a few passes, and it’s the topic of <a href="../../posts/next-concept-modeling/index.html">the next post</a>.</p>
</section>
<section id="sources" class="level2">
<h2 class="anchored" data-anchor-id="sources">Sources</h2>
<ul>
<li>van den Oord, Vinyals, Kavukcuoglu. <a href="https://arxiv.org/abs/1711.00937"><em>Neural Discrete Representation Learning.</em></a> NeurIPS 2017, arXiv:1711.00937.</li>
<li>Bengio, Léonard, Courville. <a href="https://arxiv.org/abs/1308.3432"><em>Estimating or Propagating Gradients Through Stochastic Neurons for Conditional Computation.</em></a> arXiv:1308.3432, 2013. (The straight-through estimator.)</li>
</ul>


</section>

 ]]></description>
  <category>Deep Learning</category>
  <category>GenAI</category>
  <category>Machine Learning</category>
  <guid>https://timothdev.com/posts/vq-vae/</guid>
  <pubDate>Sun, 25 Oct 2026 00:00:00 GMT</pubDate>
  <media:content url="https://timothdev.com/posts/vq-vae/vq-vae-diagram.png" medium="image" type="image/png" height="59" width="144"/>
</item>
<item>
  <title>A VAE Is a Learnable, Curved SVD (Almost)</title>
  <dc:creator>Timoth Dev</dc:creator>
  <link>https://timothdev.com/posts/vae-and-svd/</link>
  <description><![CDATA[ 






<p>While reading about variational autoencoders (VAEs), I noticed that the setup sounds a lot like SVD. You take the training data, squeeze it into a small number of values, expand it back, and penalise the model when the result doesn’t match the input. That’s what a truncated SVD does too. The difference is that a VAE <em>learns</em> how to do it.</p>
<p>The idea holds up, with one correction. A neural network doesn’t learn basis vectors the way SVD finds them. It learns something closer to a curved coordinate system. The clearest way I found to see this is to start at SVD and change one thing at a time until you arrive at a VAE.</p>
<section id="step-1-svd-changes-the-basis" class="level2">
<h2 class="anchored" data-anchor-id="step-1-svd-changes-the-basis">Step 1: SVD changes the basis</h2>
<p>Every data point is a list of numbers in some basis. For a 28×28 image that’s 784 pixel values, one per pixel axis. SVD finds a better set of axes for the same data:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0AX%20%5Capprox%20U_k%20%5CSigma_k%20V_k%5E%5Ctop%0A"></p>
<p>The rows of <img src="https://latex.codecogs.com/png.latex?V_k%5E%5Ctop"> are the new axes (the right singular vectors). They are orthogonal and sorted by how much of the data’s variation they explain. Keep the top <img src="https://latex.codecogs.com/png.latex?k"> and drop the rest.</p>
<p>Read it as an encoder and a decoder:</p>
<ul>
<li><strong>Encode:</strong> <img src="https://latex.codecogs.com/png.latex?z%20=%20V_k%5E%5Ctop%20x">. Project the 784 numbers onto <img src="https://latex.codecogs.com/png.latex?k"> axes and keep <img src="https://latex.codecogs.com/png.latex?k"> numbers.</li>
<li><strong>Decode:</strong> <img src="https://latex.codecogs.com/png.latex?%5Chat%7Bx%7D%20=%20V_k%20z">. Rebuild the image from those <img src="https://latex.codecogs.com/png.latex?k"> numbers.</li>
</ul>
<p>The Eckart–Young theorem says no other rank-<img src="https://latex.codecogs.com/png.latex?k"> linear map gets a smaller squared reconstruction error. So SVD is the best possible compression, <em>as long as the axes have to be straight</em>. Nothing is trained here. The axes come straight out of a matrix factorisation.</p>
</section>
<section id="step-2-a-linear-autoencoder-learns-the-same-thing" class="level2">
<h2 class="anchored" data-anchor-id="step-2-a-linear-autoencoder-learns-the-same-thing">Step 2: a linear autoencoder learns the same thing</h2>
<p>Now build a tiny neural network with no activation functions: one linear layer down to <img src="https://latex.codecogs.com/png.latex?k"> numbers, one linear layer back up, trained with squared error.</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">encoder <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> nn.Linear(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">784</span>, k, 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>)</span>
<span id="cb1-2">decoder <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> nn.Linear(k, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">784</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>)</span>
<span id="cb1-3"></span>
<span id="cb1-4">x_hat <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> decoder(encoder(x))</span>
<span id="cb1-5">loss <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> ((x_hat <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> 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;">2</span>).<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</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>).mean()</span></code></pre></div></div>
<p>Baldi and Hornik showed in 1989 that the best solution for this network spans the same subspace as the top <img src="https://latex.codecogs.com/png.latex?k"> singular vectors. Gradient descent rediscovers SVD.</p>
<p>So “SVD, but learnable” is literally true at this step. There’s one small difference: the learned axes don’t have to be orthogonal or sorted. Any mix of the top <img src="https://latex.codecogs.com/png.latex?k"> directions reconstructs equally well, so the network lands on one of them. It finds the same flat subspace but without SVD’s neat ordering.</p>
</section>
<section id="step-3-add-nonlinearity-and-the-axes-bend" class="level2">
<h2 class="anchored" data-anchor-id="step-3-add-nonlinearity-and-the-axes-bend">Step 3: add nonlinearity and the axes bend</h2>
<p>Add activation functions and a few hidden layers, and the encoder and decoder can now bend. This is a plain autoencoder.</p>
<p>To see what that buys, I made a toy dataset: 2D points scattered along an arc. Both methods get to describe each point with <strong>one number</strong>.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://timothdev.com/posts/vae-and-svd/svd-vs-autoencoder.png" class="img-fluid figure-img"></p>
<figcaption>Left: SVD keeps one straight axis, and every point gets projected onto it. Right: an autoencoder with a 1-number bottleneck learns a curve that follows the data. The grey lines connect each point to its reconstruction.</figcaption>
</figure>
</div>
<p>SVD’s best single axis is a straight line through the middle of the arc, so the ends get reconstructed badly. The autoencoder’s single number moves you <em>along the arc</em>. Mean squared error drops from 0.129 to 0.006.</p>
<p>This is where “learns a basis” stops being literal. A nonlinear decoder has no fixed basis vectors. Moving the latent number traces out a curve, and with <img src="https://latex.codecogs.com/png.latex?k"> latent numbers it traces a curved <img src="https://latex.codecogs.com/png.latex?k">-dimensional surface inside the data space. If you zoom in far enough, any small patch of that surface looks flat, and there you get local axes again. But they change from place to place.</p>
<p>So the better picture is: <strong>SVD lays a straight grid over the data, and an autoencoder learns a bent one from the training examples.</strong></p>
</section>
<section id="step-4-why-a-plain-autoencoder-cant-generate" class="level2">
<h2 class="anchored" data-anchor-id="step-4-why-a-plain-autoencoder-cant-generate">Step 4: why a plain autoencoder can’t generate</h2>
<p>If compression were the only goal, we could stop at step 3. But a VAE exists to <em>generate</em> new data: pick a point in the latent space, decode it, get a new image.</p>
<p>A plain autoencoder is bad at this. Nothing in its loss says where the codes should go. It can scatter the training points across the latent space with big gaps between them. Pick a random point in a gap and the decoder has never seen anything like it, so you get noise.</p>
<p>(The linear case has a fix too. Probabilistic PCA, from Tipping and Bishop, turns SVD into a model you can sample from by adding Gaussian noise. A VAE plays the same role for the curved version.)</p>
</section>
<section id="step-5-the-vae-adds-one-penalty" class="level2">
<h2 class="anchored" data-anchor-id="step-5-the-vae-adds-one-penalty">Step 5: the VAE adds one penalty</h2>
<p>A VAE changes two things.</p>
<p><strong>1. The encoder outputs a small cloud instead of a point.</strong> For each input it predicts a mean <img src="https://latex.codecogs.com/png.latex?%5Cmu"> and a spread <img src="https://latex.codecogs.com/png.latex?%5Csigma"> per latent number, and the decoder gets a random sample from that cloud:</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">h <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> encoder(x)</span>
<span id="cb2-2">mu, log_var <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> to_mu(h), to_log_var(h)</span>
<span id="cb2-3">z <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> mu <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> torch.exp(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> log_var) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> torch.randn_like(mu)   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># sample near mu</span></span>
<span id="cb2-4">x_hat <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> decoder(z)</span></code></pre></div></div>
<p>Writing the sample as <code>mu + sigma * noise</code> (the reparameterisation trick) keeps it differentiable, so normal backprop still works.</p>
<p><strong>2. The loss gets a second term.</strong></p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cmathcal%7BL%7D%20=%20%5Cunderbrace%7B%5ClVert%20x%20-%20%5Chat%7Bx%7D%20%5CrVert%5E2%7D_%7B%5Ctext%7Breconstruction%7D%7D%20+%20%5Cunderbrace%7B%5Cmathrm%7BKL%7D%5Cbig(%5Cmathcal%7BN%7D(%5Cmu,%20%5Csigma%5E2)%20%5C,%5C%7C%5C,%20%5Cmathcal%7BN%7D(0,%20I)%5Cbig)%7D_%7B%5Ctext%7Bstay%20near%20a%20standard%20Gaussian%7D%7D%0A"></p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1">recon <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> ((x_hat <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> 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;">2</span>).<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</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>
<span id="cb3-2">kl <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="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</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;">1</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> log_var <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> mu.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">pow</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> log_var.exp()).<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</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>
<span id="cb3-3">loss <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (recon <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> kl).mean()</span></code></pre></div></div>
<p>The two terms pull in opposite directions:</p>
<ul>
<li><strong>Reconstruction</strong> wants each input to have its own sharp, separate code.</li>
<li><strong>KL</strong> wants every cloud to be wide and centred at zero, like a standard bell curve.</li>
</ul>
<p>The result is a compromise. Codes are packed close together around zero, and the clouds overlap. Since the decoder is trained on random samples from these clouds, it has to give sensible outputs for every point in the region, not just the exact training codes. The gaps from step 4 get filled in.</p>
<p>Two things follow:</p>
<ul>
<li><strong>Sampling works.</strong> Draw <img src="https://latex.codecogs.com/png.latex?z"> from a standard Gaussian, decode it, and you land in a part of the space the decoder knows.</li>
<li><strong>Interpolation works.</strong> Walk in a straight line between the codes of two images and the decoded images change smoothly from one to the other.</li>
</ul>
</section>
<section id="the-ladder-in-one-table" class="level2">
<h2 class="anchored" data-anchor-id="the-ladder-in-one-table">The ladder in one table</h2>
<table class="caption-top table">
<colgroup>
<col style="width: 20%">
<col style="width: 20%">
<col style="width: 20%">
<col style="width: 20%">
<col style="width: 20%">
</colgroup>
<thead>
<tr class="header">
<th></th>
<th>SVD</th>
<th>Linear autoencoder</th>
<th>Autoencoder</th>
<th>VAE</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Axes</td>
<td>Straight</td>
<td>Straight</td>
<td>Curved</td>
<td>Curved</td>
</tr>
<tr class="even">
<td>How they’re found</td>
<td>Matrix factorisation</td>
<td>Gradient descent</td>
<td>Gradient descent</td>
<td>Gradient descent</td>
</tr>
<tr class="odd">
<td>Code for one input</td>
<td>A point</td>
<td>A point</td>
<td>A point</td>
<td>A small Gaussian cloud</td>
</tr>
<tr class="even">
<td>Loss</td>
<td>(none, it’s exact)</td>
<td>Reconstruction</td>
<td>Reconstruction</td>
<td>Reconstruction + KL</td>
</tr>
<tr class="odd">
<td>Can generate new data</td>
<td>No</td>
<td>No</td>
<td>Badly</td>
<td>Yes</td>
</tr>
</tbody>
</table>
</section>
<section id="where-the-analogy-breaks" class="level2">
<h2 class="anchored" data-anchor-id="where-the-analogy-breaks">Where the analogy breaks</h2>
<p>The SVD picture helped me a lot, but a few things don’t carry over:</p>
<ul>
<li><strong>No ranking.</strong> SVD tells you which axis matters most. VAE latent dimensions come in no particular order, and some can end up unused.</li>
<li><strong>No unique answer.</strong> SVD always gives the same result for the same data. A VAE depends on initialisation, architecture and training, and different runs give different latent spaces.</li>
<li><strong>No guarantee of the best fit.</strong> Eckart–Young proves SVD is optimal among straight-axis methods. A VAE is only as good as its training.</li>
<li><strong>VAE outputs are often blurry.</strong> The KL term trades some reconstruction quality for a well-organised latent space. That’s the price of being able to generate.</li>
</ul>
<p>If you already know SVD, you’re closer to understanding VAEs than it might seem. Bend the axes, learn them from examples, and give the latent space a shape. That’s most of a VAE.</p>
</section>
<section id="sources" class="level2">
<h2 class="anchored" data-anchor-id="sources">Sources</h2>
<ul>
<li>Eckart, Young. <em>The approximation of one matrix by another of lower rank.</em> Psychometrika, 1936.</li>
<li>Baldi, Hornik. <em>Neural networks and principal component analysis: Learning from examples without local minima.</em> Neural Networks, 1989.</li>
<li>Tipping, Bishop. <em>Probabilistic Principal Component Analysis.</em> Journal of the Royal Statistical Society B, 1999.</li>
<li>Kingma, Welling. <a href="https://arxiv.org/abs/1312.6114"><em>Auto-Encoding Variational Bayes.</em></a> arXiv:1312.6114, 2013.</li>
</ul>


</section>

 ]]></description>
  <category>Machine Learning</category>
  <category>Deep Learning</category>
  <category>GenAI</category>
  <guid>https://timothdev.com/posts/vae-and-svd/</guid>
  <pubDate>Fri, 23 Oct 2026 00:00:00 GMT</pubDate>
  <media:content url="https://timothdev.com/posts/vae-and-svd/svd-vs-autoencoder.png" medium="image" type="image/png" height="41" width="144"/>
</item>
<item>
  <title>How the NSE India Stock Dataset Was Built</title>
  <dc:creator>Timoth Dev</dc:creator>
  <link>https://timothdev.com/posts/nse-india-dataset-pipeline/</link>
  <description><![CDATA[ 






<p>This is the behind-the-scenes companion to <a href="../../posts/nse-india-stock-dataset/index.html">Ten Years of Indian Stock Market Data, and Why Raw Prices Lie</a>. That post covers what the dataset is and why raw prices can’t be trusted. This one covers how it’s put together, from the first download to the file on Kaggle.</p>
<section id="the-big-picture" class="level2">
<h2 class="anchored" data-anchor-id="the-big-picture">The big picture</h2>
<p>Everything runs as a set of small Python scripts. Each one does one job, and they run in order:</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
  A[Download&lt;br/&gt;raw files] --&gt; B[Parse into&lt;br/&gt;tables]
  B --&gt; C[Fix prices&lt;br/&gt;and dates]
  C --&gt; D{Checks&lt;br/&gt;pass?}
  D -- yes --&gt; E[Features&lt;br/&gt;and Kaggle]
  D -- no --&gt; F[Stop]
</pre>
</div>
<p></p></figure><p></p>
</div>
</div>
</div>
<p>Raw files are always kept. If a parsing rule turns out to be wrong, the tables can be rebuilt in minutes without downloading anything again.</p>
</section>
<section id="step-1-collect" class="level2">
<h2 class="anchored" data-anchor-id="step-1-collect">Step 1: Collect</h2>
<p>The data comes from four public sources:</p>
<table class="caption-top table">
<colgroup>
<col style="width: 50%">
<col style="width: 50%">
</colgroup>
<thead>
<tr class="header">
<th>Source</th>
<th>What it gives</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><strong>NSE</strong></td>
<td>Daily prices for every stock, corporate actions, quarterly results, insider trades, bulk deals, F&amp;O positions</td>
</tr>
<tr class="even">
<td><strong>NSDL</strong></td>
<td>Daily foreign investor flows</td>
</tr>
<tr class="odd">
<td><strong>BSE</strong></td>
<td>Bulk and block deals</td>
</tr>
<tr class="even">
<td><strong>Yahoo Finance</strong></td>
<td>Global indices, oil, gold, currency</td>
</tr>
</tbody>
</table>
<p>Downloading ten years of this sounds simple. In practice the sources fail in odd ways, and most of the collection code exists to handle them.</p>
<p><strong>“Not Found” doesn’t always mean not found.</strong> NSE sometimes says a file doesn’t exist when it does. In the first full run about 10% of trading days came back missing. Asked again, 5 out of 8 of them downloaded fine. So a missing file is retried on later runs, and only counts as truly missing after three tries.</p>
<p><strong>Holidays get yesterday’s file.</strong> Ask NSE for a holiday and it can hand back the previous day’s file, renamed to the date you asked for. Every file’s date is now checked against what’s written inside it.</p>
<p><strong>Files aren’t always what they claim.</strong> One day’s “CSV” was really an Excel workbook. Some zip files contain more zip files. Some put the CSV inside a folder named like a CSV.</p>
<p><strong>Some APIs quietly cut results short.</strong> NSE’s bulk deals API returns at most 70 rows as JSON, but the full month as CSV. Another endpoint once reported 0 results on one page, and a month came back with 100 of its 3,075 filings. Counts are now checked, and a short month stops the run.</p>
<p><strong>Formats change.</strong> NSE replaced its daily price file in July 2024, moved quarterly results to a new system in 2025, and changed insider disclosures in May 2026. Old and new formats are merged into one table. For prices, both versions were compared on days where both exist, and every column matched.</p>
<p><strong>Some data only exists if you save it that day.</strong> BSE’s deals and NSE’s daily FII/DII figures only show the latest day, with no archive. A day that’s missed is gone for good.</p>
<p>The downloads are built to be restarted. Each finished file gets a small marker, so a rerun skips what’s done and fills any gaps. The biggest job, about 123,000 quarterly results documents, took around 60 hours.</p>
</section>
<section id="step-2-turn-files-into-tables" class="level2">
<h2 class="anchored" data-anchor-id="step-2-turn-files-into-tables">Step 2: Turn files into tables</h2>
<p>Raw files become one clean table per topic. Most of the work is small rules, each with a reason:</p>
<ul>
<li><strong>Quarterly results:</strong> read the quarter’s own numbers, not the year-to-date totals that sit next to them in the same filing.</li>
<li><strong>Insider trades:</strong> the same trade is often filed more than once, so 14,680 duplicates were removed. When a reported trade value didn’t match quantity × price, it was corrected (1,802 rows).</li>
<li><strong>Insider categories:</strong> 142 different spellings of “promoter”, “director” and so on were mapped to six groups.</li>
</ul>
<p>One parsing bug is worth sharing. The 2017 results pages had table rows that were never closed in the HTML, so each row contained the rest of the table inside it. The parser read the next row’s label as this row’s value, and quietly lost EPS for most of 2017. It was only caught by looking at how many EPS values each year had.</p>
</section>
<section id="step-3-fix-prices-and-dates" class="level2">
<h2 class="anchored" data-anchor-id="step-3-fix-prices-and-dates">Step 3: Fix prices and dates</h2>
<p>The price fixes (splits, bonuses, demergers) are covered in the <a href="../../posts/nse-india-stock-dataset/index.html">first post</a>.</p>
<p>The date fix is simpler but just as important. Every filing gets an <code>EVENT_DATE</code>: the first trading session that could react to it. Most results come out after the market closes:</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://timothdev.com/posts/nse-india-dataset-pipeline/broadcast-hour.png" class="img-fluid figure-img"></p>
<figcaption>Hour of day when quarterly results are published (Indian time). Most arrive in the evening, after the 3:30 pm close.</figcaption>
</figure>
</div>
<p>The rule is: anything published after 3:15 pm, or on a holiday, counts for the next session. Using the quarter-end date or the trade date instead would let a backtest act on news before it was public.</p>
</section>
<section id="step-4-check-before-publishing" class="level2">
<h2 class="anchored" data-anchor-id="step-4-check-before-publishing">Step 4: Check before publishing</h2>
<p>Every build ends with a check script. If it fails, nothing downstream runs, and nothing gets published.</p>
<table class="caption-top table">
<colgroup>
<col style="width: 33%">
<col style="width: 33%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th>Check</th>
<th>What it looks for</th>
<th>Result</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><strong>Look-ahead</strong></td>
<td>Rebuild everything as if it were 1 Jan 2024. Does any past row change?</td>
<td>0 of 3.37 million rows changed</td>
</tr>
<tr class="even">
<td><strong>Hidden splits</strong></td>
<td>Any large one-day fall on a liquid stock that isn’t a known event</td>
<td>None beyond −29%</td>
</tr>
<tr class="odd">
<td><strong>Market sanity</strong></td>
<td>Does an equal-weight basket of the liquid stocks behave like the real market?</td>
<td>Tracks NIFTY with a correlation of 0.80</td>
</tr>
</tbody>
</table>
<p>The last check is a good smell test. If splits weren’t fixed, the basket would be full of fake crashes. Instead it shows the market history you’d expect, including the 2018–19 small-cap slump and the March 2020 COVID crash:</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://timothdev.com/posts/nse-india-dataset-pipeline/equal-weight-index.png" class="img-fluid figure-img"></p>
<figcaption>An equal-weight basket of all liquid stocks, dividends included (top), and how far it was below its previous peak (bottom).</figcaption>
</figure>
</div>
</section>
<section id="step-5-keep-it-fresh" class="level2">
<h2 class="anchored" data-anchor-id="step-5-keep-it-fresh">Step 5: Keep it fresh</h2>
<p>One command runs the whole pipeline every evening after NSE publishes the day’s files. It takes about 15 to 20 minutes.</p>
<p>The rule for failures is simple:</p>
<ul>
<li><strong>A failed download</strong> is logged and the run carries on. One late source shouldn’t stop the day.</li>
<li><strong>A failed build or check</strong> stops everything. Bad data is worse than no data.</li>
</ul>
<p>For the Kaggle release, the tables are split into one file per year, so you can load just the years you need.</p>
</section>
<section id="what-made-the-biggest-difference" class="level2">
<h2 class="anchored" data-anchor-id="what-made-the-biggest-difference">What made the biggest difference</h2>
<ol type="1">
<li><strong>Keep the raw files.</strong> Most bugs were in parsing, not downloading. Re-parsing takes minutes, re-downloading takes days.</li>
<li><strong>Never trust a single “missing”.</strong> Public APIs fail randomly. Retry on another day before giving up.</li>
<li><strong>Check the date inside the file</strong>, not the date in its name.</li>
<li><strong>Count things.</strong> Rows per month, values per year. Most silent bugs show up as a dip in a simple count.</li>
<li><strong>Make the checks a gate</strong>, not a report. A check that only prints a warning gets ignored.</li>
</ol>
<p><strong>Dataset:</strong> <a href="https://www.kaggle.com/datasets/timontunes/nse-india-adjusted-equity-panel">NSE India Stocks 2016–2026: Adjusted Panel</a></p>


</section>

 ]]></description>
  <category>Data Engineering</category>
  <category>Finance</category>
  <guid>https://timothdev.com/posts/nse-india-dataset-pipeline/</guid>
  <pubDate>Wed, 14 Oct 2026 00:00:00 GMT</pubDate>
  <media:content url="https://timothdev.com/posts/nse-india-dataset-pipeline/equal-weight-index.png" medium="image" type="image/png" height="71" width="144"/>
</item>
<item>
  <title>Ten Years of Indian Stock Market Data, and Why Raw Prices Lie</title>
  <dc:creator>Timoth Dev</dc:creator>
  <link>https://timothdev.com/posts/nse-india-stock-dataset/</link>
  <description><![CDATA[ 






<div class="callout callout-style-simple callout-tip">
<div class="callout-body d-flex">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-body-container">
<p><strong>Behind the scenes:</strong> <a href="../../posts/nse-india-dataset-pipeline/index.html">How the NSE India Stock Dataset Was Built</a> covers the pipeline itself, from downloading to the checks that run before every release.</p>
</div>
</div>
</div>
<p>Any study of stock returns starts with a price history you can trust. For Indian stocks that turns out to be much harder than it sounds, and most of the work goes into problems that aren’t obvious at first.</p>
<p>This post covers what goes wrong with raw NSE data and how it was fixed. The result is a free dataset on Kaggle: adjusted daily prices for <strong>3,986 NSE stocks</strong> (5 million rows), quarterly financials, insider trades, bulk deals, foreign investor flows, and 96 ready-made features for machine learning.</p>
<p><strong>Dataset:</strong> <a href="https://www.kaggle.com/datasets/timontunes/nse-india-adjusted-equity-panel">NSE India Stocks 2016–2026: Adjusted Panel</a></p>
<section id="raw-prices-are-not-adjusted" class="level2">
<h2 class="anchored" data-anchor-id="raw-prices-are-not-adjusted">Raw prices are not adjusted</h2>
<p>The National Stock Exchange of India publishes a daily file called the <em>bhavcopy</em>: open, high, low, close and volume for every listed security. It’s public, complete, and goes back decades.</p>
<p>It’s also <strong>completely unadjusted</strong>. When a company does a 1:1 bonus issue, the number of shares doubles and the price halves overnight. The bhavcopy records that as a 50% crash. Every return, moving average and 52-week high computed across that date is wrong.</p>
<p>Bajaj Finance is a good example. In June 2025 it did a split and a bonus on the same day, ten times the shares in total:</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://timothdev.com/posts/nse-india-stock-dataset/bajaj-raw-vs-adjusted.png" class="img-fluid figure-img"></p>
<figcaption>Bajaj Finance around its June 2025 split and bonus. Left: the raw close, which drops about 90% overnight. Right: the adjusted close, which is continuous.</figcaption>
</figure>
</div>
</section>
<section id="the-official-feed-only-explains-half-the-breaks" class="level2">
<h2 class="anchored" data-anchor-id="the-official-feed-only-explains-half-the-breaks">The official feed only explains half the breaks</h2>
<p>NSE also publishes a corporate-action feed that lists splits and bonuses. It helps, but it can’t be trusted on its own:</p>
<ul>
<li><strong>The previous close is never restated on ex-dates.</strong> Of 843 split and bonus events, the “previous close” field was corrected on exactly zero.</li>
<li><strong>About half the breaks have no matching record.</strong> Of 1,031 large overnight drops in liquid stocks, only 512 matched the feed. The rest were demergers, rights issues, missing records, and real crashes.</li>
<li><strong>Some companies have no records at all.</strong> Tata Motors has zero across 11 years.</li>
<li><strong>Older records are abbreviated.</strong> In 2016 and 2017 splits were written as <code>Fv Splt Frm Rs 10 To Re 1</code>. A parser looking for “split” misses all of them, including JSW Steel’s 10:1 split.</li>
</ul>
<p>So the prices themselves have to be read for evidence too.</p>
</section>
<section id="reading-the-breaks-out-of-the-prices" class="level2">
<h2 class="anchored" data-anchor-id="reading-the-breaks-out-of-the-prices">Reading the breaks out of the prices</h2>
<p>Every large overnight jump is treated as an event that needs an explanation:</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 TD
  J[Large overnight jump] --&gt; F{Split or bonus&lt;br/&gt;in the feed?}
  F -- "yes, ratio fits" --&gt; A[Adjust by the feed's factor]
  F -- no --&gt; D{Demerger, rights&lt;br/&gt;or scheme?}
  D -- yes --&gt; M[Mask the day]
  D -- no --&gt; C{Clean ratio?&lt;br/&gt;2x, 5x, 10x}
  C -- yes --&gt; A2[Adjust as a missed split]
  C -- no --&gt; R[Mask and send for review]
</pre>
</div>
<p></p></figure><p></p>
</div>
</div>
</div>
<p>Demergers get masked rather than adjusted because the right factor depends on what the spun-off business was worth, and that isn’t in any dataset.</p>
<p>Each rule in that chart came from a bug:</p>
<ul>
<li><strong>Too many allowed ratios erase real crashes.</strong> An early version allowed every bonus ratio, like 5:12 or 7:10. They sit so close together that Yes Bank’s real 2020 collapse “snapped” to a 5:12 bonus and vanished. A short list of clean ratios fixed it.</li>
<li><strong>Penny stocks break the maths.</strong> At ₹0.10, a single price tick <em>is</em> a 1.5× move. One stock collected 163 fake “splits” and a cumulative factor of 10⁴². Inference now needs a minimum price and liquidity.</li>
<li><strong>Circuit limits distort the ratio.</strong> Fitted factors were often off by exactly 0.1667. NSE resets the 20% price band on an ex-date, and hot small caps close at the upper limit, so a correct 5:1 split shows up as a ×4.17 jump.</li>
<li><strong>Some cases need a human.</strong> Checking every unexplained break on a liquid stock against news and filings found 17 corporate actions the feed never reported, including splits at United Spirits and HEG.</li>
</ul>
<p>Real crashes stay in the data: Yes Bank’s moratorium day, DHFL, Jet Airways. Removing them would make every long-only backtest look better than it should. Every decision is logged in <code>price_events.csv</code>, with its reason.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://timothdev.com/posts/nse-india-stock-dataset/price-events.png" class="img-fluid figure-img"></p>
<figcaption>Every detected price break by year, split by where the explanation came from (left), and what was done with each kind (right).</figcaption>
</figure>
</div>
</section>
<section id="time-is-the-other-half-of-the-problem" class="level2">
<h2 class="anchored" data-anchor-id="time-is-the-other-half-of-the-problem">Time is the other half of the problem</h2>
<p>Clean prices aren’t enough. You also need to know <strong>when</strong> each piece of information became public. Using it a day early is look-ahead bias, the most common reason backtests fail in real trading.</p>
<ul>
<li><strong>Quarterly results</strong> are dated by the exchange broadcast time, not the quarter end. Two thirds come out after market hours, so the first session that can react is usually the next one.</li>
<li><strong>Insider trades</strong> reach the market a median of 3 days after the trade, and more than 12,000 disclosures arrived over a month late.</li>
<li><strong>Foreign flows</strong> and <strong>US markets</strong> are published after India closes, so they’re lagged one session.</li>
</ul>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://timothdev.com/posts/nse-india-stock-dataset/insider-lag.png" class="img-fluid figure-img"></p>
<figcaption>Days between an insider trade and its public disclosure. Anything 30 days or later is piled into the last bar. Joining on the trade date quietly leaks the future into a backtest.</figcaption>
</figure>
</div>
<p>Every event row has an <code>EVENT_DATE</code>: the first session the market could have reacted.</p>
<p>The best check for all of this was rebuilding the whole price panel as if it were 1 January 2024, with no later corporate action known, and comparing it with the full build. Returns, turnover and the tradable-universe flag matched on <strong>all 3.37 million</strong> rows before that date.</p>
</section>
<section id="whats-in-the-dataset" class="level2">
<h2 class="anchored" data-anchor-id="whats-in-the-dataset">What’s in the dataset</h2>
<table class="caption-top table">
<colgroup>
<col style="width: 50%">
<col style="width: 50%">
</colgroup>
<thead>
<tr class="header">
<th>Part</th>
<th>What it contains</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><strong>Prices</strong></td>
<td>Adjusted daily OHLC, VWAP, volume, delivery % and total return (dividends included) for every NSE stock, 2016–2026, delisted ones included</td>
</tr>
<tr class="even">
<td><strong>Price events</strong></td>
<td>Every detected break, how it was classified, and whether it was adjusted or masked</td>
</tr>
<tr class="odd">
<td><strong>Corporate actions</strong></td>
<td>NSE’s feed, parsed: dividends, splits, bonuses, rights, demergers, buybacks</td>
</tr>
<tr class="even">
<td><strong>Fundamentals</strong></td>
<td>Every quarterly results filing since 2016, with revenue, profit and EPS</td>
</tr>
<tr class="odd">
<td><strong>Ownership</strong></td>
<td>SEBI insider-trading disclosures, plus bulk and block deals</td>
</tr>
<tr class="even">
<td><strong>Flows</strong></td>
<td>Daily foreign portfolio investment (NSDL) and F&amp;O positioning by FIIs, DIIs, retail and prop traders</td>
</tr>
<tr class="odd">
<td><strong>ML features</strong></td>
<td>96 point-in-time features with forward-return labels, for the liquid universe only</td>
</tr>
</tbody>
</table>
<p>Three details that matter in practice:</p>
<ul>
<li><strong>No survivorship bias.</strong> 1,047 of the 3,986 symbols stopped trading before the end. Failed and merged companies are in the data.</li>
<li><strong>A tradable-universe flag.</strong> <code>ELIGIBLE</code> marks stocks with enough turnover, a sensible price and enough history, computed from past data only. It cuts thousands of thinly traded names to the few hundred you could actually buy.</li>
<li><strong>Delivery data.</strong> India publishes how much of each day’s volume was actually delivered rather than squared off intraday. Few markets have this.</li>
</ul>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://timothdev.com/posts/nse-india-stock-dataset/eligible.png" class="img-fluid figure-img"></p>
<figcaption>Stocks traded per day, and how many pass the ELIGIBLE filter. The dip in 2019 is real: small-cap turnover dried up after the 2018 sell-off.</figcaption>
</figure>
</div>
</section>
<section id="does-any-of-it-predict-returns" class="level2">
<h2 class="anchored" data-anchor-id="does-any-of-it-predict-returns">Does any of it predict returns?</h2>
<p>To show how the data is meant to be used, there’s a <a href="https://www.kaggle.com/code/timontunes/nse-india-stocks-leak-free-ml-baseline">leak-free ML baseline</a>: LightGBM on the 96 features, trained only on the past and tested year by year from 2020, with a gap between train and test so overlapping labels can’t leak.</p>
<p>The result is more useful than a clean win would have been:</p>
<ul>
<li><strong>The model ranks stocks better than momentum.</strong> Its average daily rank correlation (IC) with future returns was 0.056, against 0.031 for 12-month momentum, and it held up in every test year.</li>
<li><strong>Momentum still made the better portfolio.</strong> Buying momentum’s top 10% every two weeks beat the market average by about 13% a year after trading costs. The model’s top 10% roughly broke even.</li>
</ul>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://timothdev.com/posts/nse-india-stock-dataset/rank-ic.png" class="img-fluid figure-img"></p>
<figcaption>Rank IC over time, 120-day rolling mean. The model (blue) stays above zero almost throughout; momentum (orange) swings more.</figcaption>
</figure>
</div>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://timothdev.com/posts/nse-india-stock-dataset/top-decile-portfolio.png" class="img-fluid figure-img"></p>
<figcaption>Cumulative excess return of each top-10% portfolio over the liquid universe. Solid lines are after trading costs.</figcaption>
</figure>
</div>
<p>Two things explain the gap. Most of the model’s skill is in spotting <em>losers</em>: its bottom 10% lags about twice as much as its top 10% leads, and a long-only investor can’t use that. Its picks also change a lot between rebalances (about 64% of the portfolio each time, against 22% for momentum), so trading costs eat most of what’s left at the top.</p>
<p>A higher accuracy score doesn’t automatically mean a better strategy, and you only see that if the test itself is honest.</p>
</section>
<section id="lessons-for-anyone-building-market-data" class="level2">
<h2 class="anchored" data-anchor-id="lessons-for-anyone-building-market-data">Lessons for anyone building market data</h2>
<ol type="1">
<li><strong>Never trust a price series you haven’t checked for breaks.</strong> Plot a few known splits first.</li>
<li><strong>The official corporate-action feed is a hint, not the truth.</strong> Read the prices too.</li>
<li><strong>Every row needs a “known since” date.</strong> Most look-ahead bugs come from event data, not prices.</li>
<li><strong>Write the look-ahead test early.</strong> Rebuilding history as of a past date and diffing it is cheap and catches the most mistakes.</li>
<li><strong>Look at the extremes.</strong> The biggest values in a column are where unit errors live. One insider filing implied a share price 100 times too high, and only a chart of totals showed it.</li>
</ol>
</section>
<section id="get-the-data" class="level2">
<h2 class="anchored" data-anchor-id="get-the-data">Get the data</h2>
<ul>
<li><strong>Dataset:</strong> <a href="https://www.kaggle.com/datasets/timontunes/nse-india-adjusted-equity-panel">NSE India Stocks 2016–2026: Adjusted Panel</a></li>
<li><strong>Notebooks:</strong>
<ul>
<li><a href="https://www.kaggle.com/code/timontunes/nse-india-adjusted-panel-starter">Starter: loading the data and its traps</a></li>
<li><a href="https://www.kaggle.com/code/timontunes/nse-india-stocks-eda-of-every-file">Exploratory analysis of every file</a></li>
<li><a href="https://www.kaggle.com/code/timontunes/nse-india-stocks-leak-free-ml-baseline">Leak-free ML baseline</a></li>
</ul></li>
</ul>
<p>The data is compiled from public sources: the National Stock Exchange of India, NSDL and BSE, who own the original data. The cleaning, adjustment and features are shared under CC BY-NC 4.0 for research and education. Nothing here is investment advice.</p>


</section>

 ]]></description>
  <category>Data Engineering</category>
  <category>Finance</category>
  <category>Machine Learning</category>
  <guid>https://timothdev.com/posts/nse-india-stock-dataset/</guid>
  <pubDate>Wed, 14 Oct 2026 00:00:00 GMT</pubDate>
  <media:content url="https://timothdev.com/posts/nse-india-stock-dataset/bajaj-raw-vs-adjusted.png" medium="image" type="image/png" height="41" width="144"/>
</item>
<item>
  <title>Agentic RAG: Corrective, Adaptive and ReAct, with an 8B Model</title>
  <dc:creator>Timoth Dev</dc:creator>
  <link>https://timothdev.com/posts/agentic-rag-crag-adaptive-react/</link>
  <description><![CDATA[ 






<div class="callout callout-style-simple callout-note">
<div class="callout-body d-flex">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-body-container">
<p><strong>RAG workshop series.</strong> I prepared these notebooks for the RAG day of <em>AI Innovation &amp; Product Development</em>, a three-day workshop I ran for final-year B.Tech AI &amp; Data Science students.</p>
<ol type="1">
<li><a href="../../posts/when-to-use-rag/index.html">When to use RAG, and when a long context window is enough</a></li>
<li><a href="../../posts/basic-rag-from-scratch/index.html">Basic RAG from scratch</a></li>
<li><a href="../../posts/hybrid-search-bm25-reranking/index.html">Hybrid search: BM25, embeddings and a reranker</a></li>
<li><a href="../../posts/rag-real-documents-chroma/index.html">RAG on real documents: query rewriting, chunking, metadata and Chroma</a></li>
<li><a href="../../posts/agentic-rag-crag-adaptive-react/index.html">Agentic RAG: corrective, adaptive and ReAct</a></li>
</ol>
<p>All notebooks: <a href="https://github.com/Zilch123/ai-workshop/tree/main/output/day1">github.com/Zilch123/ai-workshop</a></p>
</div>
</div>
</div>
<p>Every pipeline so far ran once, in a fixed order: retrieve, then answer. The last notebook of the RAG day turns retrieval into a <strong>loop with decisions</strong>:</p>
<ul>
<li><strong>Corrective RAG (CRAG):</strong> check whether the retrieved chunks are relevant. If they aren’t, rewrite the query and try again.</li>
<li><strong>Adaptive RAG:</strong> decide whether a question needs retrieval at all.</li>
<li><strong>Agentic RAG (ReAct):</strong> let the model decide, step by step, whether to search again or answer.</li>
</ul>
<p>All three reuse the hybrid search and reranker from <a href="../../posts/hybrid-search-bm25-reranking/index.html">Part 3</a>, over a slightly bigger corpus: 8 AWS services, now including API Gateway, SNS, CloudWatch and IAM. The LLM is still Llama 3.1 8B Instruct. A small model makes the failures easy to see, which is useful when teaching.</p>
<section id="corrective-rag" class="level2">
<h2 class="anchored" data-anchor-id="corrective-rag">Corrective RAG</h2>
<p>First, ask the LLM to grade the retrieval:</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"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> evaluate_retrieval(question, results):</span>
<span id="cb1-2">    context <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="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\n\n</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>.join(r[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"text"</span>] <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> r <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> results)</span>
<span id="cb1-3">    prompt <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"""</span></span>
<span id="cb1-4"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">You are evaluating whether retrieved documents are useful for answering</span></span>
<span id="cb1-5"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">a user's question. Even one relevant sentence counts as relevant.</span></span>
<span id="cb1-6"></span>
<span id="cb1-7"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">Question:</span></span>
<span id="cb1-8"><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>question<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb1-9"></span>
<span id="cb1-10"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">Retrieved documents:</span></span>
<span id="cb1-11"><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>context<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb1-12"></span>
<span id="cb1-13"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">Return ONLY one of these:</span></span>
<span id="cb1-14"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">RELEVANT</span></span>
<span id="cb1-15"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">NOT_RELEVANT</span></span>
<span id="cb1-16"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"""</span></span>
<span id="cb1-17">    response <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> client.chat.completions.create(</span>
<span id="cb1-18">        model<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;">"meta-llama/Llama-3.1-8B-Instruct"</span>,</span>
<span id="cb1-19">        messages<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;">"role"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"user"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"content"</span>: prompt}],</span>
<span id="cb1-20">        max_tokens<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;">50</span>,</span>
<span id="cb1-21">        temperature<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="cb1-22">    )</span>
<span id="cb1-23">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> response.choices[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].message.content.strip()</span></code></pre></div></div>
<p>If the grade is <code>NOT_RELEVANT</code>, rewrite the query (the rewriter from <a href="../../posts/rag-real-documents-chroma/index.html">Part 4</a>) and search again:</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> corrective_rag(question):</span>
<span id="cb2-2">    results <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> rerank(question, hybrid_search(question, top_k<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;">5</span>), top_k<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;">3</span>)</span>
<span id="cb2-3"></span>
<span id="cb2-4">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"NOT_RELEVANT"</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> evaluate_retrieval(question, results):</span>
<span id="cb2-5">        rewritten <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> rewrite_query(question)</span>
<span id="cb2-6">        results <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> rerank(rewritten, hybrid_search(rewritten, top_k<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;">5</span>), top_k<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;">3</span>)</span>
<span id="cb2-7"></span>
<span id="cb2-8">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> results</span></code></pre></div></div>
<p>On an in-domain question, “How can I make two services work independently so one doesn’t have to wait for the other?”, the grade was <code>RELEVANT</code>, with SQS first, then API Gateway and Lambda.</p>
<p>On “Why is sky blue?”, the grade was <code>NOT_RELEVANT</code>. It rewrote the query, searched again, and returned… S3, SNS and Lambda.</p>
<p>That’s the gap in this simple version. Rewriting a query can’t find an answer that isn’t in the knowledge base. A full CRAG setup does something else when the grade fails: falls back to web search, or says “I don’t know”. Our version detected the problem correctly and then returned irrelevant chunks anyway. <strong>Grading is only useful if a failed grade changes what happens next.</strong></p>
</section>
<section id="adaptive-rag-routing" class="level2">
<h2 class="anchored" data-anchor-id="adaptive-rag-routing">Adaptive RAG: routing</h2>
<p>Some questions don’t need retrieval. A router decides before any search happens:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> route_question(question):</span>
<span id="cb3-2">    prompt <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"""</span></span>
<span id="cb3-3"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">You are a query router. Our knowledge base contains information about</span></span>
<span id="cb3-4"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">AWS services, including Amazon S3, Amazon SQS, AWS Lambda, Amazon DynamoDB,</span></span>
<span id="cb3-5"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">Amazon API Gateway, Amazon SNS, and AWS IAM.</span></span>
<span id="cb3-6"></span>
<span id="cb3-7"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">Return ONLY: RAG or DIRECT</span></span>
<span id="cb3-8"></span>
<span id="cb3-9"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">Use RAG if the question is about information covered by the knowledge base.</span></span>
<span id="cb3-10"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">Use DIRECT if the question is unrelated to the knowledge base.</span></span>
<span id="cb3-11"></span>
<span id="cb3-12"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">Question:</span></span>
<span id="cb3-13"><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>question<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb3-14"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"""</span></span>
<span id="cb3-15">    ...</span></code></pre></div></div>
<p><code>DIRECT</code> questions go straight to the LLM. <code>RAG</code> questions go through hybrid search and reranking first. It routed all four test questions correctly:</p>
<table class="caption-top table">
<thead>
<tr class="header">
<th>Question</th>
<th>Route</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>What is AWS SQS?</td>
<td>RAG</td>
</tr>
<tr class="even">
<td>What is the capital of France?</td>
<td>DIRECT</td>
</tr>
<tr class="odd">
<td>How does Lambda handle incoming requests?</td>
<td>RAG</td>
</tr>
<tr class="even">
<td>What is 25 multiplied by 4?</td>
<td>DIRECT</td>
</tr>
</tbody>
</table>
<p>One thing I noticed while writing this up: the router’s description of the knowledge base leaves out CloudWatch, even though it’s in the corpus. A CloudWatch question could get routed <code>DIRECT</code> and answered from the model’s memory. <strong>The router only knows what you tell it,</strong> so generate that description from the corpus instead of typing it by hand.</p>
</section>
<section id="agentic-rag-a-react-loop" class="level2">
<h2 class="anchored" data-anchor-id="agentic-rag-a-react-loop">Agentic RAG: a ReAct loop</h2>
<p>ReAct (reason plus act) lets the model choose its next action. Here there are only two actions:</p>
<pre><code>SEARCH: &lt;search query&gt;
ANSWER: &lt;final answer&gt;</code></pre>
<p>The loop runs a search when asked, appends the results to the conversation, and asks again, up to <code>max_steps</code>:</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"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># simplified from the notebook</span></span>
<span id="cb5-2"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> step <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>(max_steps):</span>
<span id="cb5-3">    decision <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> llm(conversation)</span>
<span id="cb5-4"></span>
<span id="cb5-5">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> decision.startswith(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"SEARCH:"</span>):</span>
<span id="cb5-6">        query <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> decision.removeprefix(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"SEARCH:"</span>).strip()</span>
<span id="cb5-7">        results <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> rerank(query, hybrid_search(query, top_k<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;">5</span>), top_k<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;">3</span>)</span>
<span id="cb5-8">        conversation <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span> [</span>
<span id="cb5-9">            {<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"role"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"assistant"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"content"</span>: decision},</span>
<span id="cb5-10">            {<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"role"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"user"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"content"</span>: <span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"Search results:</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\n\n</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>join_chunks(results)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\n\n</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span></span>
<span id="cb5-11">                                        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Decide whether you have enough information. "</span></span>
<span id="cb5-12">                                        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"If not, search again."</span>},</span>
<span id="cb5-13">        ]</span>
<span id="cb5-14">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">elif</span> decision.startswith(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ANSWER:"</span>):</span>
<span id="cb5-15">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> decision.removeprefix(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ANSWER:"</span>).strip()</span>
<span id="cb5-16"></span>
<span id="cb5-17"><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;">"I could not find enough information."</span></span></code></pre></div></div>
<section id="first-run-it-never-answered" class="level3">
<h3 class="anchored" data-anchor-id="first-run-it-never-answered">First run: it never answered</h3>
<p>Question: “How can AWS services communicate asynchronously without requiring one service to wait for another?”</p>
<pre><code>Step 1: SEARCH: asynchronous communication in AWS services
Step 2: SEARCH: AWS services asynchronous communication without waiting for another service
Step 3: SEARCH: AWS services asynchronous communication example

Final Answer: I could not find enough information.</code></pre>
<p>The SQS chunk answers this almost word for word, but the model kept searching, with slightly different queries, until it ran out of steps. “If not, search again” was apparently enough of a hint for an 8B model to keep searching.</p>
<p>Two things saved this run. <strong><code>max_steps</code> is not optional.</strong> Without it, this loop would run forever. And the fallback message is honest, not made up.</p>
</section>
<section id="second-run-it-answered-and-added-things" class="level3">
<h3 class="anchored" data-anchor-id="second-run-it-answered-and-added-things">Second run: it answered, and added things</h3>
<p>The second version tightened the prompt (“You may ONLY use facts explicitly stated in the search results”, “Do not search again if the answer can be supported by the results”) and stopped the loop if the model repeated an earlier query:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb7-1"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> query.lower() <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> [q.lower() <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> q <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> previous_queries]:</span>
<span id="cb7-2">    <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;">"The agent could not find enough information."</span></span>
<span id="cb7-3">previous_queries.append(query)</span></code></pre></div></div>
<p>This time it searched once and answered on step 2:</p>
<blockquote class="blockquote">
<p>AWS services can communicate asynchronously without requiring one service to wait for another by using Amazon SQS, AWS Lambda, and Amazon API Gateway. Amazon SQS allows producers to send messages to a queue and consumers to process those messages independently, decoupling distributed applications. […] Amazon API Gateway can route incoming HTTP requests to backend services such as AWS Lambda, enabling asynchronous communication between services.</p>
</blockquote>
<p>The SQS part is right and comes straight from the chunk. The API Gateway part isn’t. The chunk says it routes HTTP requests to Lambda. “Enabling asynchronous communication” is the model’s own addition, and it went against the prompt that told it not to.</p>
<p>Two lessons from this:</p>
<ul>
<li><strong>A grounding instruction in the prompt isn’t a guarantee.</strong> If grounding matters, check it: a second LLM call or a citation check that compares each claim against the retrieved text.</li>
<li><strong>The repeat check only catches exact repeats.</strong> The first run’s three queries were all different strings, so this check wouldn’t have stopped them. Near-duplicate queries need a similarity check, or just a small <code>max_steps</code>.</li>
</ul>
</section>
</section>
<section id="what-the-rag-day-added-up-to" class="level2">
<h2 class="anchored" data-anchor-id="what-the-rag-day-added-up-to">What the RAG day added up to</h2>
<p>Across the five notebooks, the students went from a 20-line retriever to an agent that decides when to search. The habit that ties it all together isn’t any single technique. It’s <strong>printing the intermediate steps</strong>: the chunks, the scores, the grades, the agent’s decisions. Every surprise in this series (Lambda beating SQS, the question mark in BM25, the agent that never answered) showed up only because the notebooks printed what happened inside.</p>
<p>Day 2 of the workshop moved on to building software with a coding agent, and Day 3 was a hands-on build of a proof-of-concept web app.</p>
<p><strong>Notebook:</strong> <a href="https://github.com/Zilch123/ai-workshop/blob/main/output/day1/agentic_RAG.ipynb">agentic_RAG.ipynb</a> · <a href="https://colab.research.google.com/github/Zilch123/ai-workshop/blob/main/output/day1/agentic_RAG.ipynb">Open in Colab</a></p>
<p><strong>The full RAG day in one notebook:</strong> <a href="https://github.com/Zilch123/ai-workshop/blob/main/output/day1/RAG.ipynb">RAG.ipynb</a>, with the outputs from the workshop run.</p>


</section>

 ]]></description>
  <category>GenAI</category>
  <category>RAG</category>
  <category>Agents</category>
  <category>Workshop</category>
  <guid>https://timothdev.com/posts/agentic-rag-crag-adaptive-react/</guid>
  <pubDate>Tue, 22 Sep 2026 00:00:00 GMT</pubDate>
</item>
<item>
  <title>RAG on Real Documents: Query Rewriting, Chunking, Metadata and Chroma</title>
  <dc:creator>Timoth Dev</dc:creator>
  <link>https://timothdev.com/posts/rag-real-documents-chroma/</link>
  <description><![CDATA[ 






<div class="callout callout-style-simple callout-note">
<div class="callout-body d-flex">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-body-container">
<p><strong>RAG workshop series.</strong> I prepared these notebooks for the RAG day of <em>AI Innovation &amp; Product Development</em>, a three-day workshop I ran for final-year B.Tech AI &amp; Data Science students.</p>
<ol type="1">
<li><a href="../../posts/when-to-use-rag/index.html">When to use RAG, and when a long context window is enough</a></li>
<li><a href="../../posts/basic-rag-from-scratch/index.html">Basic RAG from scratch</a></li>
<li><a href="../../posts/hybrid-search-bm25-reranking/index.html">Hybrid search: BM25, embeddings and a reranker</a></li>
<li><a href="../../posts/rag-real-documents-chroma/index.html">RAG on real documents: query rewriting, chunking, metadata and Chroma</a></li>
<li><a href="../../posts/agentic-rag-crag-adaptive-react/index.html">Agentic RAG: corrective, adaptive and ReAct</a></li>
</ol>
<p>All notebooks: <a href="https://github.com/Zilch123/ai-workshop/tree/main/output/day1">github.com/Zilch123/ai-workshop</a></p>
</div>
</div>
</div>
<p><a href="../../posts/hybrid-search-bm25-reranking/index.html">Part 3</a> improved the search itself. This part covers what goes around it: the question going in, the chunks being searched, the filters on top, and where the vectors live. It combines two notebooks from the workshop.</p>
<section id="query-rewriting" class="level2">
<h2 class="anchored" data-anchor-id="query-rewriting">Query rewriting</h2>
<p>Users ask vague questions. A rewrite step asks the LLM to turn a question into a short search query before retrieval:</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"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> rewrite_query(question):</span>
<span id="cb1-2">    response <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> client.chat.completions.create(</span>
<span id="cb1-3">        model<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;">"meta-llama/Llama-3.1-8B-Instruct"</span>,</span>
<span id="cb1-4">        messages<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[</span>
<span id="cb1-5">            {<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"role"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"system"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"content"</span>: (</span>
<span id="cb1-6">                <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Rewrite the user's question into a concise search query. "</span></span>
<span id="cb1-7">                <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Return only the rewritten query. Do not answer the question."</span></span>
<span id="cb1-8">            )},</span>
<span id="cb1-9">            {<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"role"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"user"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"content"</span>: question},</span>
<span id="cb1-10">        ],</span>
<span id="cb1-11">        max_tokens<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>,</span>
<span id="cb1-12">        temperature<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.2</span>,</span>
<span id="cb1-13">    )</span>
<span id="cb1-14">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> response.choices[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].message.content <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">or</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">""</span></span></code></pre></div></div>
<p>What it produced in the workshop run:</p>
<blockquote class="blockquote">
<p><strong>Original:</strong> How can I make my apps talk to each other without waiting?</p>
<p><strong>Rewritten:</strong> “Real-time inter-app communication without blocking”</p>
</blockquote>
<p>It’s shorter and more technical. It also changed the meaning a little. The user wanted <em>asynchronous</em> communication (a queue), and “real-time” points somewhere else. The quotes in the output would also end up in the search query.</p>
<p>So check rewrites before you trust them. A safer pattern is to search with both the original and the rewritten query and merge the results.</p>
</section>
<section id="chunking" class="level2">
<h2 class="anchored" data-anchor-id="chunking">Chunking</h2>
<blockquote class="blockquote">
<p>Text chunking matters more than which embedding model or reranker you pick.</p>
</blockquote>
<p>The <a href="https://docs.langchain.com/oss/python/integrations/splitters">LangChain splitter docs</a> are a good overview. The main strategies are:</p>
<ol type="1">
<li><strong>Fixed size with overlap:</strong> each chunk repeats the end of the previous one, so a sentence cut at the edge still appears whole in one of them.</li>
<li><strong>Recursive character splitting:</strong> try to split on paragraphs first, then lines, then sentences, then words. Chunks follow the document’s structure where they can.</li>
<li><strong>Sentence window:</strong> embed single sentences for precise matching, but give the LLM a few sentences either side.</li>
<li><strong>Semantic chunking:</strong> start a new chunk where the meaning shifts, measured with embeddings.</li>
</ol>
<p>Recursive splitting is the usual default:</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="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> langchain_text_splitters <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> RecursiveCharacterTextSplitter</span>
<span id="cb2-2"></span>
<span id="cb2-3">splitter <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> RecursiveCharacterTextSplitter(</span>
<span id="cb2-4">    chunk_size<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;">1000</span>,        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># max characters per chunk</span></span>
<span id="cb2-5">    chunk_overlap<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;">200</span>,      <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># repeated between neighbouring chunks</span></span>
<span id="cb2-6">    separators<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="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\n\n</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\n</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">". "</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">" "</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">""</span>],</span>
<span id="cb2-7">)</span>
<span id="cb2-8">chunks <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> splitter.split_text(document)</span></code></pre></div></div>
<p>In the workshop we tried it on a short Markdown note about machine learning. It came back as a single 775-character chunk, because the whole note was shorter than <code>chunk_size</code>. That’s worth knowing: the splitter only splits when it has to.</p>
<p>With <code>chunk_size=200</code> and <code>chunk_overlap=40</code>, the same note splits into 6 chunks, one per section, each 97 to 171 characters. Every chunk starts at a heading, so no section gets cut in half. The overlap shows up as the <em>next</em> heading repeated at the end of each chunk. That’s harmless here, but it’s the kind of detail you only notice by printing your chunks.</p>
</section>
<section id="metadata-filtering" class="level2">
<h2 class="anchored" data-anchor-id="metadata-filtering">Metadata filtering</h2>
<p>Most production RAG systems filter before they search. Every chunk carries structured fields:</p>
<table class="caption-top table">
<thead>
<tr class="header">
<th>document</th>
<th>page</th>
<th>chapter</th>
<th>year</th>
<th>department</th>
<th>type</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>aws_guide.pdf</td>
<td>24</td>
<td>Amazon SQS</td>
<td>2025</td>
<td>Engineering</td>
<td>Documentation</td>
</tr>
<tr class="even">
<td>hr_policy.pdf</td>
<td>5</td>
<td>Leave Policy</td>
<td>2025</td>
<td>HR</td>
<td>Policy</td>
</tr>
<tr class="odd">
<td>finance_report.pdf</td>
<td>8</td>
<td>Revenue</td>
<td>2025</td>
<td>Finance</td>
<td>Report</td>
</tr>
</tbody>
</table>
<p>An HR question then only searches HR documents from this year:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1">metadata_filter <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;">"department"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"HR"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"year"</span>: <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2025</span>}</span></code></pre></div></div>
<p>This does two jobs. It cuts out irrelevant chunks that happen to score well, and it’s how you enforce permissions: a user only searches documents they’re allowed to see.</p>
<p>In the first notebook I defined this filter and left using it as an exercise. In-memory lists don’t make it easy. A vector database does.</p>
</section>
<section id="from-a-python-list-to-chroma" class="level2">
<h2 class="anchored" data-anchor-id="from-a-python-list-to-chroma">From a Python list to Chroma</h2>
<p>Every notebook so far kept embeddings in a NumPy array. Restart the runtime and they’re gone. That’s fine for 4 paragraphs and not fine for a 10,000-page manual.</p>
<p><a href="https://docs.trychroma.com/">Chroma</a> is an embedded vector database. There’s no server and no account. It’s just a folder on disk that survives a restart.</p>
<section id="step-1-a-real-pdf" class="level3">
<h3 class="anchored" data-anchor-id="step-1-a-real-pdf">Step 1: a real PDF</h3>
<p>We wrote the AWS knowledge base out as <code>aws_guide.pdf</code>, one service per page, with <code>fpdf2</code>, then read it back with <code>pypdf</code>. The rest of the code works on any PDF, so students could upload their own.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb4-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> pypdf <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> PdfReader</span>
<span id="cb4-2"></span>
<span id="cb4-3">reader <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> PdfReader(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"aws_guide.pdf"</span>)</span></code></pre></div></div>
</section>
<section id="step-2-chunk-per-page-and-keep-the-page-number" class="level3">
<h3 class="anchored" data-anchor-id="step-2-chunk-per-page-and-keep-the-page-number">Step 2: chunk per page and keep the page number</h3>
<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">splitter <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> RecursiveCharacterTextSplitter(chunk_size<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;">400</span>, chunk_overlap<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;">50</span>)</span>
<span id="cb5-2"></span>
<span id="cb5-3">pdf_chunks, pdf_metadatas <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [], []</span>
<span id="cb5-4"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> page_number, page <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;">enumerate</span>(reader.pages, start<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>
<span id="cb5-5">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> chunk <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> splitter.split_text(page.extract_text()):</span>
<span id="cb5-6">        pdf_chunks.append(chunk)</span>
<span id="cb5-7">        pdf_metadatas.append({<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"page"</span>: page_number, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"source"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"aws_guide.pdf"</span>})</span></code></pre></div></div>
<p>Splitting page by page means every chunk knows where it came from. That page number becomes both a filter and a citation.</p>
</section>
<section id="step-3-store-in-chroma" class="level3">
<h3 class="anchored" data-anchor-id="step-3-store-in-chroma">Step 3: store in Chroma</h3>
<p>We pass in the same <code>all-MiniLM-L6-v2</code> model as an embedding function, so the vectors match the rest of the series:</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="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> chromadb</span>
<span id="cb6-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> chromadb <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> EmbeddingFunction</span>
<span id="cb6-3"></span>
<span id="cb6-4"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> SentenceTransformerEmbeddingFunction(EmbeddingFunction):</span>
<span id="cb6-5">    <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;">__call__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">input</span>):</span>
<span id="cb6-6">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> embedding_model.encode(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">input</span>).tolist()</span>
<span id="cb6-7"></span>
<span id="cb6-8">chroma_client <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> chromadb.PersistentClient(path<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;">"./chroma_db"</span>)</span>
<span id="cb6-9">collection <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> chroma_client.get_or_create_collection(</span>
<span id="cb6-10">    name<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;">"aws_guide"</span>,</span>
<span id="cb6-11">    embedding_function<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>SentenceTransformerEmbeddingFunction(),</span>
<span id="cb6-12">)</span>
<span id="cb6-13">collection.add(</span>
<span id="cb6-14">    ids<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"chunk-</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>i<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i <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="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(pdf_chunks))],</span>
<span id="cb6-15">    documents<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>pdf_chunks,</span>
<span id="cb6-16">    metadatas<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>pdf_metadatas,</span>
<span id="cb6-17">)</span></code></pre></div></div>
</section>
<section id="step-4-prove-it-persists" class="level3">
<h3 class="anchored" data-anchor-id="step-4-prove-it-persists">Step 4: prove it persists</h3>
<p>A new client pointing at the same folder finds everything, without calling <code>encode()</code> again:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb7-1">reconnected <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> chromadb.PersistentClient(path<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;">"./chroma_db"</span>).get_collection(</span>
<span id="cb7-2">    name<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;">"aws_guide"</span>,</span>
<span id="cb7-3">    embedding_function<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>SentenceTransformerEmbeddingFunction(),</span>
<span id="cb7-4">)</span>
<span id="cb7-5">reconnected.count()</span></code></pre></div></div>
</section>
<section id="step-5-the-metadata-filter-for-real" class="level3">
<h3 class="anchored" data-anchor-id="step-5-the-metadata-filter-for-real">Step 5: the metadata filter, for real</h3>
<p><code>where=</code> restricts the search to matching chunks. Here, only page 2 (SQS):</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb8-1">collection.query(</span>
<span id="cb8-2">    query_texts<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;">"How do applications communicate without waiting for each other?"</span>],</span>
<span id="cb8-3">    n_results<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;">3</span>,</span>
<span id="cb8-4">    where<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;">"page"</span>: <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>},</span>
<span id="cb8-5">)</span></code></pre></div></div>
</section>
<section id="step-6-answer-with-citations" class="level3">
<h3 class="anchored" data-anchor-id="step-6-answer-with-citations">Step 6: answer with citations</h3>
<p>The prompt now labels each chunk with its page and asks the model to cite it:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb9-1">context <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="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\n\n</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>.join(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"(page </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>m[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'page'</span>]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">) </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>text<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> text, m <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> retrieved)</span>
<span id="cb9-2"></span>
<span id="cb9-3">prompt <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"""</span></span>
<span id="cb9-4"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">Answer the question using only the context below. Cite the page number.</span></span>
<span id="cb9-5"></span>
<span id="cb9-6"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">CONTEXT:</span></span>
<span id="cb9-7"><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>context<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb9-8"></span>
<span id="cb9-9"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">QUESTION:</span></span>
<span id="cb9-10"><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>question<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb9-11"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"""</span></span></code></pre></div></div>
<p>A cited answer is easy to check: open the page and read it. That’s one of the main reasons to build RAG at all (see <a href="../../posts/when-to-use-rag/index.html">Part 1</a>).</p>
</section>
<section id="stretch-tasks" class="level3">
<h3 class="anchored" data-anchor-id="stretch-tasks">Stretch tasks</h3>
<p>For students who finished early:</p>
<ul>
<li><strong>Bring your own PDF</strong> and see whether retrieval holds up on a document the examples weren’t written for.</li>
<li><strong>Add BM25 on top of Chroma.</strong> Pull the chunks with <code>collection.get()</code>, build a BM25 index, and fuse the scores as in Part 3.</li>
</ul>
</section>
</section>
<section id="whats-next" class="level2">
<h2 class="anchored" data-anchor-id="whats-next">What’s next</h2>
<p>Every pipeline so far runs in a fixed order: retrieve, then answer, once. <a href="../../posts/agentic-rag-crag-adaptive-react/index.html">Part 5</a> turns retrieval into a loop with decisions: check whether the results are any good, decide whether to search at all, and let the model search again.</p>
<p><strong>Notebooks:</strong></p>
<ul>
<li><a href="https://github.com/Zilch123/ai-workshop/blob/main/output/day1/query_and_chunking_RAG.ipynb">query_and_chunking_RAG.ipynb</a> · <a href="https://colab.research.google.com/github/Zilch123/ai-workshop/blob/main/output/day1/query_and_chunking_RAG.ipynb">Open in Colab</a></li>
<li><a href="https://github.com/Zilch123/ai-workshop/blob/main/output/day1/pdf_chroma_RAG.ipynb">pdf_chroma_RAG.ipynb</a> · <a href="https://colab.research.google.com/github/Zilch123/ai-workshop/blob/main/output/day1/pdf_chroma_RAG.ipynb">Open in Colab</a></li>
</ul>


</section>

 ]]></description>
  <category>GenAI</category>
  <category>RAG</category>
  <category>Workshop</category>
  <guid>https://timothdev.com/posts/rag-real-documents-chroma/</guid>
  <pubDate>Mon, 21 Sep 2026 00:00:00 GMT</pubDate>
</item>
<item>
  <title>Hybrid Search for RAG: BM25, Embeddings and a Reranker</title>
  <dc:creator>Timoth Dev</dc:creator>
  <link>https://timothdev.com/posts/hybrid-search-bm25-reranking/</link>
  <description><![CDATA[ 






<div class="callout callout-style-simple callout-note">
<div class="callout-body d-flex">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-body-container">
<p><strong>RAG workshop series.</strong> I prepared these notebooks for the RAG day of <em>AI Innovation &amp; Product Development</em>, a three-day workshop I ran for final-year B.Tech AI &amp; Data Science students.</p>
<ol type="1">
<li><a href="../../posts/when-to-use-rag/index.html">When to use RAG, and when a long context window is enough</a></li>
<li><a href="../../posts/basic-rag-from-scratch/index.html">Basic RAG from scratch</a></li>
<li><a href="../../posts/hybrid-search-bm25-reranking/index.html">Hybrid search: BM25, embeddings and a reranker</a></li>
<li><a href="../../posts/rag-real-documents-chroma/index.html">RAG on real documents: query rewriting, chunking, metadata and Chroma</a></li>
<li><a href="../../posts/agentic-rag-crag-adaptive-react/index.html">Agentic RAG: corrective, adaptive and ReAct</a></li>
</ol>
<p>All notebooks: <a href="https://github.com/Zilch123/ai-workshop/tree/main/output/day1">github.com/Zilch123/ai-workshop</a></p>
</div>
</div>
</div>
<p>In <a href="../../posts/basic-rag-from-scratch/index.html">Part 2</a>, plain vector search ranked Lambda above SQS for “Which AWS service can help decouple applications?”. The right chunk only reached the LLM because we sent the top 2.</p>
<p>Embeddings capture meaning, but they’re weak on exact terms: product codes, error codes, acronyms. Keyword search is the opposite. This notebook adds three things:</p>
<ul>
<li><strong>BM25</strong>, the classic keyword ranking</li>
<li><strong>Hybrid search</strong>, which combines BM25 and vector scores</li>
<li><strong>Reranking</strong>, where a cross-encoder re-scores the top candidates</li>
</ul>
<section id="bm25" class="level2">
<h2 class="anchored" data-anchor-id="bm25">BM25</h2>
<p>BM25 (Best Matching 25) scores a chunk by the query words it contains. It has three parts:</p>
<ul>
<li><strong>Term frequency:</strong> a word that appears more often counts more, with diminishing returns.</li>
<li><strong>Inverse document frequency (IDF):</strong> rare words count more than common ones.</li>
<li><strong>Length normalisation:</strong> long chunks don’t win just because they have more words.</li>
</ul>
<p>With the <code>rank_bm25</code> library it’s a few lines:</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"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> rank_bm25 <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> BM25Okapi</span>
<span id="cb1-2"></span>
<span id="cb1-3">tokenized_chunks <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [chunk.lower().split() <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> chunk <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> chunks]</span>
<span id="cb1-4">bm25 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> BM25Okapi(tokenized_chunks)</span>
<span id="cb1-5"></span>
<span id="cb1-6">scores <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> bm25.get_scores(question.lower().split())</span></code></pre></div></div>
</section>
<section id="why-bm25-also-picked-lambda" class="level2">
<h2 class="anchored" data-anchor-id="why-bm25-also-picked-lambda">Why BM25 also picked Lambda</h2>
<p>On the decouple question, BM25 got it wrong too:</p>
<table class="caption-top table">
<thead>
<tr class="header">
<th>Chunk</th>
<th>BM25 score</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><strong>Lambda</strong></td>
<td><strong>1.190</strong></td>
</tr>
<tr class="even">
<td>S3</td>
<td>0.828</td>
</tr>
<tr class="odd">
<td>SQS</td>
<td>0.780</td>
</tr>
<tr class="even">
<td>DynamoDB</td>
<td>0.000</td>
</tr>
</tbody>
</table>
<p>Scoring each query word on its own shows why. It’s the tokenizer. <code>.split()</code> splits on spaces only, so punctuation stays attached to words:</p>
<ul>
<li>The query word is <code>applications?</code>, with the question mark. It matches nothing.</li>
<li><code>service</code> only matches S3. In the SQS and Lambda chunks the word is <code>service.</code>, with a full stop.</li>
<li><code>aws</code> only appears in the Lambda chunk (“AWS Lambda”, “AWS executes”). The other chunks say “Amazon”. So in this tiny corpus “aws” is a rare word, and BM25 rewards rare words.</li>
<li><code>decouple</code> is the only word pointing at SQS, and it’s worth 0.780.</li>
</ul>
<p>Stripping punctuation (<code>re.findall(r"\w+", text.lower())</code>) moves SQS up to second and S3 drops to 0.137. Lambda still wins, though, because of “aws”. Neither fix is wrong. BM25 does exactly what it’s told. <strong>Tokenization is part of your retrieval quality</strong>, and on a small corpus IDF can reward words that carry no meaning.</p>
</section>
<section id="hybrid-search" class="level2">
<h2 class="anchored" data-anchor-id="hybrid-search">Hybrid search</h2>
<p>The two score types are on different scales (cosine is between −1 and 1, BM25 is unbounded), so we min-max normalise each one to 0–1 and take a weighted sum:</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">semantic_norm <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (semantic <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> semantic.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">min</span>()) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (semantic.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">max</span>() <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> semantic.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">min</span>())</span>
<span id="cb2-2">bm25_norm <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (bm25_scores <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> bm25_scores.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">min</span>()) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (bm25_scores.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">max</span>() <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> bm25_scores.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">min</span>())</span>
<span id="cb2-3"></span>
<span id="cb2-4">hybrid <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> semantic_weight <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> semantic_norm <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> keyword_weight <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> bm25_norm</span></code></pre></div></div>
<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 TD
  Q[Query] --&gt; S[Semantic search&lt;br/&gt;cosine similarity]
  Q --&gt; K[Keyword search&lt;br/&gt;BM25]
  S --&gt; N[Normalise and&lt;br/&gt;combine]
  K --&gt; N
  N --&gt; R[Ranked chunks]
</pre>
</div>
<p></p></figure><p></p>
</div>
</div>
</div>
<p>With equal weights, on the AWS question:</p>
<table class="caption-top table">
<thead>
<tr class="header">
<th>Chunk</th>
<th>Hybrid</th>
<th>Semantic</th>
<th>BM25</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Lambda</td>
<td>1.000</td>
<td>1.000</td>
<td>1.000</td>
</tr>
<tr class="even">
<td>SQS</td>
<td>0.543</td>
<td>0.431</td>
<td>0.655</td>
</tr>
<tr class="odd">
<td>S3</td>
<td>0.460</td>
<td>0.225</td>
<td>0.695</td>
</tr>
<tr class="even">
<td>DynamoDB</td>
<td>0.000</td>
<td>0.000</td>
<td>0.000</td>
</tr>
</tbody>
</table>
<p>When both methods make the same mistake, combining them doesn’t fix it.</p>
<p>Also notice that min-max always gives the top chunk 1.0 and the bottom one 0.0, however close the raw scores were. On 4 chunks that stretches small differences a lot. Reciprocal rank fusion, which combines ranks instead of raw scores, is a common way to avoid this.</p>
<p>To show hybrid search when it works, we switched to five short incident reports and asked “Why is the application running out of memory?”. Both methods agreed on the upload memory issue (1.000), well ahead of the next one (0.343).</p>
</section>
<section id="reranking" class="level2">
<h2 class="anchored" data-anchor-id="reranking">Reranking</h2>
<p>Embedding search uses a <strong>bi-encoder</strong>: the question and each chunk are embedded separately and then compared. That’s fast, because chunk vectors are computed once, ahead of time. But the model never sees the question and the chunk together.</p>
<p>A <strong>cross-encoder</strong> reads the question and a chunk <em>as one input</em> and outputs a relevance score. It’s much better at judging relevance, but it has to run once per (question, chunk) pair at query time. That’s why you don’t use it to search everything. You use it to re-order the top few candidates from a cheaper search.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" 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;">from</span> sentence_transformers <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> CrossEncoder</span>
<span id="cb3-2"></span>
<span id="cb3-3">reranker <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> CrossEncoder(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"cross-encoder/ms-marco-MiniLM-L6-v2"</span>)</span>
<span id="cb3-4"></span>
<span id="cb3-5"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> rerank(question, results, top_k<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>
<span id="cb3-6">    scores <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> reranker.predict([(question, r[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"text"</span>]) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> r <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> results])</span>
<span id="cb3-7">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> r, 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;">zip</span>(results, scores):</span>
<span id="cb3-8">        r[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"reranker_score"</span>] <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>(s)</span>
<span id="cb3-9">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sorted</span>(results, key<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">lambda</span> r: r[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"reranker_score"</span>], reverse<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>)[:top_k]</span></code></pre></div></div>
<p>Hybrid search for the top 4, then rerank to the top 2:</p>
<table class="caption-top table">
<thead>
<tr class="header">
<th>Chunk</th>
<th>Reranker score</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><strong>SQS</strong></td>
<td><strong>2.552</strong></td>
</tr>
<tr class="even">
<td>Lambda</td>
<td>2.543</td>
</tr>
</tbody>
</table>
<p>SQS is finally first, but only by 0.009. A reranker improves the order, but the scores are close, and on a corpus this small and this similar, nothing separates the two cleanly. The fix for that is better data, not another model.</p>
<p>Some rerankers you’ll see in production:</p>
<table class="caption-top table">
<colgroup>
<col style="width: 33%">
<col style="width: 33%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th>Reranker</th>
<th>Type</th>
<th>Typical use</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Cohere Rerank</td>
<td>Hosted API</td>
<td>Teams that want managed infrastructure</td>
</tr>
<tr class="even">
<td>BGE Reranker</td>
<td>Open weights</td>
<td>Self-hosted RAG, a popular open-source choice</td>
</tr>
<tr class="odd">
<td>Jina Reranker</td>
<td>Hosted and open</td>
<td>Multilingual or document-heavy workloads</td>
</tr>
<tr class="even">
<td>Voyage Rerank</td>
<td>Hosted API</td>
<td>High-quality managed retrieval</td>
</tr>
<tr class="odd">
<td>Qwen Reranker</td>
<td>Open weights</td>
<td>Larger models when quality matters most</td>
</tr>
</tbody>
</table>
<p>A small LLM can also be used as a reranker, if you can afford the extra latency and cost.</p>
</section>
<section id="whats-next" class="level2">
<h2 class="anchored" data-anchor-id="whats-next">What’s next</h2>
<p>So far we’ve improved the search itself. <a href="../../posts/rag-real-documents-chroma/index.html">Part 4</a> works on what goes in and out of it: rewriting the query, chunking real documents properly, filtering by metadata, and keeping vectors in a database so they survive a restart.</p>
<p><strong>Notebook:</strong> <a href="https://github.com/Zilch123/ai-workshop/blob/main/output/day1/hybrid_search_RAG.ipynb">hybrid_search_RAG.ipynb</a> · <a href="https://colab.research.google.com/github/Zilch123/ai-workshop/blob/main/output/day1/hybrid_search_RAG.ipynb">Open in Colab</a></p>


</section>

 ]]></description>
  <category>GenAI</category>
  <category>RAG</category>
  <category>Workshop</category>
  <guid>https://timothdev.com/posts/hybrid-search-bm25-reranking/</guid>
  <pubDate>Sun, 20 Sep 2026 00:00:00 GMT</pubDate>
</item>
<item>
  <title>Basic RAG from Scratch: Chunk, Embed, Compare, Prompt</title>
  <dc:creator>Timoth Dev</dc:creator>
  <link>https://timothdev.com/posts/basic-rag-from-scratch/</link>
  <description><![CDATA[ 






<div class="callout callout-style-simple callout-note">
<div class="callout-body d-flex">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-body-container">
<p><strong>RAG workshop series.</strong> I prepared these notebooks for the RAG day of <em>AI Innovation &amp; Product Development</em>, a three-day workshop I ran for final-year B.Tech AI &amp; Data Science students.</p>
<ol type="1">
<li><a href="../../posts/when-to-use-rag/index.html">When to use RAG, and when a long context window is enough</a></li>
<li><a href="../../posts/basic-rag-from-scratch/index.html">Basic RAG from scratch</a></li>
<li><a href="../../posts/hybrid-search-bm25-reranking/index.html">Hybrid search: BM25, embeddings and a reranker</a></li>
<li><a href="../../posts/rag-real-documents-chroma/index.html">RAG on real documents: query rewriting, chunking, metadata and Chroma</a></li>
<li><a href="../../posts/agentic-rag-crag-adaptive-react/index.html">Agentic RAG: corrective, adaptive and ReAct</a></li>
</ol>
<p>All notebooks: <a href="https://github.com/Zilch123/ai-workshop/tree/main/output/day1">github.com/Zilch123/ai-workshop</a></p>
</div>
</div>
</div>
<p>Frameworks like LangChain hide the parts of RAG that matter most when something breaks. So for the workshop, the first notebook built the whole pipeline by hand. It’s about 20 lines of real 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
  A[Documents] --&gt; B[Chunks]
  B --&gt; C[Embeddings]
  Q[Question] --&gt; D[Question&lt;br/&gt;embedding]
  C --&gt; E[Cosine&lt;br/&gt;similarity]
  D --&gt; E
  E --&gt; F[Top chunks]
  F --&gt; G[Prompt]
  G --&gt; H[LLM]
</pre>
</div>
<p></p></figure><p></p>
</div>
</div>
</div>
<section id="the-knowledge-base" class="level2">
<h2 class="anchored" data-anchor-id="the-knowledge-base">The knowledge base</h2>
<p>Four short paragraphs about AWS services: S3, SQS, Lambda and DynamoDB. Real systems have millions of documents, but the mechanism is the same, and with four you can read every score.</p>
<p>The question we want answered:</p>
<blockquote class="blockquote">
<p>Which AWS service should I use to decouple applications?</p>
</blockquote>
<p>The right answer is SQS.</p>
</section>
<section id="chunking" class="level2">
<h2 class="anchored" data-anchor-id="chunking">Chunking</h2>
<p>Embedding a 200-page PDF as a single vector gives a poor representation for any one question, so RAG systems split documents into chunks first. The simplest chunker splits on word count:</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"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> chunk_text(text, chunk_size<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;">250</span>):</span>
<span id="cb1-2">    words <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> text.split()</span>
<span id="cb1-3">    chunks <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []</span>
<span id="cb1-4">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i <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;">0</span>, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(words), chunk_size):</span>
<span id="cb1-5">        chunks.append(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">" "</span>.join(words[i:i <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> chunk_size]))</span>
<span id="cb1-6">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> chunks</span></code></pre></div></div>
<p>Each of our documents is shorter than 250 words, so this gives 4 chunks, one per document. In this example chunking does nothing yet. <a href="../../posts/rag-real-documents-chroma/index.html">Part 4</a> covers better strategies.</p>
</section>
<section id="embeddings" class="level2">
<h2 class="anchored" data-anchor-id="embeddings">Embeddings</h2>
<p>An embedding model turns text into a vector of numbers. Texts with similar meanings end up close together. We used <code>all-MiniLM-L6-v2</code>: 384 dimensions, about 22 million parameters, around 70 MB, fast on a CPU, and no API key needed.</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="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sentence_transformers <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> SentenceTransformer</span>
<span id="cb2-2"></span>
<span id="cb2-3">embedding_model <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> SentenceTransformer(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"all-MiniLM-L6-v2"</span>)</span>
<span id="cb2-4">chunk_embeddings <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> embedding_model.encode(chunks)   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># shape (4, 384)</span></span></code></pre></div></div>
</section>
<section id="similarity-search" class="level2">
<h2 class="anchored" data-anchor-id="similarity-search">Similarity search</h2>
<p>Embed the question the same way, then compare it with every chunk using cosine similarity:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" 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;">from</span> sklearn.metrics.pairwise <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> cosine_similarity</span>
<span id="cb3-2"></span>
<span id="cb3-3"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> search(question, top_k<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>
<span id="cb3-4">    question_embedding <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> embedding_model.encode([question])</span>
<span id="cb3-5">    scores <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cosine_similarity(question_embedding, chunk_embeddings)[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]</span>
<span id="cb3-6">    top_indices <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> scores.argsort()[::<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>][:top_k]</span>
<span id="cb3-7">    <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;">"score"</span>: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>(scores[i]), <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"text"</span>: chunks[i]} <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> top_indices]</span></code></pre></div></div>
<p>That’s semantic search. On easy questions it works well:</p>
<table class="caption-top table">
<thead>
<tr class="header">
<th>Question</th>
<th>Top chunk</th>
<th>Score</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Where should I store application files?</td>
<td>S3</td>
<td>0.229</td>
</tr>
<tr class="even">
<td>How can I run code without managing servers?</td>
<td>Lambda</td>
<td>0.311</td>
</tr>
<tr class="odd">
<td>Which database provides low latency access?</td>
<td>DynamoDB</td>
<td>0.488</td>
</tr>
<tr class="even">
<td>How can microservices communicate asynchronously?</td>
<td>SQS</td>
<td>0.338</td>
</tr>
</tbody>
</table>
<p>Look at the last row, though. Lambda came second with 0.324, very close behind.</p>
</section>
<section id="the-first-surprise" class="level2">
<h2 class="anchored" data-anchor-id="the-first-surprise">The first surprise</h2>
<p>My notebook said “you should see the SQS document receive the highest similarity score” for the decouple question. It didn’t:</p>
<table class="caption-top table">
<thead>
<tr class="header">
<th>Chunk</th>
<th>Score</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><strong>Lambda</strong></td>
<td><strong>0.549</strong></td>
</tr>
<tr class="even">
<td>SQS</td>
<td>0.467</td>
</tr>
<tr class="odd">
<td>S3</td>
<td>0.437</td>
</tr>
<tr class="even">
<td>DynamoDB</td>
<td>0.405</td>
</tr>
</tbody>
</table>
<p>Lambda won. My guess is that the Lambda text shares more surface words with the question (“AWS”, “service”, “applications”) than the SQS text does. The only word that points to SQS is “decouple”. Small embedding models pick up overlap like this more than you’d hope.</p>
<p>This turned into a better lesson than the one I’d planned: <strong>retrieval is the part most likely to be wrong, and it fails quietly.</strong></p>
</section>
<section id="prompt-and-answer" class="level2">
<h2 class="anchored" data-anchor-id="prompt-and-answer">Prompt and answer</h2>
<p>Because <code>top_k=2</code>, SQS still made it into the context, in second place. The prompt tells the model to use only that context:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb4-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> build_prompt(question, retrieved_chunks):</span>
<span id="cb4-2">    context <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="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\n\n</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>.join(retrieved_chunks)</span>
<span id="cb4-3">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"""</span></span>
<span id="cb4-4"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">    Answer the question using only the context below.</span></span>
<span id="cb4-5"></span>
<span id="cb4-6"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">    CONTEXT:</span></span>
<span id="cb4-7"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">    </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>context<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb4-8"></span>
<span id="cb4-9"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">    QUESTION:</span></span>
<span id="cb4-10"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">    </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>question<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb4-11"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">    """</span></span></code></pre></div></div>
<p>Then we send it to Llama 3.1 8B Instruct. Nscale serves it behind an OpenAI-compatible API, so the standard <code>openai</code> client works:</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"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> openai <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> OpenAI</span>
<span id="cb5-2"></span>
<span id="cb5-3">client <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> OpenAI(api_key<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>NSCALE_TOKEN, base_url<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;">"https://inference.api.nscale.com/v1"</span>)</span>
<span id="cb5-4"></span>
<span id="cb5-5">response <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> client.chat.completions.create(</span>
<span id="cb5-6">    model<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;">"meta-llama/Llama-3.1-8B-Instruct"</span>,</span>
<span id="cb5-7">    messages<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[</span>
<span id="cb5-8">        {<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"role"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"system"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"content"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"You are a helpful assistant."</span>},</span>
<span id="cb5-9">        {<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"role"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"user"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"content"</span>: prompt},</span>
<span id="cb5-10">    ],</span>
<span id="cb5-11">    max_tokens<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;">500</span>,</span>
<span id="cb5-12">    temperature<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.7</span>,</span>
<span id="cb5-13">)</span></code></pre></div></div>
<p>The answer:</p>
<blockquote class="blockquote">
<p>You should use Amazon SQS to decouple applications. It’s a managed message queue service that allows applications to communicate asynchronously.</p>
</blockquote>
<p>Correct. But only because the right chunk happened to be in the top 2 and the LLM picked it over the Lambda chunk listed above it. With <code>top_k=1</code>, the model would only have seen the Lambda chunk.</p>
</section>
<section id="five-experiments-to-try" class="level2">
<h2 class="anchored" data-anchor-id="five-experiments-to-try">Five experiments to try</h2>
<p>The point of the notebook was to change things, not just run it. These are the experiments I set for the students:</p>
<ol type="1">
<li><strong>Add similar documents.</strong> For example “EventBridge connects applications using events” and “SNS distributes messages to multiple subscribers”. Does SQS still rank first for “decouple”?</li>
<li><strong>Change the chunk size</strong> to 50, then 500. What happens to retrieval?</li>
<li><strong>Change <code>top_k</code></strong> from 1 to 3. Does more context always give a better answer?</li>
<li><strong>Add irrelevant documents.</strong> Does retrieval get worse?</li>
<li><strong>Ask something ambiguous</strong>, like “Which service should I use for messaging?”</li>
</ol>
<p>Each one shows a problem real RAG systems have to deal with. The LLM can only answer from the chunks it’s given, and basic vector search alone doesn’t reliably give it the right ones.</p>
</section>
<section id="whats-next" class="level2">
<h2 class="anchored" data-anchor-id="whats-next">What’s next</h2>
<p>Embeddings are good at meaning and bad at exact words. <a href="../../posts/hybrid-search-bm25-reranking/index.html">Part 3</a> adds keyword search (BM25), combines it with the vector scores, and adds a reranker to fix the order.</p>
<p><strong>Notebook:</strong> <a href="https://github.com/Zilch123/ai-workshop/blob/main/output/day1/basic_RAG.ipynb">basic_RAG.ipynb</a> · <a href="https://colab.research.google.com/github/Zilch123/ai-workshop/blob/main/output/day1/basic_RAG.ipynb">Open in Colab</a></p>


</section>

 ]]></description>
  <category>GenAI</category>
  <category>RAG</category>
  <category>Workshop</category>
  <guid>https://timothdev.com/posts/basic-rag-from-scratch/</guid>
  <pubDate>Sat, 19 Sep 2026 00:00:00 GMT</pubDate>
</item>
<item>
  <title>When to Use RAG, and When a Long Context Window Is Enough</title>
  <dc:creator>Timoth Dev</dc:creator>
  <link>https://timothdev.com/posts/when-to-use-rag/</link>
  <description><![CDATA[ 






<div class="callout callout-style-simple callout-note">
<div class="callout-body d-flex">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-body-container">
<p><strong>RAG workshop series.</strong> I prepared these notebooks for the RAG day of <em>AI Innovation &amp; Product Development</em>, a three-day workshop I ran for final-year B.Tech AI &amp; Data Science students.</p>
<ol type="1">
<li><a href="../../posts/when-to-use-rag/index.html">When to use RAG, and when a long context window is enough</a></li>
<li><a href="../../posts/basic-rag-from-scratch/index.html">Basic RAG from scratch</a></li>
<li><a href="../../posts/hybrid-search-bm25-reranking/index.html">Hybrid search: BM25, embeddings and a reranker</a></li>
<li><a href="../../posts/rag-real-documents-chroma/index.html">RAG on real documents: query rewriting, chunking, metadata and Chroma</a></li>
<li><a href="../../posts/agentic-rag-crag-adaptive-react/index.html">Agentic RAG: corrective, adaptive and ReAct</a></li>
</ol>
<p>All notebooks: <a href="https://github.com/Zilch123/ai-workshop/tree/main/output/day1">github.com/Zilch123/ai-workshop</a></p>
</div>
</div>
</div>
<section id="the-workshop" class="level2">
<h2 class="anchored" data-anchor-id="the-workshop">The workshop</h2>
<p>This year I ran the final-year module of a skill development program by AIC-PECF (the Atal Incubation Centre at Pondicherry Engineering College Foundation) for AKT Memorial College of Engineering and Technology. The module was called <em>AI Innovation &amp; Product Development</em>, and it ran for three days:</p>
<ul>
<li><strong>Day 1:</strong> RAG, from a 20-line retriever up to an agent that decides when to search.</li>
<li><strong>Day 2:</strong> using a coding agent to build software, and checking what it writes.</li>
<li><strong>Day 3:</strong> a hands-on build of a proof-of-concept web app.</li>
</ul>
<p>The students were in their final year of B.Tech in AI &amp; Data Science, so they knew the ML theory. What they hadn’t done much was build an LLM application end to end. The RAG day was all Colab notebooks, and this series is a write-up of them.</p>
<p>The notebooks used a small open model (Llama 3.1 8B Instruct, served by Nscale through the OpenAI Python client) and small local models for embeddings and reranking. Everything runs on a free Colab instance.</p>
</section>
<section id="is-rag-dead" class="level2">
<h2 class="anchored" data-anchor-id="is-rag-dead">Is RAG dead?</h2>
<p>This question always comes up. Models now accept hundreds of thousands, even a million, tokens. Why not paste every document into the prompt and skip retrieval?</p>
<p>Two reasons.</p>
<p><strong>Long context isn’t the same as good use of long context.</strong> A model that <em>accepts</em> a million tokens doesn’t use all of them equally well. The <a href="https://github.com/adobe-research/NoLiMa">NoLiMa benchmark</a> shows that models get much worse at finding a fact as the context grows, especially when the fact doesn’t share obvious words with the question. A short, relevant context still beats a long, noisy one.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://timothdev.com/posts/when-to-use-rag/nolima-context-accuracy.png" class="img-fluid figure-img"></p>
<figcaption>Accuracy on the NoLiMa benchmark as the context grows from 1K to 32K tokens, for a few of the models it tested (Gemini 2.5 Flash without thinking). Every model gets worse. Llama 3.1 8B, the model we used in the workshop, drops from 65.7% to 14.2%. Data from the <a href="https://arxiv.org/abs/2502.05167">NoLiMa paper</a> (Modarressi et al., ICML 2025).</figcaption>
</figure>
</div>
<p>Most of these models claim to support 128K tokens or more. At 32K, half of the ones shown here are below 50% accuracy.</p>
<p><strong>Retrieval does jobs a prompt can’t.</strong> It picks the right 3 chunks out of 10,000 tickets. It lets you cite a source. It lets you filter by who is allowed to see what.</p>
<p>What <em>has</em> changed is how often RAG is the right call. A few years ago every chatbot demo had a vector database behind it. Now, in enterprise systems, RAG is used only where retrieval is actually part of the problem.</p>
<blockquote class="blockquote">
<p>An engineer doesn’t just know how to use a tool. They know when to use it.</p>
</blockquote>
</section>
<section id="a-simple-decision-table" class="level2">
<h2 class="anchored" data-anchor-id="a-simple-decision-table">A simple decision table</h2>
<p>This is the table I gave the students. The question to ask is: <strong>do I already know where the answer is?</strong> If yes, you probably don’t need retrieval.</p>
<p><strong>Usually not worth it (use long context or load the file directly):</strong></p>
<ul>
<li>Find a clause in one known contract</li>
<li>Summarise one document</li>
<li>Answer questions over a few documents that fit comfortably in the context</li>
<li>Explain a known file or module in a codebase</li>
<li>Extract fields from a known PDF or form</li>
<li>Reason over a few sources you’ve already picked</li>
</ul>
<p><strong>Maybe (try long context first):</strong></p>
<ul>
<li>Compare 5 to 10 known documents. RAG helps only if they’re too big.</li>
<li>A corpus that fits in context but is mostly irrelevant. Retrieving first improves the signal-to-noise ratio.</li>
<li>Searching a large codebase for a concept. You need search, but grep or BM25 often beats vectors.</li>
</ul>
<p><strong>Worth it:</strong></p>
<ul>
<li>A large knowledge base where you don’t know where the answer is</li>
<li>Thousands of support tickets or contracts where only a few are relevant</li>
<li>Finding similar incidents or cases where the wording differs</li>
<li>Documents that change often, or facts newer than the model’s training data</li>
<li>Answers that need citations</li>
<li>Enterprise data with per-user or per-document permissions (RAG plus access filtering)</li>
<li>Legal and compliance knowledge bases, where provenance matters</li>
<li>Very large corpora where sending everything would cost too much</li>
</ul>
<p><strong>RAG alone isn’t enough:</strong></p>
<ul>
<li>Live or structured data from databases and APIs. Fetch it with a tool, not a vector search.</li>
<li>Exact identifiers and error codes. Keyword search (grep, SQL, BM25) usually wins here. <a href="../../posts/hybrid-search-bm25-reranking/index.html">Part 3</a> covers this.</li>
</ul>
</section>
<section id="whats-next" class="level2">
<h2 class="anchored" data-anchor-id="whats-next">What’s next</h2>
<p><a href="../../posts/basic-rag-from-scratch/index.html">Part 2</a> builds the simplest possible RAG pipeline from scratch: chunk, embed, compare, prompt. No framework and no vector database, so every step is visible.</p>
<p><strong>Notebook:</strong> <a href="https://github.com/Zilch123/ai-workshop/blob/main/output/day1/rag_when_to_use.ipynb">rag_when_to_use.ipynb</a></p>


</section>

 ]]></description>
  <category>GenAI</category>
  <category>RAG</category>
  <category>Workshop</category>
  <guid>https://timothdev.com/posts/when-to-use-rag/</guid>
  <pubDate>Fri, 18 Sep 2026 00:00:00 GMT</pubDate>
  <media:content url="https://timothdev.com/posts/when-to-use-rag/nolima-context-accuracy.png" medium="image" type="image/png" height="86" width="144"/>
</item>
<item>
  <title>A Simple Tech News Aggregator with RSS, FastAPI and React</title>
  <dc:creator>Timoth Dev</dc:creator>
  <link>https://timothdev.com/posts/tech-news-aggregator/</link>
  <description><![CDATA[ 






<p>I follow a handful of blogs and newsletters across different topics, and checking each one separately got tedious. So at a weekend hackathon run by <a href="https://fshm.org">FSHM</a>, I built a small aggregator: pick a topic and a time period, and it pulls the articles from every feed for that topic into one list, newest first.</p>
<p>Code: <a href="https://github.com/Zilch123/Tech-News-Aggregator">Zilch123/Tech-News-Aggregator</a></p>
<section id="why-rss" class="level2">
<h2 class="anchored" data-anchor-id="why-rss">Why RSS</h2>
<p>Most blogs and newsletters still publish an RSS feed, which means no scraping, no API keys and no rate limits. A feed is just an XML file with the latest posts, and <code>feedparser</code> turns it into Python objects.</p>
</section>
<section id="the-feeds" class="level2">
<h2 class="anchored" data-anchor-id="the-feeds">The feeds</h2>
<p>Topics and their feeds live in a YAML file, so adding a source doesn’t need a code change:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode yaml code-with-copy"><code class="sourceCode yaml"><span id="cb1-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">feeds</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span></span>
<span id="cb1-2"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">  </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">"datascience"</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span></span>
<span id="cb1-3"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">    </span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">-</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;"> </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">name</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;"> </span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"KDNuggets"</span></span>
<span id="cb1-4"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">      </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">url</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;"> </span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"https://www.kdnuggets.com/feed"</span></span>
<span id="cb1-5"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">    </span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">-</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;"> </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">name</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;"> </span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Analytics Vidhya"</span></span>
<span id="cb1-6"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">      </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">url</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;"> </span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"https://www.analyticsvidhya.com/feed/"</span></span>
<span id="cb1-7"></span>
<span id="cb1-8"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">  </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">"Generative AI"</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span></span>
<span id="cb1-9"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">    </span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">-</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;"> </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">name</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;"> </span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Hugging Face Blog"</span></span>
<span id="cb1-10"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">      </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">url</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;"> </span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"https://huggingface.co/blog/feed.xml"</span></span></code></pre></div></div>
<p>The repo also has feeds for front end, back end, operating systems, OpenStreetMap and mathematics.</p>
</section>
<section id="the-backend" class="level2">
<h2 class="anchored" data-anchor-id="the-backend">The backend</h2>
<p>The backend is a FastAPI app with one endpoint:</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="at" style="color: #657422;
background-color: null;
font-style: inherit;">@app.get</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"/fetch_articles/"</span>)</span>
<span id="cb2-2"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> fetch_articles_api(</span>
<span id="cb2-3">    topic: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Query(..., description<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;">"Specify a topic"</span>),</span>
<span id="cb2-4">    time_period: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Query(..., description<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;">"Specify a time period"</span>),</span>
<span id="cb2-5">):</span>
<span id="cb2-6">    articles <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> fetch_articles(topic, time_period)</span>
<span id="cb2-7">    <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;">"topic"</span>: topic, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"time_period"</span>: time_period, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"articles"</span>: articles}</span></code></pre></div></div>
<p>For a request, it:</p>
<ol type="1">
<li>Looks up the feeds for the topic.</li>
<li>Fetches them in parallel with a thread pool, since most of the time is spent waiting on the network.</li>
<li>Parses each entry’s date with <code>dateutil</code>, which handles the different date formats feeds use.</li>
<li>Drops anything older than the chosen period (last week, month, year, 3 years, 5 years or all time).</li>
<li>Sorts what’s left, newest first.</li>
</ol>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> ThreadPoolExecutor(max_workers<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;">5</span>) <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> executor:</span>
<span id="cb3-2">    article_lists <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;">list</span>(executor.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">map</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>._fetch_feed, feeds))</span>
<span id="cb3-3">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> articles <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> article_lists:</span>
<span id="cb3-4">        all_articles.extend(articles)</span></code></pre></div></div>
<p>Each article comes back with a title, summary, link and timestamp.</p>
</section>
<section id="the-frontend" class="level2">
<h2 class="anchored" data-anchor-id="the-frontend">The frontend</h2>
<p>The frontend is React with Vite and Tailwind. It has two dropdowns (topic and time period) and a search button. Results show as cards with the title, summary, publish date and a link to the original article.</p>
</section>
<section id="running-it" class="level2">
<h2 class="anchored" data-anchor-id="running-it">Running it</h2>
<p>Everything runs with Docker Compose. From the <code>project</code> folder:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb4-1"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">docker</span> compose up</span></code></pre></div></div>
<p>The frontend runs at <code>localhost:5173</code> and the API at <code>localhost:8000</code>.</p>
<p>To run without Docker, start the backend first (<code>cd backend &amp;&amp; bash run.sh</code>), then the frontend (<code>cd frontend &amp;&amp; npm run dev</code>).</p>
</section>
<section id="adding-a-topic" class="level2">
<h2 class="anchored" data-anchor-id="adding-a-topic">Adding a topic</h2>
<p>Add the topic and its feed URLs to <code>rss_feeds.yaml</code>, then add the topic name to the <code>TOPICS</code> list in <code>App.jsx</code> so it shows up in the dropdown.</p>


</section>

 ]]></description>
  <category>Hackathon</category>
  <category>Software Engineering</category>
  <guid>https://timothdev.com/posts/tech-news-aggregator/</guid>
  <pubDate>Sat, 23 Nov 2024 00:00:00 GMT</pubDate>
</item>
<item>
  <title>Following the Money with Latvian Open Data: Winning an Anti-Corruption Hackathon</title>
  <dc:creator>Timoth Dev</dc:creator>
  <link>https://timothdev.com/posts/anti-corruption-open-data-hackathon/</link>
  <description><![CDATA[ 






<p>In January 2024 I took part in the <a href="https://delna.lv/en/2024/01/05/press-release-transparency-international-latvia-invites-to-participate-in-the-anti-corruption-open-data-hackathon/">Anti-Corruption Open Data Hackathon</a>, organised by Transparency International Latvia (Delna) together with the Estonian and Finnish chapters and funded by the Nordic Council of Ministers. It ran online over two days, 25 and 26 January. The brief was simple: use open data to spot possible corruption, conflicts of interest or weak governance.</p>
<p>I worked on it solo, and the project won first place.</p>
<p>Code: <a href="https://github.com/Zilch123/Anti-corruption-open-data-hackathon">Zilch123/Anti-corruption-open-data-hackathon</a></p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://timothdev.com/posts/anti-corruption-open-data-hackathon/title.jpg" class="img-fluid figure-img"></p>
<figcaption>Title slide of the final presentation</figcaption>
</figure>
</div>
<section id="the-idea-a-risk-index-at-two-levels" class="level2">
<h2 class="anchored" data-anchor-id="the-idea-a-risk-index-at-two-levels">The idea: a risk index at two levels</h2>
<p>Corruption is hard to see in any single dataset. A political donation is legal. Owning several companies is legal. The interesting cases are where these things overlap.</p>
<p>I proposed a corruption and anti-money-laundering (AML) risk index that works at two levels:</p>
<ul>
<li><strong>Macro:</strong> which government sectors are most exposed, scored top-down from legislation and open data.</li>
<li><strong>Micro:</strong> which individuals and companies stand out, scored bottom-up from personal and business data.</li>
</ul>
<p>Each index is <em>rules plus outlier detection</em>. Combining them narrows the focus to people who score high on the micro index and also work in, or are closely linked to, a high-risk sector. Those are the cases where investigators would check bank records and financial statements.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://timothdev.com/posts/anti-corruption-open-data-hackathon/macro-micro.jpg" class="img-fluid figure-img"></p>
<figcaption>Combining the macro and micro indexes</figcaption>
</figure>
</div>
<p>In two days I built the micro level for Latvia.</p>
</section>
<section id="the-data" class="level2">
<h2 class="anchored" data-anchor-id="the-data">The data</h2>
<p>All four datasets are public:</p>
<table class="caption-top table">
<colgroup>
<col style="width: 50%">
<col style="width: 50%">
</colgroup>
<thead>
<tr class="header">
<th>Dataset</th>
<th>Source</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Political donations</td>
<td>KNAB (Latvia’s anti-corruption bureau) donations database</td>
</tr>
<tr class="even">
<td>Beneficial owners of companies</td>
<td>Latvian open data portal</td>
</tr>
<tr class="odd">
<td>Public-benefit organisations</td>
<td>Latvian open data portal</td>
</tr>
<tr class="even">
<td>Officers of offshore companies</td>
<td>Leaked offshore records (Panama and Pandora Papers style data)</td>
</tr>
</tbody>
</table>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://timothdev.com/posts/anti-corruption-open-data-hackathon/process-flow.jpg" class="img-fluid figure-img"></p>
<figcaption>The overall process flow</figcaption>
</figure>
</div>
</section>
<section id="joining-people-across-datasets" class="level2">
<h2 class="anchored" data-anchor-id="joining-people-across-datasets">Joining people across datasets</h2>
<p>There’s no shared person ID across these datasets, so the first job is building one. For beneficial owners, I combined the name with the masked personal code and stripped out everything that isn’t a letter or digit:</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">beneficial_owners[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'PrimaryKey'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> beneficial_owners[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'forename'</span>] <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> beneficial_owners[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'surname'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span>  beneficial_owners[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'latvian_identity_number_masked'</span>]</span>
<span id="cb1-2">beneficial_owners[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'PrimaryKey'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> beneficial_owners[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'PrimaryKey'</span>].<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>.replace(<span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r'</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">\W</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">''</span>, regex<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></code></pre></div></div>
<p>Then I grouped by person, counting how many companies each one owns, and did the same for donors: total donated, number of donations and number of different parties. Joining the two gives business owners who donate to political parties.</p>
</section>
<section id="simple-rules-first" class="level2">
<h2 class="anchored" data-anchor-id="simple-rules-first">Simple rules first</h2>
<p>Rules are easy to explain to journalists and investigators, so I started there:</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">cond1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> businessOwnersWhoDonateToPoliticalParties[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Unique_parties_donated'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span>
<span id="cb2-2">cond2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> businessOwnersWhoDonateToPoliticalParties[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Total_donation_EUR'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10000</span></span>
<span id="cb2-3">cond3 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> businessOwnersWhoDonateToPoliticalParties[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'NumberOfLegalEntities'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span></code></pre></div></div>
<p>Someone who has given more than €10,000 to more than two different parties, or who donates to several parties and owns several companies, is worth a look. I also cross-checked owners’ company registration numbers against the public-benefit organisation register, to find donors who run organisations with public-benefit status.</p>
</section>
<section id="matching-against-offshore-leaks" class="level2">
<h2 class="anchored" data-anchor-id="matching-against-offshore-leaks">Matching against offshore leaks</h2>
<p>The offshore leak data has no Latvian personal codes, only names, and names are written inconsistently. So I filtered the leak data to Latvia and used fuzzy matching, keeping only very close matches (a score of 95 or more):</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" 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;">from</span> thefuzz <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> fuzz, process</span>
<span id="cb3-2"></span>
<span id="cb3-3"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> find_best_match(name, choices):</span>
<span id="cb3-4">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> process.extractOne(name, choices, scorer<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>fuzz.token_set_ratio)</span>
<span id="cb3-5"></span>
<span id="cb3-6">beneficial_owners_df_agg[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'best_match'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> beneficial_owners_df_agg[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'name'</span>].<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">apply</span>(</span>
<span id="cb3-7">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">lambda</span> x: find_best_match(x, nodes_officers_LV[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'name'</span>]))</span></code></pre></div></div>
<p>Even at 95, a name match is only a lead. Two different people can share a name.</p>
</section>
<section id="letting-clustering-find-the-outliers" class="level2">
<h2 class="anchored" data-anchor-id="letting-clustering-find-the-outliers">Letting clustering find the outliers</h2>
<p>Rules only catch what you think to look for. To find unusual combinations, I merged everything into one table per person (companies owned, donations, number of parties, offshore match) and ran K-means with 4 clusters, chosen with the elbow method:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb4-1">kmeans <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> KMeans(n_clusters<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>, random_state<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;">42</span>)</span>
<span id="cb4-2">merged_df_encoded[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'cluster'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> kmeans.fit_predict(merged_df_encoded)</span></code></pre></div></div>
<table class="caption-top table">
<thead>
<tr class="header">
<th>Cluster</th>
<th>People</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>0</td>
<td>133,685</td>
</tr>
<tr class="even">
<td>1</td>
<td>43</td>
</tr>
<tr class="odd">
<td>2</td>
<td>11</td>
</tr>
<tr class="even">
<td>3</td>
<td>64</td>
</tr>
</tbody>
</table>
<p>Almost everyone lands in one big cluster. The roughly 100 people in the three small clusters are the outliers, and that’s the shortlist for human review.</p>
</section>
<section id="what-a-high-score-does-and-doesnt-mean" class="level2">
<h2 class="anchored" data-anchor-id="what-a-high-score-does-and-doesnt-mean">What a high score does and doesn’t mean</h2>
<p>I made a point of this in the presentation, and it’s worth repeating:</p>
<ul>
<li><strong>A high score isn’t proof of anything.</strong> It means the pattern is unusual, not that anyone did something wrong.</li>
<li><strong>People still have to gather the evidence.</strong> Only human investigation can produce something that would stand up in court.</li>
<li><strong>Open data can be incomplete or wrong.</strong> The output is only as good as the registers it comes from.</li>
</ul>
<p>That’s also why this post doesn’t name anyone.</p>
</section>
<section id="whats-next" class="level2">
<h2 class="anchored" data-anchor-id="whats-next">What’s next</h2>
<p>The next step I’d most like to take is adding public procurement data: do donors, or companies they own, win contracts from institutions linked to the parties they funded, especially around the time of the donation? That needs contract-level data with company registration numbers, which Latvia’s Procurement Monitoring Bureau publishes. At the macro level, LLMs could help assess anti-corruption and AML legislation across sectors.</p>
<p>Open data makes this kind of analysis possible for anyone with a laptop. The hard part isn’t the code, it’s joining messy records and being careful about what the results actually mean.</p>


</section>

 ]]></description>
  <category>Hackathon</category>
  <category>Data Analysis</category>
  <guid>https://timothdev.com/posts/anti-corruption-open-data-hackathon/</guid>
  <pubDate>Sun, 04 Feb 2024 00:00:00 GMT</pubDate>
  <media:content url="https://timothdev.com/posts/anti-corruption-open-data-hackathon/process-flow.jpg" medium="image" type="image/jpeg"/>
</item>
<item>
  <title>Predicting High-Impact IT Tickets: Notes from a Small Classification Project</title>
  <dc:creator>Timoth Dev</dc:creator>
  <link>https://timothdev.com/posts/it-ticket-impact-prediction/</link>
  <description><![CDATA[ 






<p>These are my notes from a small project: predicting which IT support tickets will turn out to be high impact, so the IT team can prioritise them as soon as they’re opened. I’m writing it down mainly for the lessons, which apply to most tabular classification problems.</p>
<p>Code: <a href="https://github.com/Zilch123/IT-Ticket-Impact-Prediction">Zilch123/IT-Ticket-Impact-Prediction</a></p>
<section id="the-problem" class="level2">
<h2 class="anchored" data-anchor-id="the-problem">The problem</h2>
<p>The data is an incident log of about 99,000 records. Each ticket has an impact level: high, medium or low. A few things stood out in the exploration:</p>
<ul>
<li><strong>95% of tickets are medium impact.</strong> High-impact tickets are only about 2.5%.</li>
<li><strong>Knowledge documents are used unevenly.</strong> None of the high-impact tickets had a knowledge document attached, compared with 20% of medium and 40% of low.</li>
<li><strong>A few groups dominate.</strong> 30% of tickets were opened by one group, and 30% were handled by one support group.</li>
<li><strong>A handful of service categories cover almost half the tickets.</strong></li>
</ul>
<p>The business need is to catch high-impact tickets, so I turned it into a binary problem: high versus everything else.</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">df_solution[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'impact'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df_solution[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'impact'</span>].<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">map</span>({<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'1 - High'</span>:<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'2 - Medium'</span>:<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>,<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'3 - Low'</span>:<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> })</span></code></pre></div></div>
</section>
<section id="lesson-1-only-use-what-you-know-at-prediction-time" class="level2">
<h2 class="anchored" data-anchor-id="lesson-1-only-use-what-you-know-at-prediction-time">Lesson 1: only use what you know at prediction time</h2>
<p>This was the most important decision in the whole project. Some columns describe the ticket when it’s opened: who raised it, when, which category. Others are filled in later, while the ticket is being solved: the support group, whether a knowledge document was used, the linked problem or change request.</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">ticket_attributes <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;">'ID'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'ID_status'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'active'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'count_reassign'</span>,</span>
<span id="cb2-2">       <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'count_opening'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'count_updated'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'ID_caller'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'opened_by'</span>,</span>
<span id="cb2-3">       <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'opened_time'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Created_by'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'created_at'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'updated_by'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'updated_at'</span>,</span>
<span id="cb2-4">       <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'type_contact'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'location'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'category_ID'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'user_symptom'</span>]</span>
<span id="cb2-5"></span>
<span id="cb2-6">solution_attributes <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;">'Support_group'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'support_incharge'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Doc_knowledge'</span>,</span>
<span id="cb2-7">       <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'confirmation_check'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'impact'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'notify'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'problem_ID'</span>,</span>
<span id="cb2-8">       <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'change_request'</span>]</span></code></pre></div></div>
<p>The solution attributes would make the model look great, because the knowledge-document column alone separates high impact well. But they don’t exist yet when the ticket is opened, which is exactly when we want the prediction. Using them is target leakage, so the model only gets the ticket attributes.</p>
</section>
<section id="lesson-2-clean-the-odd-encodings-first" class="level2">
<h2 class="anchored" data-anchor-id="lesson-2-clean-the-odd-encodings-first">Lesson 2: clean the odd encodings first</h2>
<p>Missing values were stored as <code>?</code>, and one status column used <code>-100</code>. Neither shows up as null until you replace them:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1">df_ticket <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df_ticket.replace(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'?'</span>, np.nan)</span>
<span id="cb3-2">df_ticket.loc[df_ticket[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'ID_status'</span>]<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;">'-100'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'ID_status'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.nan</span></code></pre></div></div>
</section>
<section id="lesson-3-timestamps-hold-useful-features" class="level2">
<h2 class="anchored" data-anchor-id="lesson-3-timestamps-hold-useful-features">Lesson 3: timestamps hold useful features</h2>
<p>Raw timestamps aren’t useful to a tree model, but things derived from them are. I extracted the weekday and hour for the created, opened and updated times. I also added the average opening hour per ticket ID and per category, then dropped the raw timestamps.</p>
</section>
<section id="lesson-4-plan-for-categories-you-havent-seen" class="level2">
<h2 class="anchored" data-anchor-id="lesson-4-plan-for-categories-you-havent-seen">Lesson 4: plan for categories you haven’t seen</h2>
<p>Many categorical columns had values that appear only once or twice. These don’t help the model learn, and new ones will show up in production. I replaced rare values (3 occurrences or fewer) with <code>Unknown</code>:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb4-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> clip_cat_labels(df: pd.DataFrame, cat_columns: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">list</span>, label_count<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;">3</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> pd.DataFrame:</span>
<span id="cb4-2">    df_cat_clipped <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df.copy()</span>
<span id="cb4-3">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> col <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> cat_columns:</span>
<span id="cb4-4">        value_count_df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df[col].value_counts().reset_index()</span>
<span id="cb4-5">        cat_values_with_low_count <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> value_count_df[value_count_df[col]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span>label_count][<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'index'</span>].tolist()</span>
<span id="cb4-6">        cat_clipped <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df[col].mask(df[col].isin(cat_values_with_low_count))</span>
<span id="cb4-7">        df_cat_clipped[col] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cat_clipped</span>
<span id="cb4-8">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> df_cat_clipped</span></code></pre></div></div>
<p>The label encoders are fitted with an <code>Unknown</code> class included and saved. At inference time, any value the encoder hasn’t seen maps to <code>Unknown</code> instead of crashing.</p>
</section>
<section id="lesson-5-for-imbalance-try-the-simple-fix-first" class="level2">
<h2 class="anchored" data-anchor-id="lesson-5-for-imbalance-try-the-simple-fix-first">Lesson 5: for imbalance, try the simple fix first</h2>
<p>With only 2.5% positives, the model needs help to pay attention to the rare class. I tried SMOTE and ADASYN oversampling, but neither beat simple class weights:</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"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.utils <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> class_weight</span>
<span id="cb5-2">classes_weights <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> class_weight.compute_sample_weight(class_weight<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;">'balanced'</span>, y<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>y_train_xgb)</span>
<span id="cb5-3"></span>
<span id="cb5-4">model_xgb <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> XGBClassifier(max_depth<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;">16</span>, n_estimators<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>, learning_rate<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.2</span>,</span>
<span id="cb5-5">                          min_child_weight<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>, gamma<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.5</span>)</span>
<span id="cb5-6">model_xgb.fit(X_train_xgb, y_train_xgb, sample_weight<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>classes_weights)</span></code></pre></div></div>
<p>I also tried KNN, iterative and MissForest imputation for missing values. None improved the metrics over filling with <code>Unknown</code>. It’s worth writing down what didn’t work, so you don’t try it again.</p>
</section>
<section id="lesson-6-different-models-give-different-trade-offs" class="level2">
<h2 class="anchored" data-anchor-id="lesson-6-different-models-give-different-trade-offs">Lesson 6: different models give different trade-offs</h2>
<p>I trained two models and then combined them:</p>
<ul>
<li><strong>XGBoost</strong>, with features chosen using <code>SelectFromModel</code>. It catches most high-impact tickets but raises many false alarms.</li>
<li><strong>Random forest</strong>, with settings found using auto-sklearn. It’s precise but misses many.</li>
<li><strong>A soft-voting ensemble</strong> of the two, which averages their probabilities. Changing each model’s weight moves the balance between precision and recall.</li>
</ul>
<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">eclf <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> EnsembleVoteClassifier(clfs<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[model_rf, model_xgb], weights<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="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], voting<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;">'soft'</span>)</span>
<span id="cb6-2">eclf.fit(X_train_xgb, y_train)</span></code></pre></div></div>
<p>Results on a 5% hold-out set kept aside from the start, for the high-impact class:</p>
<table class="caption-top table">
<thead>
<tr class="header">
<th>Model</th>
<th>Recall</th>
<th>Precision</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>XGBoost</td>
<td><strong>0.89</strong></td>
<td>0.36</td>
</tr>
<tr class="even">
<td>Ensemble (equal weights)</td>
<td>0.71</td>
<td><strong>0.85</strong></td>
</tr>
<tr class="odd">
<td>Random forest</td>
<td>0.54</td>
<td>0.94</td>
</tr>
</tbody>
</table>
<p>Which one is “best” is a business decision, not a modelling one. If every missed high-impact ticket is costly and the team is happy to double-check alerts, the XGBoost model (89% recall) is the better fit. If too many false alarms mean people start ignoring them, the ensemble (85% precision) is safer.</p>
</section>
<section id="taking-it-further" class="level2">
<h2 class="anchored" data-anchor-id="taking-it-further">Taking it further</h2>
<p>If the IT team found the prototype useful, the next steps would be:</p>
<ul>
<li><strong>Serve it</strong> with a FastAPI service in a container, with a CI/CD pipeline.</li>
<li><strong>Pilot it</strong> with a small group of IT staff using the predictions, compared against a group working the usual way, to check it actually saves time.</li>
<li><strong>Monitor it</strong> for data drift (for example, a KS test on the input features) and model drift (tracking recall and F1 over time), with automatic alerts.</li>
<li><strong>Track experiments</strong> with a tool like MLflow, and retrain as more labelled data comes in.</li>
</ul>
<p>The same data could support other uses: suggesting which support group a ticket should go to, predicting the related problem ID, or recommending knowledge documents.</p>
</section>
<section id="what-id-check-next-time" class="level2">
<h2 class="anchored" data-anchor-id="what-id-check-next-time">What I’d check next time</h2>
<p>Looking back, the data looks like an event log, where the same incident appears in several rows as it’s updated. I split the data randomly by row, and used the incident ID as a feature. That means rows from the same incident can end up in both training and test sets, which can make the scores look better than they really are. Next time I’d split by incident ID (for example with <code>GroupShuffleSplit</code>) and drop the ID itself as a feature.</p>


</section>

 ]]></description>
  <category>Machine Learning</category>
  <guid>https://timothdev.com/posts/it-ticket-impact-prediction/</guid>
  <pubDate>Fri, 28 Apr 2023 00:00:00 GMT</pubDate>
</item>
<item>
  <title>Forecasting Product Demand with SARIMA</title>
  <dc:creator>Timoth Dev</dc:creator>
  <link>https://timothdev.com/posts/demand-forecasting-sarima/</link>
  <description><![CDATA[ 






<p>Demand forecasting means predicting how much of a product people will buy. Manufacturers use it to plan production, and retailers use it to decide what to stock. Get it wrong one way and you’re left with unsold stock, the other way and you run out.</p>
<p>I used it as a hands-on way to learn classical time series forecasting. The notebook started from Susan Li’s well-known walkthrough, <a href="https://www.kdnuggets.com/2018/09/end-to-end-project-time-series-analysis-forecasting-python.html">An End-to-End Project on Time Series Analysis and Forecasting with Python</a>, which uses the same Superstore dataset, and I extended it to compare the three product categories.</p>
<p>Code: <a href="https://github.com/Zilch123/DemandForecast">Zilch123/DemandForecast</a></p>
<section id="the-data" class="level2">
<h2 class="anchored" data-anchor-id="the-data">The data</h2>
<p>The Superstore dataset has about 10,000 order lines from 2014 to 2017, across three categories: furniture, office supplies and technology. Each order has a date and a sales value.</p>
<p>I started with furniture. The steps to turn raw orders into a time series:</p>
<ol type="1">
<li>Keep only the order date and sales.</li>
<li>Add up sales per day.</li>
<li>Resample to monthly, taking the average daily sales for each month.</li>
</ol>
<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">furniture <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> furniture.groupby(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Order Date'</span>)[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Sales'</span>].<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>().reset_index()</span>
<span id="cb1-2">furniture <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> furniture.set_index(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Order Date'</span>)</span>
<span id="cb1-3">y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> furniture[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Sales'</span>].resample(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'MS'</span>).mean()</span></code></pre></div></div>
<p>Monthly data smooths out the noise of individual days, but it leaves only 48 data points for 4 years. That’s not much, and it limits how complex the model can be.</p>
</section>
<section id="trend-and-seasonality" class="level2">
<h2 class="anchored" data-anchor-id="trend-and-seasonality">Trend and seasonality</h2>
<p>Splitting the series into trend, seasonality and residual shows what we’re dealing with:</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">decomposition <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> sm.tsa.seasonal_decompose(y, model<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;">'additive'</span>)</span>
<span id="cb2-2">decomposition.plot()</span></code></pre></div></div>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://timothdev.com/posts/demand-forecasting-sarima/decomposition.png" class="img-fluid figure-img"></p>
<figcaption>Furniture sales split into trend, seasonal and residual components</figcaption>
</figure>
</div>
<p>There’s a strong yearly pattern: sales drop at the start of every year and peak towards the end. The trend moves around but doesn’t grow much over the 4 years.</p>
</section>
<section id="why-sarima" class="level2">
<h2 class="anchored" data-anchor-id="why-sarima">Why SARIMA</h2>
<p>ARIMA models a series from its own past values (AR), differencing to remove the trend (I) and past forecast errors (MA). SARIMA adds the same three parts again at a seasonal lag, here 12 months. That means it can model the yearly pattern directly, without removing it first.</p>
<p>A SARIMA model is written as (p, d, q) × (P, D, Q, s):</p>
<ul>
<li><strong>p, d, q:</strong> autoregressive order, differencing and moving average order for the month-to-month part</li>
<li><strong>P, D, Q:</strong> the same for the seasonal part</li>
<li><strong>s:</strong> the season length, 12 for monthly data</li>
</ul>
</section>
<section id="picking-the-parameters" class="level2">
<h2 class="anchored" data-anchor-id="picking-the-parameters">Picking the parameters</h2>
<p>I tried every combination of 0 and 1 for each parameter and kept the one with the lowest AIC. AIC rewards a good fit but penalises extra parameters, which matters with only 48 points.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1">p <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> d <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> q <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;">range</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;">2</span>)</span>
<span id="cb3-2">pdq <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;">list</span>(itertools.product(p, d, q))</span>
<span id="cb3-3">seasonal_pdq <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [(x[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>], x[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], x[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>], <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> x <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> pdq]</span>
<span id="cb3-4"></span>
<span id="cb3-5"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> param <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> pdq:</span>
<span id="cb3-6">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> param_seasonal <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> seasonal_pdq:</span>
<span id="cb3-7">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">try</span>:</span>
<span id="cb3-8">            model <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> sm.tsa.statespace.SARIMAX(y, order<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>param, seasonal_order<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>param_seasonal,</span>
<span id="cb3-9">                                              enforce_stationarity<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>, enforce_invertibility<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-10">            results <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> model.fit()</span>
<span id="cb3-11">            <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'ARIMA</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{}</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">x</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{}</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;"> - AIC:</span><span class="sc" 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="bu" style="color: null;
background-color: null;
font-style: inherit;">format</span>(param, param_seasonal, results.aic))</span>
<span id="cb3-12">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">except</span>:</span>
<span id="cb3-13">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">continue</span></span></code></pre></div></div>
<p>The best was (1, 1, 1) × (1, 1, 0, 12), with an AIC of 297.8. Several combinations failed to converge, which is another sign the dataset is small.</p>
</section>
<section id="checking-the-forecasts" class="level2">
<h2 class="anchored" data-anchor-id="checking-the-forecasts">Checking the forecasts</h2>
<p>I compared the model’s one-step-ahead predictions for 2017 against the actual sales:</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://timothdev.com/posts/demand-forecasting-sarima/one-step-forecast.png" class="img-fluid figure-img"></p>
<figcaption>One-step-ahead predictions for 2017 against actual sales</figcaption>
</figure>
</div>
<p>The predictions follow the seasonal pattern well. The RMSE was about 200, against monthly averages of roughly 400 to 1,300.</p>
<p>One caveat I’d point out now: the model was fitted on all the data, including 2017, so this isn’t a true out-of-sample test. A one-step-ahead prediction also gets to see the actual value from the month before. A fairer check is to fit on 2014 to 2016 only, then forecast all of 2017 in one go and compare.</p>
</section>
<section id="forecasting-ahead" class="level2">
<h2 class="anchored" data-anchor-id="forecasting-ahead">Forecasting ahead</h2>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb4-1">pred_uc <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> results.get_forecast(steps<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>)</span>
<span id="cb4-2">pred_ci <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pred_uc.conf_int()</span></code></pre></div></div>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://timothdev.com/posts/demand-forecasting-sarima/long-forecast.png" class="img-fluid figure-img"></p>
<figcaption>100-month forecast with its confidence interval</figcaption>
</figure>
</div>
<p>The forecast keeps the seasonal shape, but the grey confidence interval widens quickly the further out it goes. The model is honest about getting less sure over time.</p>
<p>Two things stand out in this plot:</p>
<ul>
<li><strong>100 months is too far.</strong> Forecasting 8 years ahead from 4 years of history isn’t meaningful. For planning stock, a few months ahead is what matters, and that’s where the interval is narrowest.</li>
<li><strong>The lower bound goes below zero.</strong> Sales can’t be negative, but SARIMA doesn’t know that. Modelling the log of sales would keep forecasts positive.</li>
</ul>
</section>
<section id="comparing-the-categories" class="level2">
<h2 class="anchored" data-anchor-id="comparing-the-categories">Comparing the categories</h2>
<p>Running the same steps for office supplies and technology and plotting the three together:</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://timothdev.com/posts/demand-forecasting-sarima/categories.png" class="img-fluid figure-img"></p>
<figcaption>Monthly sales for furniture, office supplies and technology</figcaption>
</figure>
</div>
<p>All three share the same yearly pattern, low in January and high towards the end of the year. Furniture usually sells more than office supplies per month, probably because each item costs more, although office supplies overtake furniture in a few months. Technology is the most volatile, with sharp spikes.</p>
<p>Because the seasonality is shared, a model per category would work, but so would a single model that uses one category’s sales to help forecast the others.</p>
</section>
<section id="what-id-do-next" class="level2">
<h2 class="anchored" data-anchor-id="what-id-do-next">What I’d do next</h2>
<ul>
<li>Validate properly on a held-out year, as described above.</li>
<li>Model log sales so forecasts stay positive.</li>
<li>Forecast at a finer level, by product or region, which is where stock decisions are actually made.</li>
<li>Compare against simpler baselines (same month last year) and other methods like Prophet or gradient boosting with lag features.</li>
<li>Wrap it in a small Streamlit app, so someone can pick a category and a horizon and see the forecast.</li>
</ul>


</section>

 ]]></description>
  <category>Machine Learning</category>
  <category>Data Analysis</category>
  <guid>https://timothdev.com/posts/demand-forecasting-sarima/</guid>
  <pubDate>Wed, 06 Apr 2022 00:00:00 GMT</pubDate>
  <media:content url="https://timothdev.com/posts/demand-forecasting-sarima/long-forecast.png" medium="image" type="image/png" height="64" width="144"/>
</item>
<item>
  <title>Basic Questions I Ask Junior Data Scientists</title>
  <dc:creator>Timoth Dev</dc:creator>
  <link>https://timothdev.com/posts/junior-data-scientist-interview-questions/</link>
  <description><![CDATA[ 






<p>When I was hiring a junior data scientist at Blackstraw, I used a short interview in two parts: a 20-minute hands-on exercise in a notebook, then a set of theory questions. None of it is hard. The goal is to check the basics and see how the candidate thinks.</p>
<p>The questions and notebook are on GitHub: <a href="https://github.com/Zilch123/Data-Science-Interview">Zilch123/Data-Science-Interview</a></p>
<section id="what-im-actually-looking-for" class="level2">
<h2 class="anchored" data-anchor-id="what-im-actually-looking-for">What I’m actually looking for</h2>
<p>Getting every answer right matters less than three things:</p>
<ul>
<li><strong>Curiosity.</strong> Do they ask about the data, the problem or the business before jumping in?</li>
<li><strong>Clarifying questions.</strong> “Optimise for recall” is vague on purpose. A good candidate asks what it means here before writing code.</li>
<li><strong>Talking through their thinking.</strong> I want to hear why they’re doing something, not just watch them type. A wrong answer explained clearly tells me more than a right answer in silence.</li>
</ul>
</section>
<section id="part-1-the-hands-on-exercise" class="level2">
<h2 class="anchored" data-anchor-id="part-1-the-hands-on-exercise">Part 1: the hands-on exercise</h2>
<p>The data is scikit-learn’s breast cancer dataset: 569 samples, 30 numeric features, and two classes, benign and malignant. Malignant is the positive class (1).</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"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> datasets</span>
<span id="cb1-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> pandas <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> pd</span>
<span id="cb1-3"></span>
<span id="cb1-4">dat <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> datasets.load_breast_cancer()</span>
<span id="cb1-5">df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pd.DataFrame(dat.data, columns<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>dat.feature_names)</span>
<span id="cb1-6">df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'target'</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;">1</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> t <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="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> t <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> dat.target]   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># malignant = 1</span></span></code></pre></div></div>
<section id="q1.-which-variable-is-most-correlated-with-the-target-2-min" class="level3">
<h3 class="anchored" data-anchor-id="q1.-which-variable-is-most-correlated-with-the-target-2-min">Q1. Which variable is most correlated with the target? (2 min)</h3>
<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">df.corr()[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'target'</span>].sort_values()</span></code></pre></div></div>
<p><strong>Answer:</strong> <code>worst concave points</code>, at 0.79. Close behind are <code>worst perimeter</code> (0.78), <code>mean concave points</code> (0.78), <code>worst radius</code> (0.78) and <code>mean perimeter</code> (0.74).</p>
<p>A good candidate also points out that many of these features are measuring the same thing (radius, perimeter and area), so they’re strongly correlated with each other too.</p>
</section>
<section id="q2.-for-the-top-five-whats-the-difference-between-benign-and-malignant-with-tolerance-8-min" class="level3">
<h3 class="anchored" data-anchor-id="q2.-for-the-top-five-whats-the-difference-between-benign-and-malignant-with-tolerance-8-min">Q2. For the top five, what’s the difference between benign and malignant, with tolerance? (8 min)</h3>
<p>“With tolerance” means: don’t just give me the means, show me the spread as well.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1">top <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;">'mean perimeter'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'worst radius'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'mean concave points'</span>,</span>
<span id="cb3-2">       <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'worst perimeter'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'worst concave points'</span>]</span>
<span id="cb3-3">df.groupby(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'target'</span>)[top].agg([<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'mean'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'std'</span>])</span></code></pre></div></div>
<table class="caption-top table">
<thead>
<tr class="header">
<th>Feature</th>
<th>Benign (mean ± std)</th>
<th>Malignant (mean ± std)</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>mean perimeter</td>
<td>78.1 ± 11.8</td>
<td>115.4 ± 21.9</td>
</tr>
<tr class="even">
<td>worst radius</td>
<td>13.4 ± 2.0</td>
<td>21.1 ± 4.3</td>
</tr>
<tr class="odd">
<td>mean concave points</td>
<td>0.026 ± 0.016</td>
<td>0.088 ± 0.034</td>
</tr>
<tr class="even">
<td>worst perimeter</td>
<td>87.0 ± 13.5</td>
<td>141.4 ± 29.5</td>
</tr>
<tr class="odd">
<td>worst concave points</td>
<td>0.074 ± 0.036</td>
<td>0.182 ± 0.046</td>
</tr>
</tbody>
</table>
<p><strong>Answer:</strong> malignant tumours are clearly larger and have more concave points, and the gaps are bigger than the standard deviations, so the classes separate well. Strong candidates plot the distributions, or mention a test like a t-test, instead of stopping at the table.</p>
</section>
<section id="q3.-build-a-logistic-regression-model-optimised-for-recall.-10-min" class="level3">
<h3 class="anchored" data-anchor-id="q3.-build-a-logistic-regression-model-optimised-for-recall.-10-min">Q3. Build a logistic regression model optimised for recall. (10 min)</h3>
<p>Recall matters here because missing a malignant tumour is much worse than a false alarm.</p>
<p>A plain <code>LogisticRegression()</code> on an 80/20 split already gets 0.98 recall and 0.88 precision on malignant cases. Most candidates stop there. A stronger answer:</p>
<ul>
<li>scales the features (logistic regression is sensitive to scale)</li>
<li>uses a stratified split</li>
<li>tunes <code>C</code> with recall as the scoring metric</li>
<li>picks the probability threshold on purpose, instead of using the default 0.5</li>
</ul>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb4-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.model_selection <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> train_test_split, GridSearchCV, cross_val_predict</span>
<span id="cb4-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.pipeline <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> make_pipeline</span>
<span id="cb4-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.preprocessing <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> StandardScaler</span>
<span id="cb4-4"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.linear_model <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> LogisticRegression</span>
<span id="cb4-5"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.metrics <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> precision_recall_curve, classification_report</span>
<span id="cb4-6"></span>
<span id="cb4-7">X, y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df.drop(columns<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;">'target'</span>), df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'target'</span>]</span>
<span id="cb4-8">X_train, X_test, y_train, y_test <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> train_test_split(</span>
<span id="cb4-9">    X, y, test_size<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.2</span>, stratify<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>y, random_state<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="cb4-10"></span>
<span id="cb4-11">pipe <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> make_pipeline(StandardScaler(), LogisticRegression(max_iter<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;">1000</span>))</span>
<span id="cb4-12">grid <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> GridSearchCV(pipe,</span>
<span id="cb4-13">                    {<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"logisticregression__C"</span>: [<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.01</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.1</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;">10</span>],</span>
<span id="cb4-14">                     <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"logisticregression__class_weight"</span>: [<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"balanced"</span>]},</span>
<span id="cb4-15">                    scoring<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;">"recall"</span>, cv<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;">5</span>)</span>
<span id="cb4-16">grid.fit(X_train, y_train)</span>
<span id="cb4-17"></span>
<span id="cb4-18"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># out-of-fold probabilities, so the threshold isn't tuned on data the model has seen</span></span>
<span id="cb4-19">probs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cross_val_predict(grid.best_estimator_, X_train, y_train,</span>
<span id="cb4-20">                          cv<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;">5</span>, method<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;">"predict_proba"</span>)[:, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb4-21">precision, recall, thresholds <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> precision_recall_curve(y_train, probs)</span>
<span id="cb4-22">threshold <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> thresholds[recall[:<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;">&gt;=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.98</span>].<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">max</span>()   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># highest threshold with recall &gt;= 0.98</span></span>
<span id="cb4-23"></span>
<span id="cb4-24">y_pred <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (grid.predict_proba(X_test)[:, <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;">&gt;=</span> threshold).astype(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>)</span>
<span id="cb4-25"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(classification_report(y_test, y_pred))</span></code></pre></div></div>
<p>On my run this gave 0.98 recall and 0.79 precision on the test set. That’s the trade-off: higher recall costs precision. The interesting part of the conversation is how they’d decide where to set it, and whether they ask the clinician or business side what a missed case costs.</p>
</section>
</section>
<section id="part-2-theory-questions" class="level2">
<h2 class="anchored" data-anchor-id="part-2-theory-questions">Part 2: theory questions</h2>
<section id="approaches-for-imbalanced-datasets" class="level3">
<h3 class="anchored" data-anchor-id="approaches-for-imbalanced-datasets">Approaches for imbalanced datasets?</h3>
<ul>
<li>Use the right metric: precision, recall, F1 or PR-AUC, not accuracy.</li>
<li>Resample: oversample the minority class (for example with SMOTE) or undersample the majority. Do it on the training set only.</li>
<li>Use class weights, so mistakes on the minority class cost more.</li>
<li>Tune the decision threshold.</li>
<li>Use stratified splits, so every fold has some minority examples.</li>
<li>Get more minority data if you can.</li>
</ul>
</section>
<section id="your-preprocessing-and-inference-take-6-minutes-in-production.-the-mlops-team-wants-it-real-time.-what-do-you-suggest" class="level3">
<h3 class="anchored" data-anchor-id="your-preprocessing-and-inference-take-6-minutes-in-production.-the-mlops-team-wants-it-real-time.-what-do-you-suggest">Your preprocessing and inference take 6 minutes in production. The MLOps team wants it real-time. What do you suggest?</h3>
<p>The best first answer is “find out where the 6 minutes go”. Profile before changing anything. Common fixes:</p>
<ul>
<li>Precompute heavy features offline and look them up at request time (a feature store or cache).</li>
<li>Load the model once at startup, not on every request.</li>
<li>Replace Python loops with vectorised pandas or NumPy code.</li>
<li>Use a smaller or faster model, or quantise or distil the current one.</li>
<li>Split the work: run what has to be live in real time and batch the rest.</li>
<li>Scale out horizontally if it’s a throughput problem rather than latency.</li>
</ul>
</section>
<section id="what-are-precision-and-recall-when-do-you-prioritise-recall" class="level3">
<h3 class="anchored" data-anchor-id="what-are-precision-and-recall-when-do-you-prioritise-recall">What are precision and recall? When do you prioritise recall?</h3>
<ul>
<li><strong>Precision:</strong> of everything predicted positive, how much was actually positive? TP / (TP + FP).</li>
<li><strong>Recall:</strong> of everything actually positive, how much did we find? TP / (TP + FN).</li>
</ul>
<p>Prioritise recall when missing a positive is expensive: cancer screening, fraud detection or safety faults. Prioritise precision when false alarms are expensive, like spam filters that bin real email.</p>
</section>
<section id="when-do-you-use-the-f1-score" class="level3">
<h3 class="anchored" data-anchor-id="when-do-you-use-the-f1-score">When do you use the F1 score?</h3>
<p>F1 is the harmonic mean of precision and recall. Use it when you care about both, want a single number to compare models, and the classes are imbalanced. It’s low if either precision or recall is low.</p>
</section>
<section id="when-shouldnt-you-use-accuracy" class="level3">
<h3 class="anchored" data-anchor-id="when-shouldnt-you-use-accuracy">When shouldn’t you use accuracy?</h3>
<p>When classes are imbalanced. If 1% of transactions are fraud, a model that always says “not fraud” is 99% accurate and completely useless. Accuracy also treats every mistake as equally costly, which is rarely true.</p>
</section>
<section id="what-is-regularisation-and-when-do-you-use-it" class="level3">
<h3 class="anchored" data-anchor-id="what-is-regularisation-and-when-do-you-use-it">What is regularisation, and when do you use it?</h3>
<p>Regularisation adds a penalty on model weights to the loss, so the model prefers simpler solutions and overfits less.</p>
<ul>
<li><strong>L1 (lasso)</strong> can push weights to exactly zero, so it also does feature selection.</li>
<li><strong>L2 (ridge)</strong> shrinks all weights smoothly and handles correlated features well.</li>
</ul>
<p>Use it when the model overfits (good on training data, worse on validation), when you have many features or few samples, or when features are correlated. In scikit-learn’s <code>LogisticRegression</code>, <code>C</code> is the <em>inverse</em> of the regularisation strength, which candidates often get backwards.</p>
</section>
<section id="how-do-you-compare-two-distributions" class="level3">
<h3 class="anchored" data-anchor-id="how-do-you-compare-two-distributions">How do you compare two distributions?</h3>
<ul>
<li>Start visually: histograms, density plots, box plots or a QQ plot.</li>
<li>Use a test that fits the question: Kolmogorov-Smirnov for the whole distribution, a t-test or Mann-Whitney U for the centre, chi-square for categories.</li>
<li>For data drift in production, use KL or Jensen-Shannon divergence, or the population stability index (PSI).</li>
</ul>
</section>
<section id="what-is-ab-testing" class="level3">
<h3 class="anchored" data-anchor-id="what-is-ab-testing">What is A/B testing?</h3>
<p>A controlled experiment. You randomly split users into two groups, show each a different version, and compare a metric you chose beforehand, like conversion rate. Decide the metric, sample size and duration up front, then use a significance test at the end. The classic mistake is checking the results every day and stopping as soon as they look good.</p>
</section>
<section id="what-types-of-recommender-systems-are-there" class="level3">
<h3 class="anchored" data-anchor-id="what-types-of-recommender-systems-are-there">What types of recommender systems are there?</h3>
<ul>
<li><strong>Collaborative filtering:</strong> recommends from user behaviour (“people who liked this also liked…”). It can be user-based, item-based, or use matrix factorisation.</li>
<li><strong>Content-based:</strong> recommends items similar to what the user already liked, using item features.</li>
<li><strong>Hybrid:</strong> combines the two, which helps with the cold-start problem for new users and items.</li>
</ul>
<p>A popularity-based recommender is a useful baseline to beat.</p>
</section>
<section id="how-does-gradient-descent-work" class="level3">
<h3 class="anchored" data-anchor-id="how-does-gradient-descent-work">How does gradient descent work?</h3>
<p>It minimises a loss function step by step. At each step, compute the gradient of the loss with respect to the parameters, and move the parameters a small amount in the opposite direction. The step size is the learning rate: too big and it overshoots or diverges, too small and it’s slow. Batch gradient descent uses all the data for each step, stochastic uses one sample, and mini-batch (the usual choice) uses a small batch.</p>
</section>
<section id="how-do-pca-and-svd-work" class="level3">
<h3 class="anchored" data-anchor-id="how-do-pca-and-svd-work">How do PCA and SVD work?</h3>
<p>PCA finds new axes (principal components) that capture the most variance in the data. Each one is at right angles to the previous ones. Keeping the first few reduces the number of dimensions while losing as little information as possible.</p>
<p>In practice, PCA is computed with SVD. Centre the data and factor it as X = UΣVᵀ. The columns of V are the principal components, and the singular values in Σ tell you how much variance each one explains. Scale the features first, or the ones with large units will dominate.</p>


</section>
</section>

 ]]></description>
  <category>Career</category>
  <category>Machine Learning</category>
  <guid>https://timothdev.com/posts/junior-data-scientist-interview-questions/</guid>
  <pubDate>Thu, 24 Mar 2022 00:00:00 GMT</pubDate>
</item>
</channel>
</rss>
