<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Varuntej on Medium]]></title>
        <description><![CDATA[Stories by Varuntej on Medium]]></description>
        <link>https://medium.com/@varuntej07?source=rss-ce1906f9f6e6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*kMq_OTdSaZH2zPaA</url>
            <title>Stories by Varuntej on Medium</title>
            <link>https://medium.com/@varuntej07?source=rss-ce1906f9f6e6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 22:40:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@varuntej07/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Tree Communication Collective by Hand: Why the Cost Is 2 log2(N), and When That Beats the Ring]]></title>
            <link>https://medium.com/@varuntej07/tree-communication-collective-by-hand-why-the-cost-is-2-log2-n-and-when-that-beats-the-ring-db91bd1b1d5c?source=rss-ce1906f9f6e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/db91bd1b1d5c</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[collective-communication]]></category>
            <category><![CDATA[aws-neuron]]></category>
            <category><![CDATA[tensor-parallelism]]></category>
            <category><![CDATA[trees]]></category>
            <dc:creator><![CDATA[Varuntej]]></dc:creator>
            <pubDate>Tue, 23 Jun 2026 06:22:39 GMT</pubDate>
            <atom:updated>2026-06-23T06:55:09.072Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vPfYMMK-7fD7P0TpnZoBZg.png" /><figcaption>Tree CC</figcaption></figure><p>The previous <a href="https://medium.com/@varuntej07/why-all-reduce-is-reduce-scatter-all-gather-and-why-is-the-cost-2-n-1-not-n-1-229f3cd73d25">blog </a>traced ring all-reduce and showed its cost is 2(N-1): one N-1 for reduce-scatter, one N-1 for all-gather. The ring is bandwidth optimal, but that 2(N-1) is a problem. The step count grows linearly with the number of cores. At 256 cores the ring takes 510 sequential steps before a single token comes out. For small tensors, where each step is mostly fixed latency rather than data movement, that linear growth is the whole cost.</p><p>Tree all-reduce attacks exactly that weakness. It computes the identical sum and lands the identical result on every core, but instead of passing data around a ring it folds the cores up a binary tree and unfolds the result back down. The cost is 2 log2(N) steps. For 256 cores that is 16 steps instead of 510. This post derives that 2 log2(N) the same way the ring post derived 2(N-1): start from a real matmul, compute the partial sums by hand, then trace every number up the tree and back down until the formula is something you can point at.</p><p>Same four cores, same distinct values, no zeros, because repeated numbers are impossible to follow when the point is watching them move. I reuse the exact matmul from the ring post so you can lay the two traces side by side.</p><h3>Where the partial sums come from</h3><p>One linear layer, Y = X @ W, one token. X is 1 x 4 and W is 4 x 4:</p><pre>X = [ 3  2  1  3 ]        W = [ 5  4  3  2 ]   row 0<br>                              [ 1  4  3  2 ]   row 1<br>                              [ 1  3  4  2 ]   row 2<br>                              [ 4  2  1  5 ]   row 3</pre><p>Computed normally, the answer is one 1 x 4 vector:</p><pre>Y = X @ W = [ 30  29  22  27 ]</pre><p>That is the target every core must end up holding.</p><p>Split across four cores along the contraction dimension. Row-parallel: W cut along its rows, X cut along its matching columns. Core i gets column i of X, a scalar, and row i of W, a length-4 vector:</p><pre>Core 0:  X_0 = 3    W_0 = [ 5  4  3  2 ]<br>Core 1:  X_1 = 2    W_1 = [ 1  4  3  2 ]<br>Core 2:  X_2 = 1    W_2 = [ 1  3  4  2 ]<br>Core 3:  X_3 = 3    W_3 = [ 4  2  1  5 ]</pre><p>Each core computes X_i @ W_i, the scalar times the row, and gets a full 1 x 4 partial sum:</p><pre>Core 0:  3 * [ 5  4  3  2 ]  =  [ 15  12   9   6 ]<br>Core 1:  2 * [ 1  4  3  2 ]  =  [  2   8   6   4 ]<br>Core 2:  1 * [ 1  3  4  2 ]  =  [  1   3   4   2 ]<br>Core 3:  3 * [ 4  2  1  5 ]  =  [ 12   6   3  15 ]</pre><p>Sum down the columns to confirm:</p><pre>position 0:  15 +  2 +  1 + 12 = 30<br>position 1:  12 +  8 +  3 +  6 = 29<br>position 2:   9 +  6 +  4 +  3 = 22<br>position 3:   6 +  4 +  2 + 15 = 27<br><br>Target: [30, 29, 22, 27]</pre><p>These four partial vectors are the input to the tree. The job is the same as any all-reduce: add the four vectors, leave every core holding [30, 29, 22, 27]. What changes is the routing.</p><h3>The structural idea: fold, then unfold</h3><p>The ring threads data through every core in sequence, which is why it pays N-1 per phase. The tree refuses to go through cores one at a time. It pairs them up and collapses pairs in parallel.</p><p>Think about adding four numbers. You can do it sequentially, a+b, then +c, then +d, which is three dependent steps. Or you can do (a+b) and (c+d) at the same time, then add the two results, which is two steps because the first two additions happen simultaneously. The tree is the second strategy applied to whole vectors sitting on different cores. Halve the number of live cores at every level, and you reach a single core holding the full sum in log2(N) levels instead of N-1.</p><p>That handles the reduction, which is data flowing inward to one root core. But the postcondition still demands every core hold the result, so after the root has the sum you reverse the tree and broadcast it back outward, doubling the live cores at each level, another log2(N) levels. Fold up in log2(N), unfold down in log2(N). The total is 2 log2(N), and the 2 is the same structural 2 as the ring: one factor for the reduction inward, one for the broadcast outward. The difference is only how many steps each direction costs.</p><p>Trace both directions.</p><h3>Phase 1: reduce-up, where log2(N) comes from</h3><p>Arrange the four cores as a binary tree. Pair (0,1) and pair (2,3) at the bottom, with core 0 and core 2 as the two sub-roots, and core 0 as the overall root.</p><p>Level 1, distance 1. Within each pair, the odd core sends its whole vector to the even core, which adds it in. Both pairs do this at the same time, in one step.</p><pre>Core 1 sends [ 2  8  6  4 ] to Core 0<br>Core 3 sends [ 12 6  3 15 ] to Core 2</pre><p>The receivers add:</p><pre>Core 0:  [15 12  9  6] + [ 2  8  6  4]  =  [17 20 15 10]<br>Core 2:  [ 1  3  4  2] + [12  6  3 15]  =  [13  9  7 17]</pre><p>State after level 1. Cores 1 and 3 have done their job and drop out. Cores 0 and 2 now each hold a pair-sum:</p><pre>Core 0:  [17 20 15 10]   = P0 + P1<br>Core 1:  (done, idle)<br>Core 2:  [13  9  7 17]   = P2 + P3<br>Core 3:  (done, idle)</pre><p>Level 2, distance 2. The two surviving cores combine. Core 2 sends its whole pair-sum to core 0, which adds it in.</p><pre>Core 2 sends [13 9 7 17] to Core 0</pre><pre>Core 0:  [17 20 15 10] + [13 9 7 17]  =  [30 29 22 27]</pre><p>Core 0 now holds the complete sum [30, 29, 22, 27]. That took 2 steps, which is log2(4). Each step halved the number of active cores: 4 cores, then 2, then 1. Notice no core ever handled a chunk. <em>Every message in the tree is the whole vector</em>. That is the price the tree pays, and we return to it.</p><p>Why log2(N) and not N-1? Because the tree collapses pairs in parallel. The ring forces a partial to walk past every core one at a time, N-1 hops. The tree halves the live set each level, so it reaches the root in the number of times you can halve N, which is log2(N). For N=4 the gap is small, 2 versus 3. For N=256 it is 8 versus 255, and that is the entire reason the tree exists.</p><h3>Phase two: broadcast-down, the second log2(N)</h3><p>The root holds the answer. The postcondition needs it on all four cores. Reverse the tree. The root unfolds the result outward, doubling the live set each level, the mirror image of the fold.</p><p>Level 1, distance 2. Core 0 sends the whole result to core 2, the other sub-root.</p><pre>Core 0 sends [30 29 22 27] to Core 2</pre><pre>Core 0:  [30 29 22 27]<br>Core 2:  [30 29 22 27]</pre><p>Level 2, distance 1. Each sub-root sends to its child. Both happen in the same step.</p><pre>Core 0 sends [30 29 22 27] to Core 1<br>Core 2 sends [30 29 22 27] to Core 3</pre><p>Final state:</p><pre>Core 0:  [30 29 22 27]<br>Core 1:  [30 29 22 27]<br>Core 2:  [30 29 22 27]<br>Core 3:  [30 29 22 27]</pre><p>Every core holds the target. That took 2 steps, again log2(4). The broadcast doubled the informed set each level: 1 core, then 2, then 4. Same shape as the fold, run backward.</p><h3>Adding the two halves</h3><pre>reduce-up:        log2(N) steps   (fold inward, halve live cores each level)<br>broadcast-down:   log2(N) steps   (unfold outward, double informed cores each level)<br>tree all-reduce:  2*log2(N) steps</pre><p>For N=4 that is 2 + 2 = 4 steps, exactly what we traced. The 2 is the same 2 as the ring: one log2(N) to reduce inward, one log2(N) to broadcast outward. Both algorithms are reduce-then-broadcast. They differ only in how each direction is routed, which sets whether each direction costs N-1 or log2(N).</p><p><strong><em>The ring grows linearly. The tree grows logarithmically.</em></strong> <strong><em>If steps were the only thing that mattered, the tree would always win and the ring would not exist.</em></strong></p><h3>The catch — tree is not bandwidth optimal</h3><p>Steps are not the only thing that matters. Look back at what crossed each link.</p><p>In the ring, every message was a chunk of size S/N. Total bytes per link came to 2S(N-1)/N, which flattens to about 2S no matter how many cores you add. That is bandwidth optimal.</p><p>In the tree, every message is the whole tensor S. Core 1 shipped its entire vector to core 0. Core 2 shipped its entire pair-sum to core 0. The root then shipped the entire result down. No chunking ever happens. The links near the root carry full-S messages, and that does not shrink as N grows. The tree’s bandwidth term is log₂N x the ring’s, not because each link carries more bytes (it carries about the same, 2S), but because the full-S transfers lie on a serial dependency chain log₂N deep — you stream S through the pipe log₂N times back-to-back instead of streaming S/N chunks that overlap.</p><p>That sets up the real tradeoff. Model the time of one step as a fixed latency alpha plus the message transfer S_msg / B, where B is link bandwidth:</p><pre>ring time  ~  2(N-1) * (alpha + (S/N)/B)<br>tree time  ~  2 log2(N) * (alpha +  S/B)</pre><p>Two regimes fall out.</p><p>When S is small, the transfer term is tiny and alpha dominates each step. Cost is basically step count times alpha. Fewer steps wins, so the tree wins. This is the latency-bound regime: small tensors, many cores.</p><p>When S is large, the transfer term dominates and the message size matters more than the step count. The ring’s S/N messages beat the tree’s full-S messages, so the ring wins. This is the bandwidth-bound regime: <em>big activation tensors in LLM tensor parallelism, where the ring is the default for good reason.</em></p><p>Plugging in NeuronLink-like numbers, 1 microsecond per hop and 190 GB/s, the crossover for 8 cores sits somewhere around a few hundred kilobytes to a megabyte. Below it the tree is faster, above it the ring takes over. That crossover, not a universal winner, is why a real collective library carries both algorithms and picks based on tensor size and core count at compile time.</p><h3>The one sentence to keep</h3><p>Tree all-reduce is reduce-up plus broadcast-down, each costing log2(N) because the tree halves the live cores every level instead of walking through them one at a time, so the cost is 2 log2(N). It beats the ring’s 2(N-1) on step count for small tensors where latency dominates, and loses on bandwidth for large tensors because every message is the whole tensor instead of a 1/N chunk. Same reduce-then-broadcast skeleton as the ring. Only the routing, and therefore the cost per direction, changes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db91bd1b1d5c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why All-Reduce is Reduce-Scatter + All-Gather? and Why is the Cost 2(N-1), Not (N-1)??]]></title>
            <link>https://medium.com/@varuntej07/why-all-reduce-is-reduce-scatter-all-gather-and-why-is-the-cost-2-n-1-not-n-1-229f3cd73d25?source=rss-ce1906f9f6e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/229f3cd73d25</guid>
            <category><![CDATA[collective-communication]]></category>
            <category><![CDATA[neurons]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[distributed-training]]></category>
            <category><![CDATA[all-reduce-algorithm]]></category>
            <dc:creator><![CDATA[Varuntej]]></dc:creator>
            <pubDate>Mon, 22 Jun 2026 18:33:27 GMT</pubDate>
            <atom:updated>2026-06-22T18:33:27.330Z</atom:updated>
            <content:encoded><![CDATA[<p>Most explanations of all-reduce hand you a diagram of arrows going around a ring and a formula that says the cost is 2(N-1) steps. Then they move on. Nobody tells you why it is 2(N-1) and not (N-1). If you stare at the ring picture you can convince yourself a single lap around the ring is N-1 hops, so where does the second factor of 2 come from? Are we just going around twice for no reason?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V-7LLcz9gqHc0Px7-oWNIA.png" /><figcaption>All-redcue = reduce-scatter + all-gather</figcaption></figure><p>The factor of 2 is not arbitrary and it is not a doubling for safety. It falls directly out of a structural fact: <strong><em>all-reduce is two different collectives glued together</em></strong>. The <em>first is reduce-scatter,</em> which costs N-1 steps. The <em>second is all-gather</em>, which also costs N-1 steps. Add them and you get 2(N-1). The whole blog is going to make that decomposition concrete by tracing real numbers through both halves, so that by the end the 2 is something you can point at rather than something you memorized.</p><p>I am going to use four cores the entire way through, with real partial sums and distinct values, because zeros and ones are impossible to track when the whole point is watching numbers move.</p><h3>What all-reduce has to produce and Where the partial sums actually come from</h3><p>Most all-reduce posts start by asserting some partial vectors out of thin air. That hides the one thing worth seeing: the partials are not given, they are computed, and they come out of a row-parallel matmul. So in this blog we start one step earlier, from the matmul itself.</p><p>Take a single linear layer, Y = X @ W, for one token. X is 1 x 4 and W is 4 x 4:</p><pre>X = [ 3  2  1  3 ]        W = [ 5  4  3  2 ]   row 0<br>                              [ 1  4  3  2 ]   row 1<br>                              [ 1  3  4  2 ]   row 2<br>                              [ 4  2  1  5 ]   row 3</pre><p>The true answer, computed normally, is one 1 x 4 vector:</p><pre>Y = X @ W = [ 30  29  22  27 ]</pre><p>Hold onto [30, 29, 22, 27]. That is the target every core must end up with.</p><p>Now split this across four cores along the contraction dimension. This is a row-parallel split: W is cut along its rows, and X is cut along its matching columns. Core i gets column i of X (a single scalar) and row i of W (a length-4 vector):</p><pre>Core 0:  X_0 = 3    W_0 = [ 5  4  3  2 ]<br>Core 1:  X_1 = 2    W_1 = [ 1  4  3  2 ]<br>Core 2:  X_2 = 1    W_2 = [ 1  3  4  2 ]<br>Core 3:  X_3 = 3    W_3 = [ 4  2  1  5 ]</pre><p>Each core computes X_i @ W_i, which is just the scalar times the row. The result on every core is a full 1 x 4 vector, the same shape as the final answer, but each one is only a partial sum:</p><pre>Core 0:  3 * [ 5  4  3  2 ]  =  [ 15  12   9   6 ]<br>Core 1:  2 * [ 1  4  3  2 ]  =  [  2   8   6   4 ]<br>Core 2:  1 * [ 1  3  4  2 ]  =  [  1   3   4   2 ]<br>Core 3:  3 * [ 4  2  1  5 ]  =  [ 12   6   3  15 ]</pre><p>These four vectors are where every later number in this post comes from. They are computed, not asserted. Verify the target by summing them down the columns:</p><pre>position 0:  15 +  2 +  1 + 12 = 30<br>position 1:  12 +  8 +  3 +  6 = 29<br>position 2:   9 +  6 +  4 +  3 = 22<br>position 3:   6 +  4 +  2 + 15 = 27<br><br>Target: [30, 29, 22, 27]    # accurate</pre><p>That matches X @ W exactly, which confirms the split is correct. The partials are right, none of them is the answer alone, and now all-reduce has a precise job: take these four partial vectors, add them, and leave every core holding the identical [30, 29, 22, 27].</p><p>That word “every” is the whole reason the cost is 2(N-1) and not N-1. Keep watching for it.</p><h3>The reasoning that makes (N-1) tempting and wrong</h3><p>Here is the trap. You might say: there are four partial vectors, addition over four items is three pairwise adds, three is N-1, so the cost is N-1. That counts the additions correctly and ignores the part that actually costs anything.</p><p><em>The additions are free. The expensive resource is the link between cores.</em> The real question is never how many adds, it is how many times the data crosses a wire. And the postcondition forces data across wires in two separate directions.</p><p>Direction one: the partials have to come together to be summed. Data flows inward and collapses. That is a reduction.</p><p>Direction two: the finished total has to come back out to every core, because the postcondition demands every core hold it. Data flows outward and replicates. That is a broadcast.</p><p>You cannot skip direction two. Even with a magic free reduction that left the full sum on one core instantly, you would still owe N-1 steps to get that result back out to the other N-1 cores. Reduction inward, broadcast outward. Two directions, two costs. That is the seed of the 2.</p><p>Ring all-reduce is the bottleneck-free version of exactly these two movements. It calls direction one reduce-scatter and direction two all-gather. Trace both.</p><h3>Phase one: reduce-scatter, and where its N-1 comes from</h3><p>Arrange the four cores in a logical ring, 0 to 1 to 2 to 3 to 0. <strong><em>Every core sends only to its right neighbor and receives only from its left neighbor</em></strong>.</p><p>Chop each core’s length-4 vector into 4 chunks of one value each. Here is the starting grid. Rows are cores, columns are chunks, and every cell is one of the partial values we just computed above:</p><pre>          chunk0  chunk1  chunk2  chunk3<br>Core 0  [  15      12       9       6  ]<br>Core 1  [   2       8       6       4  ]<br>Core 2  [   1       3       4       2  ]<br>Core 3  [  12       6       3      15  ]</pre><p>The goal of reduce-scatter is narrow. Not to give everyone the full sum, but to leave each core holding exactly one chunk that is fully summed across all four cores, with the four finished chunks scattered one per core. That weaker goal is what makes it cheap.</p><p>The send schedule is the part people get wrong, so here it is exactly. On step t, core i sends the chunk with index (i — t) mod 4 to its right neighbor, and adds the chunk arriving from its left into its own matching slot. The chunk index walks backward as t grows. That is deliberate. It makes each chunk accumulate contributions from consecutive cores as it travels forward around the ring.</p><p>Step 1, t = 0. Core i sends chunk (i - 0) mod 4 = chunk i.</p><pre>Core 0 sends chunk0 (=15) to Core 1<br>Core 1 sends chunk1 (=8)  to Core 2<br>Core 2 sends chunk2 (=4)  to Core 3<br>Core 3 sends chunk3 (=15) to Core 0</pre><p>Each receiver adds the arriving chunk into its own same-index slot:</p><pre>Core 1 chunk0:  2 + 15 = 17<br>Core 2 chunk1:  3 +  8 = 11<br>Core 3 chunk2:  3 +  4 =  7<br>Core 0 chunk3:  6 + 15 = 21</pre><p>Grid after step 1, changed cells starred (*):</p><pre>          chunk0   chunk1   chunk2   chunk3<br>Core 0  [  15       12        9      *21  ]<br>Core 1  [ *17        8        6        4  ]<br>Core 2  [   1      *11        4        2  ]<br>Core 3  [  12        6       *7       15  ]</pre><p>Step 2, t = 1. Core i sends <em>chunk (i - 1) mod 4</em>. So core 0 sends chunk3, core 1 sends chunk0, core 2 sends chunk1, core 3 sends chunk2. Each core forwards the chunk it just accumulated, so the running partial keeps moving.</p><pre>Core 0 sends chunk3 (=21) to Core 1<br>Core 1 sends chunk0 (=17) to Core 2<br>Core 2 sends chunk1 (=11) to Core 3<br>Core 3 sends chunk2 (=7)  to Core 0</pre><p>Receivers add:</p><pre>Core 1 chunk3:  4 + 21 = 25<br>Core 2 chunk0:  1 + 17 = 18<br>Core 3 chunk1:  6 + 11 = 17<br>Core 0 chunk2:  9 +  7 = 16</pre><p>Grid after step 2:</p><pre>chunk0   chunk1   chunk2   chunk3<br>Core 0  [  15       12      *16       21  ]<br>Core 1  [  17        8        6      *25  ]<br>Core 2  [ *18       11        4        2  ]<br>Core 3  [  12      *17        7       15  ]</pre><p>Step 3, t = 2. Core i sends <em>chunk (i - 2) mod 4</em>. Core 0 sends chunk2, core 1 sends chunk3, core 2 sends chunk0, core 3 sends chunk1.</p><pre>Core 0 sends chunk2 (=16) to Core 1<br>Core 1 sends chunk3 (=25) to Core 2<br>Core 2 sends chunk0 (=18) to Core 3<br>Core 3 sends chunk1 (=17) to Core 0</pre><p>Receivers add:</p><pre>Core 1 chunk2:  6 + 16 = 22<br>Core 2 chunk3:  2 + 25 = 27<br>Core 3 chunk0: 12 + 18 = 30<br>Core 0 chunk1: 12 + 17 = 29</pre><p>Grid after step 3:</p><pre>          chunk0   chunk1   chunk2   chunk3<br>Core 0  [  15      *29       16       21  ]<br>Core 1  [  17        8      *22       25  ]<br>Core 2  [  18       11        4      *27  ]<br>Core 3  [ *30       17        7       15  ]</pre><p>Read the starred cells. Each one is a fully summed value from the target [30, 29, 22, 27]:</p><pre>Core 3 owns chunk0 = 30   (correct)<br>Core 0 owns chunk1 = 29   (correct)<br>Core 1 owns chunk2 = 22   (correct)<br>Core 2 owns chunk3 = 27   (correct)</pre><p>That took exactly 3 steps, which is N-1 for N=4. The complete answer now exists in the system but it is shredded: each core holds one quarter of it, and three quarters of every core’s vector is still stale partial data. No core can answer the query yet. This is the precise meaning of reduce-scatter. The reduction is done, the result is scattered, and the operation is only half finished.</p><p>Why N-1 and not N? A chunk must visit N cores to collect N contributions, and it starts already sitting on one of them. It needs N-1 hops to reach the other N-1. One free starting position, N-1 paid moves. That is the first N-1.</p><h3>Phase two: all-gather, and the second N-1</h3><p>Now the postcondition bites. Every core needs the full [30, 29, 22, 27], but each core holds only one correct chunk. Those correct chunks have to be copied out to everybody. This is all-gather: same ring, same neighbor-only sends, but now there is no addition. Each core forwards a finished chunk, the receiver stores it in the right slot, and the finished chunks circulate until everyone has all four.</p><p>Starting state, only the finished chunks shown, dots are slots not yet holding final values:</p><pre>          chunk0   chunk1   chunk2   chunk3<br>Core 0  [   .        29        .        .  ]<br>Core 1  [   .         .       22        .  ]<br>Core 2  [   .         .        .       27  ]<br>Core 3  [  30         .        .        .  ]</pre><p>The rule mirrors phase one. On each step, core i sends the finished chunk it currently owns to its right neighbor, store on arrival, no add. The owned chunk index walks forward by one each step.</p><p>Step 1. Each core sends its owned correct chunk right.</p><pre>Core 3 sends chunk0 (=30) to Core 0<br>Core 0 sends chunk1 (=29) to Core 1<br>Core 1 sends chunk2 (=22) to Core 2<br>Core 2 sends chunk3 (=27) to Core 3</pre><p>Grid after step 1:</p><pre>          chunk0   chunk1   chunk2   chunk3<br>Core 0  [  30        29        .        .  ]<br>Core 1  [   .        29       22        .  ]<br>Core 2  [   .         .       22       27  ]<br>Core 3  [  30         .        .       27  ]</pre><p>Step 2. Forward the chunk each core just received.</p><pre>Core 0 sends chunk0 (=30) to Core 1<br>Core 1 sends chunk1 (=29) to Core 2<br>Core 2 sends chunk2 (=22) to Core 3<br>Core 3 sends chunk3 (=27) to Core 0</pre><p>Grid after step 2:</p><pre>          chunk0   chunk1   chunk2   chunk3<br>Core 0  [  30        29        .       27  ]<br>Core 1  [  30        29       22        .  ]<br>Core 2  [   .        29       22       27  ]<br>Core 3  [  30         .       22       27  ]</pre><p>Step 3. Forward once more.</p><pre>Core 0 sends chunk3 (=27) to Core 1<br>Core 1 sends chunk0 (=30) to Core 2<br>Core 2 sends chunk1 (=29) to Core 3<br>Core 3 sends chunk2 (=22) to Core 0</pre><p>Grid after step 3:</p><pre>          chunk0   chunk1   chunk2   chunk3<br>Core 0  [  30        29       22       27  ]<br>Core 1  [  30        29       22       27  ]<br>Core 2  [  30        29       22       27  ]<br>Core 3  [  30        29       22       27  ]</pre><p>Every core now holds [30, 29, 22, 27]. The postcondition is satisfied. That took exactly 3 steps, again N-1, for the same reason as before: each finished chunk lives on one core and has to reach the other N-1, so N-1 forwarding hops.</p><h3>Adding the two halves</h3><p>The derivation is now arithmetic on the two phase costs:</p><pre>reduce-scatter:  N-1 steps   (reduction inward, sum gets scattered)<br>all-gather:      N-1 steps   (broadcast outward, chunks get gathered)<br><br>all-reduce:      (N-1) + (N-1) = 2(N-1) step</pre><p>For N=4 that is 3 + 3 = 6 steps, exactly what we traced. The 2 is not a fudge factor and not a redundant second lap. It is one N-1 for collapsing the partials into a scattered sum, and a second N-1 for spreading that sum back out to satisfy the every-core postcondition. Two structurally distinct jobs, two costs, summed.</p><p>If anyone sells you N-1 as the cost of all-reduce, they have silently dropped the broadcast. N-1 is the honest cost of reduce-scatter alone, or of all-gather alone, or of a one-directional reduce that leaves the answer on a single core. The instant you require every core to hold the result, you have bought the second N-1, and the cost is 2(N-1).</p><h3>The same split explains the bandwidth story</h3><p>The decomposition explains why ring all-reduce is loved for large tensors, not just the step count. Count bytes per link instead of steps.</p><p>Let the full tensor be size S. In reduce-scatter, each core sends one chunk of size S/N per step for N-1 steps, so it pushes (N-1) S/N bytes across its link. All-gather is identical traffic, another (N-1) S/N bytes. Total bytes any single link carries:</p><pre>2 * (N-1) * S/N  =  2S * (N-1)/N</pre><p>As N grows, (N-1)/N approaches 1, so per-link traffic flattens at about 2S no matter how many cores you add. The 2 here is the same 2 as in the step count, for the same reason: <em>one S of traffic to reduce-scatter, one S to all-gather.</em> The decomposition that explains the latency cost also explains the bandwidth cost. That is not a coincidence, it is the same two-phase structure read through two different meters.</p><h3>The one sentence to keep</h3><p><strong><em>All-reduce equals reduce-scatter plus all-gather. </em></strong>Reduce-scatter costs N-1, all-gather costs N-1, and the postcondition that every core must hold the result is what forces both, so the cost is 2(N-1) and can never be N-1. Memorize the decomposition, not the formula, and the formula rebuilds itself every time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=229f3cd73d25" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tensor Parallelism by Hand: The Matrix Math Most Explainers Skip]]></title>
            <link>https://medium.com/@varuntej07/tensor-parallelism-explained-94d17f6643f0?source=rss-ce1906f9f6e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/94d17f6643f0</guid>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[training]]></category>
            <category><![CDATA[inference]]></category>
            <category><![CDATA[distributed-computing]]></category>
            <category><![CDATA[tensor-parallelism]]></category>
            <dc:creator><![CDATA[Varuntej]]></dc:creator>
            <pubDate>Thu, 18 Jun 2026 05:20:39 GMT</pubDate>
            <atom:updated>2026-06-19T07:09:07.991Z</atom:updated>
            <content:encoded><![CDATA[<p>Every explainer says the same sentence: “a tensor is split into N chunks along a dimension so each device holds 1/N of it.” That sentence is true and useless. It tells you nothing about <em>when</em> the split happens, <em>where</em> in the model it happens, <em>what</em> gets communicated, or <em>why</em> you would do it at all. This post answers those questions by following a single MLP block through two GPUs, with the actual matrices drawn out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cgqZ9sMFjjORoQLNhPZLoQ.png" /></figure><h3>First, why split anything</h3><p>You split a weight matrix across devices for exactly two reasons, and they are independent.</p><ol><li><strong>Memory.</strong> A 70B parameter model in bf16 is about 140 GB of weights. For training, add gradients (another 140 GB) and Adam optimizer states (roughly 560 GB at fp32 momentum plus variance). That total does not fit on one 80 GB GPU. Even for inference-only, 140 GB of weights plus the KV cache overflows a single device. Now imagine a trillion-parameter model.</li><li><strong>Latency and throughput.</strong> Even when the weights fit, one device runs the matmul sequentially. Splitting a matmul across 4 devices cuts the per-device FLOPs by 4 and the math finishes faster.</li></ol><p>This already answers the single-GPU question. Tensor parallelism is a <em>multi-device</em> strategy. If you have one GPU and the model fits, there is no tensor parallelism happening. The thousands of cores inside that one GPU are running the matmul in parallel, but that is the kernel’s job, not a model-sharding decision. Tensor parallelism only exists once there are at least two devices to shard a weight matrix across.</p><h3>Where it happens</h3><p>Not everywhere. Tensor parallelism targets the two fat matmuls inside each transformer decoder layer:<br>- The <strong>Attention block</strong>: the QKV projection and the output projection.<br>- The <strong>MLP block</strong>: the up-projection and the down-projection.</p><p>These are where the parameters and the FLOPs live. Layernorms, residual adds, and the softmax are cheap and stay replicated. So the question “when does it happen” has a precise answer: at specific points inside every decoder layer, twice per layer on the forward pass, and twice more per layer on the backward pass during training. Between those points each GPU runs alone.</p><h3>The two moves: column split and row split</h3><p>A linear layer is Y = X @ W. Take X as [inp_tokens x d_in] and W as [d_in x d_out]. There are exactly two ways to cut W.</p><h3>Column split (cut along d_out)</h3><pre> W                        W_0                   W_1<br>   [ d_in x d_out ]    =    [ d_in x d_out/2 ]    [ d_in x d_out/2 ]<br>                                  GPU 0                GPU 1<br><br> Y = X @ [ W_0 | W_1 ] = [ X @ W_0 | X @ W_1 ] = [ Y_0 | Y_1 ]</pre><p>Each GPU holds the full X (replicated) and half the columns of W. GPU 0 produces the left half of the output columns, GPU 1 the right half. <strong>No communication is needed to compute this.</strong> The output comes out split along its feature dimension.<br><em>“Replicated” here is about space, not time. </em><em>X is the input activation to this layer, the embedded tokens at layer 0 and the previous layer&#39;s output everywhere after, so it changes every layer. What replication means is that at the instant this matmul runs, every GPU in the group holds an identical copy of that one layer&#39;s </em><em>X. The activation differs across layers but is the same across GPUs at any given layer. That sameness is not assumed, it is restored at the end of every block by the </em><strong><em>all-reduce </em></strong><em>in the row-parallel layer, which leaves the same summed output on every rank. That output becomes the next layer&#39;s replicated </em><em>X. So the per-layer cycle is replicated input, split by the column-parallel matmul, replicated again by the closing all-reduce. (</em><strong><em>This is also why every GPU in a tensor-parallel group processes the same tokens. Different batches go to different data-parallel groups, never to different tensor-parallel ranks</em></strong><em>)</em></p><h3>A column split with real numbers</h3><p>The abstract d_in by d_out labels above are easy to lose track of, so here is the same column split with every value filled in to better understand the exact cut you would do by hand. A is the activation, B is the weight, both 3 x 3 for this example, run across three GPUs.</p><pre>   A = [ 1  2  3 ]        B = [ 1  0  2 ]<br>       [ 4  5  6 ]            [ 0  1  1 ]<br>       [ 7  8  9 ]            [ 1  1  0 ]</pre><p>Cut B into its three columns. Each GPU holds the full A and one column of B:</p><pre>   GPU 0: B_0 = [ 1 ]    GPU 1: B_1 = [ 0 ]    GPU 2: B_2 = [ 2 ]<br>                [ 0 ]                 [ 1 ]                 [ 1 ]<br>                [ 1 ]                 [ 1 ]                 [ 0 ]</pre><p>Each GPU computes A @ B_i on its own, no communication:</p><pre>   GPU 0:  A @ B_0 = [ 1*1 + 2*0 + 3*1 ]   [  4 ]<br>                     [ 4*1 + 5*0 + 6*1 ] = [ 10 ]<br>                     [ 7*1 + 8*0 + 9*1 ]   [ 16 ]<br><br>   GPU 1:  A @ B_1 = [ 1*0 + 2*1 + 3*1 ]   [  5 ]<br>                     [ 4*0 + 5*1 + 6*1 ] = [ 11 ]<br>                     [ 7*0 + 8*1 + 9*1 ]   [ 17 ]<br><br>   GPU 2:  A @ B_2 = [ 1*2 + 2*1 + 3*0 ]   [  4 ]<br>                     [ 4*2 + 5*1 + 6*0 ] = [ 13 ]<br>                     [ 7*2 + 8*1 + 9*0 ]   [ 22 ]</pre><p>Stack the three column results side by side and you have the full product:</p><pre>   [  4 |  5 |  4 ]     [  4   5   4 ]<br>   [ 10 | 11 | 13 ]  =  [ 10  11  13 ]   = A @ B<br>   [ 16 | 17 | 22 ]     [ 16  17  22 ]</pre><p>That is column parallelism end to end. The combine step here is a <strong>concatenation</strong>, which as a collective is an <strong>all-gather</strong>: every GPU produced a different slice of the output columns and you stitch them together. This is the all-gather case. You only get an all-reduce when you split the contraction dimension instead, where each GPU holds a partial sum of the <em>same</em> output positions and you add rather than concatenate.</p><p>In a real transformer you usually avoid even this gather. The up-projection is column-parallel exactly like this, but instead of gathering its output you feed the column slices straight into a row-parallel down-projection, which ends in one all-reduce. The column result above never has to be reassembled. As a standalone matmul though, this split, compute, concatenate is precisely what tensor parallelism does.</p><h3>Row split (cut along d_in)</h3><pre>W                              W_0   [ d_in/2 x d_out ]   GPU 0<br>   [ d_in x d_out ]    =       ---<br>                               W_1   [ d_in/2 x d_out ]   GPU 1<br><br><br>X must also be split:   X = [ X_0 | X_1 ]<br><br><br>Y = [X_0 | X_1] @ [ W_0 ]  =     X_0 @ W_0  +  X_1 @ W_1<br>                  [ W_1 ]          (GPU 0)       (GPU 1)</pre><p>Here W is cut along its input dimension, so the input X must arrive already split along <em>its</em> feature dimension. Each GPU computes a full-shape [tokens x d_out] result, but each result is only a <strong>partial sum</strong>. The true output is X_0@W_0 + X_1@W_1, and that addition lives across two GPUs. Adding numbers that sit on different devices is a collective operation. This is the all-reduce.</p><h3>A row split with real numbers</h3><p>Row split is the one that surprises people, so here it is with numbers. Take the same W as the weight and feed it the activation X. The contraction dimension, the shared 3, is what gets cut across three GPUs.</p><pre>   X = [ 1  2  3 ]        W = [ 1  0  2 ]<br>       [ 4  5  6 ]            [ 0  1  1 ]<br>                              [ 1  1  0 ]</pre><p>Cut W along its rows and X along its columns. The cut index lines up: GPU i gets column i of X and row i of W.</p><pre>   GPU 0:  X_0 = [ 1 ]   W_0 = [ 1  0  2 ]<br>                 [ 4 ]<br><br>   GPU 1:  X_1 = [ 2 ]   W_1 = [ 0  1  1 ]<br>                 [ 5 ]<br><br>   GPU 2:  X_2 = [ 3 ]   W_2 = [ 1  1  0 ]<br>                 [ 6 ]</pre><p>Now the surprising part. Each GPU computes X_i @ W_i, and the result is a <strong>full </strong><strong>2 x 3 matrix</strong>, the same shape as the final answer, not a slice of it:</p><pre>   GPU 0:  X_0 @ W_0 = [ 1 ] @ [ 1 0 2 ] = [ 1  0  2 ]<br>                       [ 4 ]               [ 4  0  8 ]<br><br>   GPU 1:  X_1 @ W_1 = [ 2 ] @ [ 0 1 1 ] = [ 0  2  2 ]<br>                       [ 5 ]               [ 0  5  5 ]<br><br>   GPU 2:  X_2 @ W_2 = [ 3 ] @ [ 1 1 0 ] = [ 3  3  0 ]<br>                       [ 6 ]               [ 6  6  0 ]</pre><p>Each of those is a complete-looking matrix but a wrong answer on its own. None of them is a piece of the output you can slot into place. They are <strong>partial sums</strong>, and the real output only appears when you add all three element by element:</p><pre>   [ 1 0 2 ]   [ 0 2 2 ]   [ 3 3 0 ]   [  4   5   4 ]<br>   [ 4 0 8 ] + [ 0 5 5 ] + [ 6 6 0 ] = [ 10  11  13 ]</pre><p>That addition across three GPUs is the <strong>all-reduce</strong>. Compare it to the column split, where the combine was concatenation. <em>The final numbers match the first two rows of the </em><em>A @ B from the column example (first example), reached by cutting a different dimension and paying a different collective.</em></p><p>Two things make this the non-obvious case. First, the input had to arrive already split along the contraction dimension. On its own you would scatter X to set that up, but in a transformer the previous column-parallel layer hands you exactly this split for free. Second, parallel here does not mean each device owns a region of the answer. Every device computes the whole shape and owns none of it alone. The answer is the sum, which is why a row split always ends in a reduction and never a gather.</p><h3>Why the pairing is the whole trick</h3><p>Look at what column split produces and what row split consumes:</p><ul><li>Column split produces an output <strong>split along its feature dimension</strong>.</li><li>Row split requires an input <strong>split along its feature dimension</strong>.</li></ul><p>They fit. If you make the up-projection column-parallel and the down-projection row-parallel, the split output of the first matmul is exactly the split input the second matmul wants. Nothing is communicated between them. You pay for communication only once, at the end of the row-parallel layer, where the partial sums get reduced.</p><p>There is a second reason the order has to be <em>column-then-row</em>, and it is the nonlinearity. The MLP applies <a href="https://www.datacamp.com/tutorial/gelu">GeLU </a>(or SwiGLU) between the two matmuls. GeLU is elementwise. Each output column is computed independently of the others, so applying GeLU to a column slice gives the correct result for that slice. A row split would scramble this, because a row-split intermediate<em> holds partial sums</em>, and GeLU(a + b) is not equal to GeLU(a) + GeLU(b). <strong><em>Column split keeps every hidden unit whole on one device, so GeLU is applied to the complete value </em></strong><em>(</em><strong><em>GeLU(a+b)</em></strong><em>) </em><strong><em>rather than to a partial sum, and the activation is exact.</em></strong></p><h3>The worked example</h3><p>Two tokens, d_model = 4, d_hidden = 8, tensor parallel degree 2. Watch the shapes.</p><p><strong>Input, replicated on both GPUs:</strong></p><pre>X = [ 2 x 4 ]      (same X on GPU 0 and GPU 1)</pre><p><strong>Up-projection, column split</strong> (W_up is [4 x 8], cut into two [4 x 4]):</p><pre>   GPU 0:  X[2x4] @ W_up_0[4x4]  =  H_0 [2 x 4]<br>   GPU 1:  X[2x4] @ W_up_1[4x4]  =  H_1 [2 x 4]<br>   <br>   no communication</pre><p>The 8-wide hidden is now physically two 4-wide halves, one per GPU.</p><p><strong>GeLU, elementwise on each half independently:</strong></p><pre>   GPU 0:  H_0 -&gt; GeLU(H_0) [2 x 4]<br>   GPU 1:  H_1 -&gt; GeLU(H_1) [2 x 4]<br><br>   no communication</pre><p><strong>Down-projection, row split</strong> (W_down is [8 x 4], cut into two [4 x 4]):</p><pre>   GPU 0:  GeLU(H_0)[2x4] @ W_down_0[4x4]  =  P_0 [2 x 4]   partial<br>   GPU 1:  GeLU(H_1)[2x4] @ W_down_1[4x4]  =  P_1 [2 x 4]   partial</pre><p>The hidden was split along the 8 dimension, and W_down was split along its 8-row dimension. They line up, which is why no communication happened on the handoff. Each P is the right shape but only half the answer.</p><p><strong>All-reduce, the one communication point:</strong></p><pre>Y[2 x 4] = P_0 + P_1        summed across GPU 0 and GPU 1<br>                            every GPU ends up with the full Y</pre><p>One MLP block, four matmul shards, one collective. That is the entire rhythm: independent compute, independent compute, all-reduce.</p><h3>Attention is the same shape</h3><p>QKV projection is column-parallel, split by attention heads, because heads are already independent. <em>Each GPU gets a subset of heads and runs their attention end to end.</em> The output projection is row-parallel, and one all-reduce closes the block. Same pattern, one all-reduce per attention block.</p><p>The GQA wrinkle: with grouped-query attention the KV heads are shared across groups of query heads. When you shard heads across tensor parallel ranks you must keep each KV head with the query heads that use it. If the tensor parallel degree exceeds the number of KV heads, the KV heads get replicated rather than split. The KV cache shards along the same head dimension, which is why tensor parallelism also shrinks per-GPU KV cache memory, not just weights.</p><h3>What “gathered” actually means</h3><p>People say the result is “gathered,” but the collective depends on which dimension you cut.</p><ul><li>If you split the <strong>output</strong> (column-parallel) and want the full tensor back, you concatenate the slices. That is an <strong>all-gather</strong>.</li><li>If you split the <strong>contraction dimension</strong> (row-parallel), each device holds a partial sum and you add them. That is an <strong>all-reduce</strong>.</li></ul><p>The Megatron MLP and attention blocks end on a row-parallel layer, so the closing collective is an all-reduce, not a gather. The output lands replicated on every GPU, which is exactly the replicated input the next layer’s column-parallel matmul expects. The pattern self-perpetuates down the stack.</p><p>These collectives run over NCCL, on NVLink inside a node and InfiniBand across nodes. Because an all-reduce sits on the critical path of every single layer, tensor parallelism is normally kept <em>within</em> a node where NVLink bandwidth is high. Stretching it across nodes makes the all-reduce the bottleneck, since every layer now waits on slow inter-node links.</p><h3>Inference versus training who use it?</h3><p>Both use it. The difference is how many times you pay.</p><p><strong>Inference</strong> is forward only. Per decoder layer: one all-reduce after attention, one after the MLP. Two per layer, every token-generation step. Tensor parallelism is the default for low-latency serving inside a node precisely because it parallelizes <em>within</em> a layer and adds no pipeline bubble, unlike pipeline parallelism.</p><p><strong>Training</strong> adds the backward pass, which has its own communication. In Megatron’s notation there are two conjugate operators wrapping each block:</p><pre>   f : identity in forward,  all-reduce in backward<br>   g : all-reduce in forward, identity in backward</pre><p><strong>g </strong>does the all-reduce you saw above on the forward pass. On the backward pass, <strong>f </strong>does an all-reduce to sum the gradients flowing back into the replicated input. So training costs four all-reduces per layer per step: two forward, two backward. On top of that, each GPU only stores gradients and optimizer state for its own weight shard, which is the memory win that made splitting worth it in the first place. This tensor-parallel communication is separate from and composes with the data-parallel gradient all-reduce across replicas.</p><h3>Recap</h3><pre>   <strong>Why split</strong>        memory wall and latency wall, multi-device only<br>   <strong>Where</strong>            the two matmuls in attention and the two in the MLP<br>   <strong>Column split</strong>     cut output dim, no comm, feeds the next layer directly<br>   <strong>Row split</strong>        cut contraction dim, ends in an all-reduce<br>   <strong>The pairing</strong>      column then row, so the middle handoff is free<br>   <strong>Gathered how</strong>     all-gather to concat columns, all-reduce to sum partials<br>   <strong>When</strong>             after the row-parallel matmul, twice per layer forward<br>   <strong>Inference        </strong>2 all-reduces per layer per step<br>   <strong>Training         </strong>4 all-reduces per layer per step, plus sharded optim state<br>   <strong>Single GPU?</strong>      not applicable, nothing to shard across</pre><p>The one-sentence definition was not wrong. It was just the last 5 percent. The actual content is the choreography: which dimension you cut decides which collective you owe, and the column-then-row pairing is what makes the middle of the layer communication-free.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94d17f6643f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Two AI Agents Arguing With Each Other Over Voice in Real-Time]]></title>
            <link>https://medium.com/@varuntej07/two-ai-agents-arguing-with-each-other-over-voice-in-real-time-e176e19aa642?source=rss-ce1906f9f6e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/e176e19aa642</guid>
            <category><![CDATA[voice-ai]]></category>
            <category><![CDATA[debating]]></category>
            <category><![CDATA[realtime-voice]]></category>
            <category><![CDATA[ai-voice-agent]]></category>
            <category><![CDATA[amazon-nova-sonic]]></category>
            <dc:creator><![CDATA[Varuntej]]></dc:creator>
            <pubDate>Wed, 18 Mar 2026 02:17:35 GMT</pubDate>
            <atom:updated>2026-03-18T02:36:26.089Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever been walking to the store, riding alone in a car, sitting on a bus with nothing but dead air in your ears and thought, <em>I could use this time for something meaningful</em>?</p><p>If not, that’s fine. But I kept having that thought.</p><p>What if I could just pull out my phone and listen to two AI agents go at it right now? Not a podcast someone recorded last week. Not one AI giving me a clean summary. Not typing a question into a chatbot and reading a wall of text. But two agents on opposing sides, arguing about something I actually care about, generating the whole thing live while I walk.</p><p>Every time I had ten minutes of nothing, waiting on food, taking my dog out, standing in line, I wanted to hear something useful (of course not by chatting duhhh..!) so I decided why not hear two sharp perspectives collide on whatever question was bouncing around my head. A real back and forth where one side pushes back on the other and I get to hear the friction. Not letting two phones near and letting them argue. Not a summarized answer. An argument. The kind where you walk away thinking about angles you never would have found on your own.</p><p>That’s the product I wanted. Nobody had built it. Right when I wanted to build this, I came across the Amazon Nova hackathon and discovered Nova Sonic could do bidirectional voice streaming in real time. I had my opening. The model was the tool. The product was mine.</p><p>That’s how <a href="https://pocketpanel-production.up.railway.app/">PocketPanel</a> started.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aFh1Iz959W0G_jvqHaaUXg.png" /><figcaption>pocket-panel</figcaption></figure><h3>What I Built</h3><p>PocketPanel lets you enter any topic, whether a 4 day work week is actually more productive? Is college still worth it now? Should we be colonizing Mars or fixing Earth first? Will AI take more jobs than it creates? And two AI voice agents take opposing sides and argue about it in real time. Both speech and text generate simultaneously. It sounds like two people who actually disagree, not two scripts being narrated. Contractions, emphasis, pacing, conviction, all generated live.</p><p>You can throw a question in mid debate and the next agent addresses it without skipping a beat. Brave Search grounds the agents on live web sources when the topic needs real facts, not just opinions. Once the debate wraps up, a post debate analysis breaks down what each side got right and what they missed.</p><p><a href="https://pocketpanel-production.up.railway.app/">Try it live.</a></p><h3>How the Whole Thing Works</h3><p><strong>Nova Lite</strong> is the Intent classifier. It takes your topic and figures out what format the conversation should be. Structured debate? Rapid crossfire? Podcast style? Explainer? It’s fast and cheap so I use it to make that decision before anything expensive runs.</p><p><strong>Nova Sonic</strong> is the brain and the voice. Two instances per debate, each holding an opposing position on its own WebSocket connection. Each one generates its own arguments with audio and text streaming out at the same time. This is the core of the whole thing.</p><p><strong>Nova Pro</strong> comes in at the end. Once both agents are done arguing, Pro writes up a post debate analysis. Each side’s strongest point, what they missed, follow up questions worth thinking about.</p><p>Here’s the actual flow. Agent A goes first opens a WebSocket session, send A its assigned position as the system prompt, send the topic as the user input, and stream some silence frames to <em>wake up the audio pipeline </em>(more on that later). Sonic starts generating. Audio chunks and text events come back interleaved on the same stream. When Sonic signals it’s done, I close the session. Whatever Agent A said in text (both audio, text is generated at the same time) becomes the input for Agent B’s turn. B gets a fresh session with its own position and A’s argument to respond to.</p><p>They just keep alternating. A, B, A, B. Each session is completely independent. No memory leaking between agents. No shared state that could accidentally bias one side. The only thing connecting the turns is the transcript that the orchestrator passes along.</p><pre>User enters topic<br>  │<br>  ├─ Nova Lite      -&gt; classify intent, pick format<br>  ├─ Nova Pro       -&gt; generate opposed positions for Agent A and Agent B<br>  ├─ Brave Search   -&gt; (tool calling) pull live sources to ground the debate<br>  │<br>  └─ Turn loop<br>       │<br>       ├─ [Turn 1 — Agent A]<br>       │    open bidirectional WebSocket<br>       │    send: system prompt (A&#39;s position) + topic + silence frames<br>       │    receive: audioOutput -&gt; ~100ms WAV chunks -&gt; browser -&gt; AudioContext<br>       │    receive: textOutput -&gt; transcript + input for Agent B<br>       │    close session<br>       │<br>       ├─ [Turn 2 — Agent B]<br>       │    open bidirectional WebSocket<br>       │    send: system prompt (B&#39;s position) + A&#39;s argument + silence frames<br>       │    receive: audioOutput + textOutput (same flow)<br>       │    close session<br>       │<br>       ├─ [Turn 3 — Agent A] ... alternating<br>       │<br>       └─ Nova Pro -&gt; post-debate synthesis streamed to browser</pre><h3>The Silence That Almost Killed the Project</h3><p>This one was brutal.</p><p>I had everything connected. WebSocket open, events flowing in the right order, code looking clean. And Sonic just… didn’t respond. No error. No timeout message. No crash. Just silence. Like sending a text and never getting a reply.</p><p>Turns out the bidirectional streaming protocol needs events sent in an exact sequence:</p><pre>sessionStart -&gt; promptStart -&gt; SYSTEM TEXT -&gt; USER TEXT -&gt; AUDIO -&gt; promptEnd -&gt; sessionEnd</pre><p>One thing out of place and you get nothing. Not an error. Nothing. I went through three different AWS reference implementations before I found that my content blocks were accidentally nesting inside each other instead of opening and closing one after another. The model needs strict sequential ordering. The moment I fixed that, audio started coming through.</p><p>But wait there’s more. Even with the events in the right order, some sessions still gave me silence. After a lot of trial and error I figured out that Sonic needs a minimum amount of audio input before it starts generating. You have to send enough silence frames to get the audio pipeline going. Too little and the model just sits there.</p><p>How much silence? About 500 milliseconds. I found that number by just sending longer and longer buffers until it worked. It’s not documented anywhere. You just have to discover it yourself.</p><h3>Making the Audio Not Sound Terrible</h3><p>Alright so getting audio from the server to the browser without stuttering. This was its own whole adventure.</p><p>I’m streaming roughly 100 millisecond WAV (Waveform Audio File Format) chunks over a WebSocket. On the server side, the audio coming from Sonic gets buffered into small pieces, wrapped with a WAV header, and sent to the browser. Sounds simple enough.</p><p><strong>First attempt: HTMLAudioElement.</strong> I created one audio element per chunk and played them back to back. The problem is each element has its own decoder startup time. Result: audible gaps between every single chunk. The debate sounded like a bad phone call.</p><p><strong>Second attempt: Web Audio API with AudioContext.</strong> This one uses hardware clock scheduling so you can queue chunks against a precise timeline. The gaps went away. But then a new problem showed up. When multiple decodeAudioData calls ran at the same time, they raced against each other on the shared playback timestamp. Some chunks overlapped. Some went silent.</p><p><strong>What actually worked:</strong> I serialized all the decode calls through a promise chain. Each chunk waits for the one before it to finish decoding, then schedules itself at the exact right time.</p><pre>// Serialized decode chain where each chunk schedules after the previous<br>decodeChain = decodeChain.then(() =&gt; {<br>  return audioContext.decodeAudioData(wavBuffer).then(decoded =&gt; {<br>    const source = audioContext.createBufferSource();<br>    source.buffer = decoded;<br>    source.connect(audioContext.destination);<br>    source.start(nextPlayTime);<br>    nextPlayTime += decoded.duration;<br>  });<br>});</pre><p>Gap-free playback on a live stream of 100ms chunks. No stuttering, no overlaps, no decoder race conditions.</p><h3>Throwing Questions Mid Debate</h3><p>This was actually the easiest part to build, which surprised me.</p><p>When you type a question during a live debate, the orchestrator holds onto it until the current agent finishes talking. Then it tucks your question into the next agent’s prompt right alongside the opponent’s last argument. The agent answers your question and keeps arguing. No break in flow.</p><p>It works this cleanly because of the stateless session design. Every turn already gets all the context it needs from scratch, the agent’s position, what the opponent said, the format rules. A moderator question is just one more piece of context in the prompt. Nothing to break. Nothing to corrupt.</p><h3>What I Actually Learned</h3><p>The biggest takeaway wasn’t technical. It was conceptual.</p><p>The WebSocket streaming stuff was hard but in a different way. Each piece on its own, session management, event ordering, audio chunking, browser playback, is totally manageable. The hard part is making all of them work together without latency spikes or race conditions ruining the experience. That’s where the real engineering is.</p><p>And honestly? The product works. I use it myself. Ten minutes walking to the store, I hear two agents tear apart a topic I’ve been thinking about, and I come back with angles I hadn’t considered. That was the whole point.</p><h3>What’s Next for PocketPanel</h3><p>Custom voices so users can pick agents that sound like personas they actually want to listen to. Domain specific agents tuned for law, medicine, finance. Multi language debates where each agent argues in a different language. Audience voting that shifts how the agents argue mid debate.</p><p>The architecture is already multi agent. Scaling from here is an orchestration problem, not a rewrite.</p><p><strong>PocketPanel is live.</strong> Enter a topic, hit start, listen to two AI agents debate about it.</p><p><a href="https://pocketpanel-production.up.railway.app/"><strong>Try PocketPanel</strong></a></p><p><a href="https://github.com/varuntej07/Pocket-Panel"><strong>GitHub</strong></a></p><p><em>Tags: AI Voice Agents, Multi-Agent AI, Real-Time AI Debate, Amazon Nova Sonic, Bidirectional Streaming, WebSocket Audio Streaming, Speech-to-Speech AI, Voice AI App, Amazon Bedrock, Web Audio API, PocketPanel, Multiple-Agents-Debating, AI Podcast Generator</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e176e19aa642" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What If Learning Looked Like a Map Instead of a Chat Thread?]]></title>
            <link>https://medium.com/@varuntej07/what-if-learning-looked-like-a-map-instead-of-a-chat-thread-68a354a24ff5?source=rss-ce1906f9f6e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/68a354a24ff5</guid>
            <category><![CDATA[edtech-startup]]></category>
            <category><![CDATA[depthwise-learning]]></category>
            <category><![CDATA[ai-learning]]></category>
            <category><![CDATA[edtech]]></category>
            <category><![CDATA[productivity]]></category>
            <dc:creator><![CDATA[Varuntej]]></dc:creator>
            <pubDate>Wed, 11 Mar 2026 07:45:17 GMT</pubDate>
            <atom:updated>2026-03-11T07:45:17.230Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Stop Using NotebookLM If You Want to Go Deep</strong></p><p>I was trying to understand how diffusion models actually work — not the “it gradually adds noise and learns to reverse it” summary, but the real thing. The math behind the forward process. Why the loss function looks the way it does. What DDPM actually changed.</p><p>So I did what everyone does. I opened an AI chatbot and typed “Explain what is diffusion model.</p><p>I got a great answer. Thorough. Accurate. A clean breakdown of the forward process, reverse process, training objective, score matching, the SDE framing — all of it laid out in well-structured paragraphs.</p><figure><img alt="Claude’ response on Diffusion" src="https://cdn-images-1.medium.com/proxy/1*ZM3ykoiW-GY_OwiagnHSQw.png" /><figcaption>Claude’ response on Diffusion</figcaption></figure><p>And then I hit the problem that always comes next.</p><h3>The Shape of the Problem</h3><p>Reading that answer, I had three threads pulling at me simultaneously. I wanted to understand the difference between the forward and reverse processes at a mathematical level. I was curious how diffusion compares to GANs and VAEs — the answer mentioned score matching but didn’t contrast approaches. And I wanted concrete examples of what diffusion does beyond image generation.</p><p>In a chat interface, I have to pick one. Ask a follow-up. Get the answer. Ask another follow-up. Get the answer. The previous context scrolls off the screen. I can’t hold the shape of what I’m learning. I just have an increasingly long thread of text.</p><p>This isn’t a flaw in any particular chatbot. It’s a constraint of the format itself. <strong><em>Chat is sequential. Learning isn’t.</em></strong></p><p>When you’re genuinely working through something hard, you don’t move in a straight line. You’re reading about the ELBO and you hit “KL divergence” and you stop. You don’t want to abandon the ELBO thread — you just need to pull on KL divergence for a second. Then inside that explanation you hit “information entropy” and you pause again. You’re not lost. You’re exploring. You’re building a map.</p><p>Every chat-based interface treats this as a problem to manage. I started wondering if it was actually the feature to design around.</p><h3>Building the Map</h3><p>That’s what I built with <a href="http://depthwise.app/">Depthwise</a>. Here’s the same question — “Explain what is diffusion model” — instead of a thread, the answer becomes a visual knowledge graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5j-EETA-n7-qcyCykivfeA.png" /><figcaption>Diffusion on depthwise.app</figcaption></figure><p>The root node gives you the core explanation. But instead of stopping there, the app generates three to five branches — each one a direction you can take. Not random follow-ups. Typed directions: a “why” that digs into mechanistic causes, a “how” that walks through implementation, an “example” that gets concrete, a “compare” that pulls in adjacent concepts.</p><p>You click the branch that interests you. It expands. That node branches again. The tree stays on screen. You can see where you came from. You can see what you haven’t explored yet. You can zoom out and look at the whole map of what you’ve learned.</p><p>Those three threads I had pulling at me after the chat answer? In Depthwise, they’re all visible at once. I can pursue the GAN comparison, go three levels deep, then come back and open the forward-vs-reverse branch without losing anything.</p><h3><strong>The Difference Between Q&amp;A and Exploration</strong></h3><p>Chat-based AI is excellent at answering questions. That’s what it’s built for — you ask, it answers, and the answer is often good. Depthwise isn’t trying to replace that. It’s solving a different problem: what happens after the first answer, when you want to keep going.</p><p>In a Q&amp;A interaction, you’re always deciding what to ask next from scratch. In an exploration interface, the tool shows you what’s possible from where you are. It generates the branches — here’s the “why,” here’s the “how,” here’s the example. You pick the direction that pulls at you. The tool does the cartography; you do the navigation.</p><p>This maps more closely to how actual curiosity works. You don’t always know what question to ask. You know which direction feels interesting.</p><h3>What’s Under the Hood</h3><p>Each time you expand a node, Depthwise sends the full path of how you got there — the root question, every parent node, the branch types you chose. This prevents the AI from giving you the same overview at depth 4 that it gave at depth 1. The deeper you go, the more specific the branches become.</p><p>The five branch types — why, how, what-if, example, compare — aren’t just labels. They’re instructions about what kind of answer to generate. A “why” branch focuses on mechanistic causes. An “example” branch generates a concrete implementation. A “compare” branch pulls in analogous concepts from adjacent fields. The same node generates completely different content depending on which direction you choose.</p><p>Sessions are persistent. You can explore anonymously and migrate your session when you sign in. Free tier gives you ten explorations a month and five levels of depth — enough to go meaningfully deep on one topic per day.</p><h3><strong>The Thing I Kept Noticing</strong></h3><p>When I use Depthwise on topics I actually want to learn, I stay on the canvas longer than I expect. Not because it’s addictive. Because I can see what I haven’t understood yet.</p><p>The unexplored branches sit there. Waiting. You finish one path and realize you skipped the “compare” branch three levels up and now you’re curious what it says. You go back. You expand it. It connects to what you just learned.</p><p>This is what learning feels like when it’s working. Not a long conversation thread. A map you’re drawing in real time, with blank regions that get smaller as you keep going.</p><h3><strong>Try It</strong></h3><p><a href="https://depthwise.app/"><strong>Depthwise </strong></a>is live at <a href="http://depthwise.app/">https://depthwise.app</a>. Anonymous sessions work without signing in — enter a question, start exploring. If you like it, sign in and your session migrates automatically.</p><p><strong><em>Knowledge isn’t a thread you follow. It’s a tree you map. That’s what the right learning tool should let you do.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68a354a24ff5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Triton Is Not CUDA in Python — It’s a Tiling DSL]]></title>
            <link>https://medium.com/@varuntej07/triton-is-not-cuda-in-python-its-a-tiling-dsl-c65c15ce3c46?source=rss-ce1906f9f6e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/c65c15ce3c46</guid>
            <category><![CDATA[gpu-programming]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[cuda-programming]]></category>
            <category><![CDATA[triton]]></category>
            <category><![CDATA[llm-inference]]></category>
            <dc:creator><![CDATA[Varuntej]]></dc:creator>
            <pubDate>Wed, 25 Feb 2026 06:03:03 GMT</pubDate>
            <atom:updated>2026-02-25T06:03:03.744Z</atom:updated>
            <content:encoded><![CDATA[<p>Triton Basics: tiles vs threads, program_id, tl.arange, masks, and autotuning for fast GPU kernels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TtsrLeOLtqAX2TsvYNNorQ.png" /></figure><p>I was halfway through my first Triton kernel when I realized I was writing it wrong. Not syntactically wrong — it compiled and ran. But I was thinking about it wrong. I was treating Triton like CUDA with Python syntax: one program instance per element, manual index math, the whole single-thread mental model. The kernel was 30× slower than it should have been.</p><p>That’s when I understood — Triton is not CUDA in Python. It’s a completely different programming model that happens to compile down to the same GPU hardware. The difference is fundamental enough that your CUDA intuitions will actively mislead you.</p><p>Here’s everything I learned getting that mental model right.</p><p>Let me start with what CUDA actually asks you to do, because the contrast makes Triton click.</p><p>In CUDA, you write code from the perspective of a single thread. One thread, one element. You launch thousands of these threads organized into blocks, and each thread figures out which element it owns using threadIdx and blockIdx. A vector addition looks like:</p><pre>// CUDA: I am one thread. I process one element.<br>int i = blockIdx.x * blockDim.x + threadIdx.x;<br>if (i &lt; n) c[i] = a[i] + b[i];</pre><p>Simple enough. But then the hard part begins. You — the programmer — must ensure that threads within a warp (a group of 32 threads that execute in lockstep) access consecutive memory addresses so the hardware can coalesce those 32 requests into one memory transaction. You must manually manage shared memory (__shared__) and synchronize threads (__syncthreads()) to avoid race conditions. You must handle warp divergence where threads in the same warp take different if/else branches. Getting all of this right is the difference between a kernel running at 10% versus 90% of what the hardware can actually deliver.</p><p>Triton throws all of that away and starts from a different premise.</p><p>Instead of writing code for one thread processing one element, you write code for one <strong>program instance</strong> processing an entire <strong>tile</strong> of elements. Not one value — a whole block of them, loaded, computed, and stored as a unit. There is no threadIdx in Triton. You never touch shared memory. You never call a synchronization barrier. The compiler handles all of that based on the tile-level operations you describe.</p><p>Here is the same vector addition in Triton:</p><pre>@triton.jit<br><br>def add_kernel(x_ptr, y_ptr, output_ptr, n_elements, BLOCK_SIZE: tl.constexpr):<br>    pid = tl.program_id(axis=0)   # Get the 1D program instance id (which block of work this kernel instance handles)<br>    <br>    # element indices this program instance will process<br>    offsets = pid * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)<br>    <br>    # ignore out-of-bounds offsets on the last block<br>    mask = offsets &lt; n_elements<br>    x = tl.load(x_ptr + offsets, mask=mask)<br>    y = tl.load(y_ptr + offsets, mask=mask)<br><br>    tl.store(output_ptr + offsets, x + y, mask=mask)</pre><p>This looks superficially similar, but the semantics are completely different. The variable x is not a single float. It&#39;s a <strong>vector of BLOCK_SIZE floats</strong> — an entire tile loaded in one shot. The addition x + y operates on the full tile simultaneously. Triton&#39;s compiler sees this tile-level intent and generates all the thread-level machinery underneath: which threads access which addresses, how data flows through shared memory, when synchronization barriers are needed.</p><p>The Triton documentation puts it directly: programs operate on blocks of data rather than individual elements, which “effectively abstracts away all the issues related to concurrency within CUDA thread blocks (e.g., memory coalescing, shared memory synchronization/conflicts, tensor core scheduling).”</p><p>That’s the core inversion.</p><p>CUDA: scalar program, blocked threads. <br>Triton: blocked program, scalar threads (handled by the compiler).</p><p>Everything else follows from this.</p><p>Now let’s look at what program_id actually is and how one kernel becomes many.</p><p>When you launch a Triton kernel, you don’t run it once. You launch a <strong>grid</strong> of program instances, each identified by a unique program_id. Here&#39;s what a launch looks like:</p><pre>grid = lambda meta: (triton.cdiv(n_elements, meta[&#39;BLOCK_SIZE&#39;]),)<br>add_kernel[grid](x, y, output, n_elements, BLOCK_SIZE=1024)</pre><p>triton.cdiv is ceiling division. If n_elements is 8192 and BLOCK_SIZE is 1024, then triton.cdiv(8192, 1024) = 8. So the grid creates 8 program instances that run in parallel on the GPU. Each one calls tl.program_id(axis=0) and gets a unique number: 0 through 7.</p><p>This maps directly to CUDA’s blockIdx.x under the hood — if you inspect the compiled PTX, tl.program_id(0) literally reads from the blockIdx.x register. But you never interact with the thread level. Each Triton program instance is a complete tile-processing unit, not a bag of threads you must coordinate.</p><p>Now here’s the line that tripped me up initially:</p><pre>offsets = pid * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)</pre><p>Let’s unpack what this actually produces at runtime, value by value. tl.arange(0, BLOCK_SIZE) generates a vector of consecutive integers, just like numpy.arange. With BLOCK_SIZE=4:</p><pre>tl.arange(0, 4) -&gt; [0, 1, 2, 3]</pre><p>That’s the local offset within a tile. Every program instance generates the same local offsets — it’s the “shape” of the tile.</p><p>pid * BLOCK_SIZE is a scalar — the starting position for this specific program instance. It shifts the local offsets to the right global position. So with an array of 16 elements, BLOCK_SIZE=4, four program instances launch, and each one computes:</p><pre>pid=0: offsets = 0*4 + [0,1,2,3] = [ 0,  1,  2,  3]<br>pid=1: offsets = 1*4 + [0,1,2,3] = [ 4,  5,  6,  7]<br>pid=2: offsets = 2*4 + [0,1,2,3] = [ 8,  9, 10, 11]<br>pid=3: offsets = 3*4 + [0,1,2,3] = [12, 13, 14, 15]</pre><p>No overlap. Full coverage. Each program instance owns exactly one tile of 4 elements.</p><p>The critical thing to internalize: offsets is not a scalar. It&#39;s a <strong>tensor of integers</strong>. When you later write tl.load(x_ptr + offsets), Triton adds that integer tensor to the base pointer and gets a <strong>tensor of pointers</strong> — one pointer per element in the tile. Then tl.load fetches all values simultaneously, returning a tensor of floats. Every variable in a Triton kernel is a tile, not a scalar. This is the mental model shift that makes everything else work.</p><p>One common beginner mistake makes this concrete: forgetting to multiply by pid. If you write offsets = tl.arange(0, BLOCK_SIZE) without the pid * BLOCK_SIZE term, every program instance computes the same offsets [0, 1, 2, 3]. All 4 instances process the same first tile. Your kernel runs without errors, produces output of the right shape, but only the first BLOCK_SIZE elements are correct. The rest are untouched or garbage. It&#39;s a silent correctness bug — the kind that shows up in production, not in unit tests.</p><p>But there’s a problem this model creates immediately.</p><p>Consider an array of 7 elements with BLOCK_SIZE=4. How many program instances do you need? triton.cdiv(7, 4) = 2. Two instances. Let&#39;s trace what happens:</p><pre>pid=0: offsets = [0, 1, 2, 3]  -&gt; all valid, elements 0-3 exist<br>pid=1: offsets = [4, 5, 6, 7]  -&gt; element 7 (index 8) does NOT exist</pre><p>Instance 1 tries to load index 7 from a 7-element array. In a language like Python, this would raise an IndexError. On a GPU, there is no bounds checking. tl.load will read whatever bytes happen to sit at that memory address — possibly another tensor&#39;s data, possibly uninitialized memory, possibly a memory address that triggers a hardware fault. The results range from silently wrong output to a full GPU crash.</p><p>And it gets worse on the write side. tl.store at index 7 writes to memory you don&#39;t own. You might corrupt another tensor, corrupt CUDA&#39;s internal data structures, or trigger an illegal memory access that kills your entire Python process. This is not an edge case. It happens every time your data size isn’t perfectly divisible by your block size — which is almost always. A model with 4097 elements and BLOCK_SIZE=1024 hits this on the last of 5 tiles.</p><p>The solution is <strong>masks</strong>: boolean tensors that guard every load and store.</p><pre>offsets = pid * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)<br>mask = offsets &lt; n_elements<br>x = tl.load(x_ptr + offsets, mask=mask, other=0.0)</pre><p>mask is a boolean vector, same shape as offsets. For our 7-element example:</p><pre>pid=0: offsets=[0,1,2,3], mask=[True, True, True, True]   → load all 4<br>pid=1: offsets=[4,5,6,7], mask=[True, True, True, False]  → load 3, substitute 0.0 for index 7</pre><p>When mask[i] is False, tl.load returns the other value (here, 0.0) instead of touching memory. For tl.store, masked-out positions simply aren&#39;t written. The out-of-bounds access never happens.</p><p>This looks like a small detail, but the other value is a correctness landmine. For vector addition, other=0.0 is fine — adding zero is harmless. But consider a softmax kernel. Softmax first finds the maximum value in a row, then subtracts it for numerical stability. If you mask with other=0.0, those zeros participate in the max calculation. For a row of all-negative values, the masked zeros become the spurious maximum, and the entire softmax output is wrong.</p><p>The fix: other=-float(&#39;inf&#39;) for max operations. Negative infinity loses every comparison, so masked elements never affect the result:</p><pre># Softmax: masked loads must use -inf, not 0.0<br>row = tl.load(input_ptr + offsets, mask=mask, other=-float(&#39;inf&#39;))<br>row_max = tl.max(row, axis=0)  # -inf entries don&#39;t affect max</pre><p>Every operation has its own correct other value. Sum reductions need other=0.0. Min reductions need other=float(&#39;inf&#39;). Multiplications might need other=1.0. There is no universal default — you have to think about what the identity element is for your specific computation.</p><p>Now let’s scale this up to something more interesting: matrix multiplication. This is where tiling becomes a real algorithm, not just a way to partition a flat array.</p><p>Say you have two matrices: A is 2048×2048 and B is 2048×2048. The output C = A × B is also 2048×2048. That’s about 8.6 billion multiply-add operations. No single program instance can do all of that.</p><p>So you tile the output (divide the output matrix C into smaller rectangular chunks → tiles). Pick a tile size of 128×128. The output matrix C has 2048/128 = 16 tiles along rows and 16 tiles along columns. That’s 16 × 16 = 256 tiles total. You launch a 2D grid of 256 program instances, one per output tile:</p><pre>grid = lambda meta: (<br>    triton.cdiv(M, meta[&#39;BLOCK_SIZE_M&#39;]),<br>    triton.cdiv(N, meta[&#39;BLOCK_SIZE_N&#39;])<br>)</pre><p>Inside the kernel, each program instance identifies itself in two dimensions:</p><pre>pid_m = tl.program_id(0)  # which row of tiles (0 to 15)<br>pid_n = tl.program_id(1)  # which column of tiles (0 to 15)</pre><p>Program instance (3, 5) computes the 128×128 chunk of C starting at row 384 (3×128), column 640 (5×128). Clear enough. But here’s the part that’s less obvious.</p><p>To compute a single element C[i][j], you need the dot product of row i of A and column j of B — that’s 2048 multiply-adds. To compute the entire 128×128 output tile, you need 128 full rows of A (each 2048 elements long) and 128 full columns of B (each 2048 elements long). That’s 128 × 2048 + 128 × 2048 = about 1 million floats just for the inputs to one tile. You can’t fit all of that into registers or shared memory at once.</p><p>So each program instance <strong>iterates over the K dimension in chunks</strong>. K is the shared dimension — the 2048 that A’s columns and B’s rows have in common. You break K into tiles of 128:</p><pre>Iteration 0: Load A_tile[:128, 0:128]   and B_tile[0:128, :128]     -&gt; multiply, accumulate<br>Iteration 1: Load A_tile[:128, 128:256] and B_tile[128:256, :128]   -&gt; multiply, accumulate<br>Iteration 2: Load A_tile[:128, 256:384] and B_tile[256:384, :128]   -&gt; multiply, accumulate<br>...<br>Iteration 15: Load A_tile[:128, 1920:2048] and B_tile[1920:2048, :128] -&gt; multiply, accumulate</pre><p>Each iteration loads a 128×128 slice of A and a 128×128 slice of B — small enough to fit in registers — multiplies them using tl.dot (which the compiler maps to tensor core instructions), and accumulates the partial result into a running sum. After 16 iterations (2048 / 128), the output tile is complete.</p><p>So the full picture: 256 program instances run in parallel across the GPU. Each one iterates sequentially through 16 K-dimension chunks. Within each chunk, tl.dot runs a 128×128 matrix multiply at hardware speed. The result is a complete 2048×2048 matrix multiplication.</p><p>Building the 2D tile offsets uses the same tl.arange pattern, but with broadcasting to create a grid:</p><pre>row_offsets = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)[:, None]  # shape: [128, 1]<br>col_offsets = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)[None, :]  # shape: [1, 128]<br># Broadcasting: row_offsets + col_offsets * stride -&gt; shape [128, 128] pointer grid</pre><p>Every concept from the 1D case carries over. Masks protect boundary tiles where M or N isn’t divisible by the block size. The other value for accumulation is 0.0 because adding zero to a running sum is harmless.</p><p>At this point you can write correct Triton kernels. But correct and fast are different things on a GPU. The performance difference between a naive and well-tuned Triton kernel is often 2–3x and can reach <strong>95x</strong> in extreme cases.</p><p>The single most impactful knob is BLOCK_SIZE. Consider a simple sin kernel — each element just computes tl.sin(x). Benchmarks show that BLOCK_SIZE=4 versus an autotuned block size can produce a <strong>95× performance gap</strong>. The reason: with tiny blocks, each streaming multiprocessor (SM) doesn&#39;t have enough work to hide memory latency. The GPU has deep pipelines, while one group of threads waits for data from HBM (400+ cycles), another group should be computing. With BLOCK_SIZE=4, there&#39;s nothing to overlap. The SM stalls.</p><p>Triton provides @triton.autotune to search across configurations automatically:</p><pre>@triton.autotune(configs=[<br>    triton.Config({&#39;BLOCK_SIZE&#39;: 128}, num_warps=4),<br>    triton.Config({&#39;BLOCK_SIZE&#39;: 256}, num_warps=4),<br>    triton.Config({&#39;BLOCK_SIZE&#39;: 512}, num_warps=8),<br>    triton.Config({&#39;BLOCK_SIZE&#39;: 1024}, num_warps=8),<br>], key=[&#39;n_elements&#39;])<br>@triton.jit<br>def my_kernel(...):<br>    ...</pre><p>The key parameter tells the autotuner: re-run the search when n_elements changes, because the optimal block size depends on problem size. num_warps controls how many warps (groups of 32 threads) each program instance uses — more warps mean more parallelism within a tile but also more register pressure.</p><p>For matrix multiplication, the optimization goes deeper. The order in which program instances are mapped to output tiles matters enormously for cache performance. Naive row-major ordering — pid 0 gets tile (0,0), pid 1 gets (0,1), etc., this causes poor reuse of the GPU’s L2 cache. The Triton matmul tutorial demonstrates <strong>grouped ordering</strong>: processing tiles in clusters so that nearby program instances share input data in L2. This single change jumps performance from roughly 220 TFLOPS to 245 TFLOPS on an A100, that’s over 10% from just reordering which tile each program instance computes.</p><p>The largest gains come from <strong>algorithm-level fusion</strong>. PyTorch’s default softmax reads the input tensor multiple times from HBM: once to compute the max, once to subtract and exponentiate, once to sum, once to divide. That’s four round trips to the slowest level of the memory hierarchy. A fused Triton softmax kernel loads the data once into registers, computes everything, and writes the result once. Two HBM accesses instead of eight that’s roughly 4x less memory traffic. In practice, the fused Triton kernel delivers about 4x the throughput of naive PyTorch softmax and even beats torch.softmax at larger sizes.</p><p>To understand why Triton can do all this, it helps to see what the compiler actually does with your tile-level code.</p><p>The compilation pipeline has six stages: your Python function decorated with @triton.jit gets parsed into <strong>Triton IR</strong> (a custom intermediate representation for tile operations), then lowered to <strong>Triton GPU IR</strong> (which adds thread-level layout information), then to <strong>LLVM IR</strong>, then to <strong>PTX</strong> (NVIDIA&#39;s assembly language), and finally to <strong>cubin</strong> (the binary that runs on the GPU). Each stage is cached at ~/.triton/cache/ — you can inspect any of them.</p><p>The magic mostly happens in the Triton IR -&gt; Triton GPU IR stage. This is where the compiler makes all the decisions you’d have to make manually in CUDA: It assigns <strong>layout encodings</strong> that determine how each element in your tile maps to a specific thread in a specific warp. These encodings are chosen to maximize memory coalescing — consecutive elements in the fastest-varying dimension get assigned to consecutive threads.</p><p>It automatically manages <strong>shared memory</strong>. When your kernel needs to share data between different phases of computation (like the accumulation loop in matmul), the compiler allocates SRAM on the SM and inserts the necessary synchronization barriers. You never see this in your source code.</p><p>It recognizes tl.dot operations and lowers them to <strong>tensor core MMA instructions</strong> (mma.sync.m16n8k16), which compute small matrix multiplies at hardware-peak throughput.</p><p>It inserts <strong>software pipelining</strong> for loops — while iteration N’s data is being computed, iteration N+1’s data is already being fetched from memory using asynchronous copies (cp.async). This overlaps compute and memory access, hiding latency.</p><p>What you — the programmer — still control: tile sizes, grid dimensions, which data to load and when, the algorithm itself, and sometimes compiler hints when automatic inference falls short. That’s the division of labor. You make the architectural decisions. The compiler handles the thousands of micro-decisions that make GPU code fast.</p><p>The result: Triton matmul achieves over 90% of peak device throughput, matching cuBLAS (NVIDIA’s hand-tuned library). Production Triton kernels in PyTorch and inference frameworks typically hit 80–95% of expert CUDA performance with a fraction of the code.</p><p>Here’s the mental model that makes Triton click:</p><p><strong>You are not writing code for a thread. You are writing code for a tile.</strong></p><p>Every variable is a block of data. Every operation processes the full block. tl.program_id tells you which tile you own. tl.arange builds the local indices within your tile. Masks protect the boundary tiles where the data doesn&#39;t fill a complete block. The grid of program instances is how your tiles cover the full problem.</p><p>Once this inversion is internalized, Triton kernels become surprisingly readable. Each one is a straightforward description: load a tile, transform it, store the result. The compiler turns that description into the thousands of thread-level instructions that actually execute on the GPU.</p><p>That’s not CUDA in Python. That’s a different language for a different way of thinking about the same hardware.</p><p><em>If you’re learning GPU programming and inference optimization, I’m documenting the whole journey. Follow along.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c65c15ce3c46" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why PyTorch Wastes Your GPU Memory on Purpose (And Why That’s Brilliant)]]></title>
            <link>https://medium.com/@varuntej07/why-pytorch-wastes-your-gpu-memory-on-purpose-and-why-thats-brilliant-0a76899797fb?source=rss-ce1906f9f6e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/0a76899797fb</guid>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[llm-inference]]></category>
            <category><![CDATA[parallel-computing]]></category>
            <category><![CDATA[computer-architecture]]></category>
            <category><![CDATA[memory-management]]></category>
            <dc:creator><![CDATA[Varuntej]]></dc:creator>
            <pubDate>Wed, 11 Feb 2026 08:22:36 GMT</pubDate>
            <atom:updated>2026-02-11T18:47:28.512Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>A low-level look at how GPU memory actually works, from silicon to </strong><strong>torch.cuda.memory_allocated()</strong></p><p>I was going through a GPU memory profiling exercise on Colab. I created a 200MB tensor on a T4 and printed the memory stats:</p><pre>a = torch.randn(50_000_000, device=&#39;cuda&#39;)  # 50M floats × 4 bytes = 200MB<br>print(f&quot;Allocated: {torch.cuda.memory_allocated() / 1e6:.1f} MB&quot;)<br>print(f&quot;Reserved:  {torch.cuda.memory_reserved() / 1e6:.1f} MB&quot;)<br>print(f&quot;Cached: {torch.cuda.memory_cached() / 1e6:.1f} MB&quot;)</pre><pre>Allocated: 200.0 MB<br>Reserved:  201.3 MB<br>Cached: 201.3 MB</pre><p>Okay, close enough. Then I ran the same cell again. Same code. Same tensor size.</p><pre>Allocated: 200.0 MB<br>Reserved:  402.7 MB<br>Cached: 402.7 MB</pre><p>Wait. I still have one 200MB tensor. But PyTorch is now hoarding 402MB of GPU memory? That is double what I am using.</p><p>Then I ran nvidia-smi and saw an even bigger number on top of that.</p><p>Three tools. Three different numbers. Same GPU. Same model. That is when I realized I did not actually understand how GPU memory works. Not the textbook “GPUs have VRAM” version. The real version, what happens byte by byte when you create a tensor, who talks to whom, and why PyTorch deliberately grabs memory it has no plans to use right now.</p><p>Here is everything I learned.</p><h3>First, What Even Is GPU Memory?</h3><p>Before we talk about PyTorch, we need to understand the hardware it sits on top of.</p><p>A GPU is not one big processor. It is a grid of smaller processors called <strong>Streaming Multiprocessors (SMs)</strong>. A T4 has 40 of them. An A100 has 108. Each <strong>SM </strong>has <a href="https://docs.nvidia.com/cuda/cuda-programming-guide/index.html"><strong>CUDA </strong></a>cores (a <strong>scalar ALU lane</strong> on NVIDIA GPUs) for math, Tensor Cores (specialized <strong>matrix math engines</strong>) for matrix operations, and its own small fast memory.</p><p>The memory on a GPU is organized in a hierarchy, from fastest and smallest to slowest and largest:</p><p><strong>Registers</strong> sit inside each CUDA core. They are the fastest memory on the chip, single-cycle access. Each thread (one core — one thread) gets a private set of registers to hold its immediate working values. Think of these like the numbers you hold in your head mid-calculation. They disappear the moment the thread finishes.</p><p><strong>Shared Memory / L1 Cache</strong> is a small SRAM block on each SM, typically 48KB to 228KB depending on the GPU. All threads within a thread block (a group of threads assigned to the same SM) can read and write to this shared pool. This is where the real optimization happens: you load a small tile of your matrix from main memory into shared memory once, then every thread in the block reads from it repeatedly without going back to main memory. Access latency is roughly 20 to 30 clock cycles.</p><p><strong>L2 Cache</strong> is shared across all SMs on the entire GPU. On an A100, it is 40MB. When data is not in L1 or shared memory, the SM checks L2 before going all the way to main memory. Latency is around 200 or more cycles.</p><p><strong>HBM (High Bandwidth Memory)</strong> is the big one. This is what people call “VRAM.” It is the 16GB on a T4, the 80GB on an A100. Physically, HBM is a stack of DRAM chips sitting on or next to the GPU die, connected by thousands of tiny wires called Through-Silicon Vias. This is where your model weights, KV cache, and activation tensors live. Massive bandwidth (900 GB/s on A100, 3.35 TB/s on H100) but the slowest access latency in the hierarchy at 400 or more cycles.</p><p>When you hear “my model does not fit in GPU memory,” people mean HBM. Everything else in this hierarchy is managed automatically by hardware and the CUDA runtime. HBM is the finite resource you are fighting over.</p><h3>How the CPU and GPU Actually Talk</h3><p>Here is something that broke my mental model — the CPU and GPU do not share memory.</p><p>They are two completely separate computing systems. The CPU has its own RAM (your 16GB or 64GB of DDR4/DDR5). The GPU has its own HBM. They are connected by a <strong>PCIe bus</strong>, a hardware link between two independent machines. PCIe Gen 4 x16 gives you about 32 GB/s. Compare that to HBM’s 900+ GB/s. The bridge between CPU and GPU is roughly <strong>28x slower</strong> than the GPU’s own memory bus.</p><p>This means every time data crosses between them, it is expensive. Here is what happens when you call</p><pre>from transformers import AutoModel<br><br># Download a pretrained model (small enough to not OOM)<br>model = AutoModel.from_pretrained(&quot;bert-base-uncased&quot;).cuda()<br><br># Right now weights are in CPU RAM<br>print(f&quot;Allocated before .cuda(): {torch.cuda.memory_allocated() / 1e6:.1f} MB&quot;)<br><br># This moves all weights from CPU RAM → GPU HBM over PCIe<br>model.cuda()<br><br>print(f&quot;Allocated after .cuda():  {torch.cuda.memory_allocated() / 1e6:.1f} MB&quot;)<br>print(f&quot;Reserved after .cuda():   {torch.cuda.memory_reserved() / 1e6:.1f} MB&quot;)</pre><pre>Allocated before .cuda(): 638.1 MB<br>Allocated after .cuda(): 638.1 MB<br>Reserved after .cuda(): 721.4 MB</pre><p>Your model weights are sitting in CPU RAM. PyTorch asks CUDA to allocate space in HBM. Then a <strong>DMA engine</strong> (a dedicated hardware unit on the GPU) copies the weights from CPU RAM to HBM over PCIe. Neither CPU cores nor GPU compute cores do this copy. The DMA engine handles it autonomously. For a 16GB model on PCIe Gen 4, this transfer alone takes about half a second.</p><p>Once weights are in HBM, the GPU accesses them at full bandwidth. The CPU’s job is done.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QREL_L9hrWKQEEg6EPqCUg.png" /></figure><p>When you run output = model(input), the CPU does not compute anything. It writes a <strong>command packet</strong> into a shared command queue that tells the GPU which kernel to launch, with what arguments (pointers to tensors in HBM, matrix dimensions, etc.). It then pokes a hardware register called a <strong>doorbell</strong> that signals &quot;new work available.&quot; The GPU&#39;s command processor reads the command and distributes work across SMs. The CPU is free the entire time.</p><p>This is <strong>asynchronous execution</strong>. The CPU queues work and moves on. The GPU works through the queue independently.</p><p>The only time the CPU waits is when it needs a result. Calling print(tensor) forces <strong>synchronization</strong>: the CPU sends a sync request, waits for all queued GPU work to finish, then reads the result back over PCIe. A single print() in an inference loop drains the entire pipeline. This is the most common hidden performance killer in GPU code.</p><h3>PyTorch’s Memory Caching Allocator</h3><p>Now the memory puzzle from the beginning makes perfect sense.</p><p>Every time PyTorch needs GPU memory for a tensor, it could call cudaMalloc to request memory from the CUDA runtime. But cudaMalloc is slow for two reasons: it takes microseconds (which is comparable to kernel execution time), and it forces a <strong>CPU-GPU synchronization</strong> because the GPU must finish all pending work before CUDA can safely modify the GPU&#39;s memory page tables.</p><p>If you are doing hundreds of small allocations per forward pass, calling cudaMalloc for each one kills throughput.</p><p>So PyTorch puts its own memory manager between your code and CUDA. The <strong>CUDACachingAllocator</strong> works like this:</p><p>The first time you create a tensor, the allocator calls cudaMalloc and grabs a chunk of HBM. Not just the exact size you asked for, but rounded up to the nearest <strong>2 MiB block boundary</strong>. This is why a 200,000,000-byte tensor (200MB) results in 201.3MB reserved: 200,000,000 bytes rounds up to 192 MiB = 201,326,592 bytes.</p><p>The allocator now manages that block internally. When you create another small tensor, it carves it out of existing cached space using pointer arithmetic. Nanoseconds. No GPU call. When you delete a tensor, the allocator does NOT return the memory to CUDA. It puts the block on an internal <strong>free list</strong>. Next time you need that size or smaller, it reuses the cached block instantly.</p><p>This gives us the two key functions:</p><p><strong>torch.cuda.memory_allocated()</strong> is the sum of bytes occupied by your live tensors. Your actual data footprint.</p><p><strong>torch.cuda.memory_reserved()</strong> is the total bytes the allocator has claimed from CUDA via cudaMalloc. This includes live tensors plus all the free blocks sitting in the allocator&#39;s cache waiting to be reused.</p><p>The gap between them is the <strong>allocator overhead </strong>— memory that PyTorch grabbed from the GPU but is not currently using. It is not wasted. It is pre-staged so that future allocations skip the expensive cudaMalloc path.</p><h3>Why Running the Same Cell Twice Doubled “Reserved”</h3><p>Back to the mystery. First run: Allocated 200MB, Reserved 201.3MB. Second run: Allocated 200MB, Reserved 402.7MB.</p><p>This comes down to <strong>Python’s assignment order</strong>. When you run a = torch.randn(50_000_000, device=&#39;cuda&#39;) the second time, Python evaluates the right side first. It creates the new tensor before dropping the old reference to a. So during that creation, the old tensor is still alive, still occupying its 201.3MB block. The allocator sees no free blocks available. It calls cudaMalloc for another 201.3MB chunk.</p><p>Only after the new tensor exists does Python assign it to a, dropping the reference to the old tensor. The old block goes to the free list.</p><p>Final state: one live tensor at 200MB (allocated), but two 201.3MB blocks claimed from CUDA (reserved = 402.7MB). One block is in use, the other is sitting in the allocator’s cache, ready for instant reuse.</p><p>This exact pattern happens thousands of times during model inference. Intermediate activations get created and freed every layer. The allocator absorbs those allocations and deallocations without ever touching CUDA again after the first few forward passes. That is the entire point.</p><p>At large scales, you see the same rounding effect. A tensor that reports 8,191MB allocated might show 8,198MB reserved. The 7MB gap is the allocator’s block alignment overhead. The allocator always rounds up. It never rounds down. Every allocation pays a small tax for the speed of cached reuse.</p><h3>The Third Number: nvidia-smi</h3><p>Run !nvidia-smi in a Colab cell while your model is loaded. The &quot;Memory-Used&quot; number will be <strong>higher</strong> than both memory_allocated and memory_reserved.</p><p>nvidia-smi reports from the GPU hardware&#39;s perspective. It sees every byte claimed through cudaMalloc by anyone, not just PyTorch. The extra memory comes from three sources.</p><p><strong>CUDA context.</strong> The moment any CUDA operation runs, even torch.cuda.is_available(), the CUDA runtime allocates a context on the GPU: driver structures, kernel code, thread stack space, page tables. This costs 300MB to 800MB depending on the GPU. You have not created a single tensor and you have already lost half a gigabyte.</p><p><strong>Library workspaces.</strong> When PyTorch calls cuBLAS for matrix multiplication or cuDNN for convolutions, those libraries allocate their own temporary workspace buffers in HBM. These go through cudaMalloc directly, outside PyTorch&#39;s caching allocator. PyTorch has no visibility into them.</p><p><strong>Other processes.</strong> Anything else using the GPU (monitoring tools, display servers, other scripts) shows up in nvidia-smi too.</p><p>The hierarchy is always:</p><pre>nvidia-smi used  &gt;  memory_reserved  ≥  memory_allocated</pre><h3>Why This Actually Matters</h3><p>This is not academic trivia. Say you are deploying a 7B parameter model in FP16 on a T4 (16GB). The weights alone are about 14GB. You see 2GB of remaining HBM and think you have room for a KV cache.</p><p>But once you account for CUDA context (500MB), allocator overhead (10 to 15 percent of working set), cuBLAS workspaces (a few hundred MB), and peak activation memory during the forward pass, your real KV cache budget is closer to 500MB. Maybe less.</p><p>If you only check memory_allocated, you think you have headroom. If you only check nvidia-smi, you cannot tell what is reclaimable cache versus fixed overhead. You need all three numbers to make accurate capacity decisions.</p><p>This is exactly why inference engines like vLLM bypass PyTorch’s allocator entirely for KV cache management. They implement their own <strong>PagedAttention</strong> allocator to eliminate fragmentation for the single largest memory consumer in LLM serving. They understood the gap and engineered around it.</p><p>That understanding is what separates running model.generate() from actually engineering inference systems.</p><p><em>If you are learning GPU programming and inference optimization, I am documenting the whole journey. Follow along.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0a76899797fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Physics of GPU Memory: A Deep Dive into Bits, Circuits, and AI Quantization]]></title>
            <link>https://medium.com/@varuntej07/why-computers-waste-memory-on-purpose-and-why-that-makes-gpus-fast-7e1661f5e69b?source=rss-ce1906f9f6e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e1661f5e69b</guid>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[computer-architecture]]></category>
            <category><![CDATA[binary]]></category>
            <category><![CDATA[quantization]]></category>
            <category><![CDATA[systems-engineering]]></category>
            <dc:creator><![CDATA[Varuntej]]></dc:creator>
            <pubDate>Tue, 10 Feb 2026 07:12:39 GMT</pubDate>
            <atom:updated>2026-03-26T19:51:34.830Z</atom:updated>
            <content:encoded><![CDATA[<h3>The rabbit hole I fell into while studying GPU programming</h3><p>I was reading about model quantization — the thing that lets you run a 16GB AI model in 4GB of VRAM — and I hit this line in a tutorial:</p><blockquote><em>“An 8-bit integer means each value occupies 8 bits of memory. With 8 bits, there are 2 ²⁸ = 256 possible values.”</em></blockquote><p>And I thought I understood it. I really did. Then I tried to actually explain it to myself and realized I had no idea what “a value occupying 8 bits” actually means at the physical level.</p><p>This sent me down a rabbit hole that changed how I understand everything about computers, GPUs, and why quantization works the way it does. Here’s the journey.</p><h3>Wait, what even IS a bit?</h3><p>A bit is actually a single wire on a chip that is either ON or OFF. Electricity flowing = 1. No electricity = 0. That’s it. There is no 2. There is no 3. Just 0 or 1.</p><p>Your computer’s RAM? Billions of these tiny switches sitting on a silicon chip.</p><p>So when someone says “8 bits” they mean 8 of these switches.</p><p>Picture a wall with 8 light switches on it, labeled right to left:</p><pre>Switch:    7     6     5     4     3     2     1     0<br>State:   [OFF] [OFF] [OFF] [OFF] [OFF] [OFF] [OFF] [OFF]<br>Binary:    0     0     0     0     0     0     0     0</pre><p>That configuration represents the number 0.</p><p>Flip switch 0 ON:</p><pre>Switch:    7     6     5     4     3     2     1     0<br>State:   [OFF] [OFF] [OFF] [OFF] [OFF] [OFF] [OFF] [ON]<br>Binary:    0     0     0     0     0     0     0     1</pre><p>That’s the number 1.</p><p>Now here’s where it gets interesting. Flip switch 1 ON, switch 0 back OFF:</p><pre>Switch:    7     6     5     4     3     2     1     0<br>State:   [OFF] [OFF] [OFF] [OFF] [OFF] [OFF] [ON] [OFF]<br>Binary:    0     0     0     0     0     0     1     0</pre><p>That’s the number 2. Not “ten.” Binary 10 = decimal 2.</p><p>In binary each switch can only be 0 or 1, so after 1 you reset to 0 and carry, meaning each position to the left represents twice as many combinations as the one before it. That’s why the weights are 1, 2, 4, 8… which are 2 ⁰, 2 ¹, 2 ², 2 ³….</p><h3>But why does binary 10 equal 2?</h3><p>Each switch position has a weight — a power of 2, starting from the right:</p><pre>Switch:     7      6      5      4      3      2      1      0<br>Weight:    128     64     32     16      8      4      2      1<br>           (2⁷)  (2⁶)   (2⁵)  (2⁴)   (2³)   (2²)   (2¹)   (2⁰)</pre><p>To get the number: multiply each switch state (0 or 1) by its weight, then add them up.</p><p>Let’s store the number 42:</p><pre>Switch:     7      6      5      4      3      2      1      0<br>Weight:    128     64     32     16      8      4      2      1<br>State:      0      0      1      0      1      0      1      0</pre><pre>Value = (0×128) + (0×64) + (1×32) + (0×16) + (1×8) + (0×4) + (1×2) + (0×1)<br>      = 32 + 8 + 2<br>      = 42</pre><p>So the binary representation of 42 is 00101010. Eight switches. Eight bits. The number 42 &quot;occupies&quot; 8 bits.</p><p>And here’s the part that clicked: “8 bits” does NOT mean the number is 8 digits long. It means we are using 8 switches to represent it, even though the number 42 only actually <em>needs</em> 6 of those switches.</p><p>The two leftmost switches? Just sitting there at zero. Wasted. On purpose.</p><p>More on that in a second.</p><h3>The 256 thing</h3><p>With 8 switches, each having 2 possible states (ON/OFF), the total combinations are:</p><pre>2 × 2 × 2 × 2 × 2 × 2 × 2 × 2 = 2⁸ = 256</pre><p>Smallest value: all OFF = 00000000 = 0</p><p>Largest value: all ON = 11111111 = 128 + 64 + 32 + 16 + 8 + 4 + 2 + 1 = 255</p><p>That’s why unsigned 8-bit integers go from 0 to 255. You literally cannot represent 256 — you’d need a 9th switch.</p><p><strong>Where you’ve seen this:</strong> Every pixel on your screen uses this. RGB color values — each one is an 8-bit unsigned integer. Pure red is R=255, G=0, B=0. That’s 24 switches for one pixel. Your 1920×1080 display? About 50 million switches worth of color data per frame.</p><h3>The question that broke my brain</h3><p>Here’s where I got stuck. I just showed you that 42 in binary is 101010. That&#39;s 6 bits. Not 8. So why are we wasting 2 extra switches on zeros?</p><p>And it’s not just 42. The number 3 is 11 — that&#39;s only 2 bits. But if I store it as an 8-bit integer, it becomes 00000011. Six wasted switches.</p><p>Why? Can’t the computer just… use the exact number of bits each value needs?</p><p>This is the question most people skip. But answering it explains why computers work the way they do, why quantization saves memory, and why NVIDIA keeps building new hardware.</p><h3>The parking lot analogy</h3><p>Imagine a parking lot where every space is the same width — wide enough for the biggest SUV.</p><p>When a motorcycle parks, it occupies the full space. The remaining area is empty, but no one else can use it. The motorcycle doesn’t get a smaller spot just because it’s small.</p><p>That’s what a data type is. When you write code, you choose the parking space size before you know what’s parking there:</p><pre>uint8_t  x = 42;   // 8-bit container<br>uint16_t y = 42;   // 16-bit container<br>uint32_t z = 42;   // 32-bit container</pre><p>All three store the exact same number (42), but they use different amounts of memory:</p><pre>uint8_t  (8 bits):    0 0 1 0 1 0 1 0</pre><pre>uint16_t (16 bits):   0 0 0 0 0 0 0 0  0 0 1 0 1 0 1 0</pre><pre>uint32_t (32 bits):   0 0 0 0 0 0 0 0  0 0 0 0 0 0 0 0<br>                      0 0 0 0 0 0 0 0  0 0 1 0 1 0 1 0</pre><p>Same motorcycle. Different sized parking spots. The extra zeros are just… there.</p><h3>Why not just use the minimum bits?</h3><p>This was the real rabbit hole. Turns out there’s a very good reason, and it comes down to physics.</p><h3>Reason 1: The hardware needs to know where things are</h3><p>Say you have 4 numbers stored back-to-back in memory using fixed 8-bit containers:</p><pre>Address:  0        8        16       24       32<br>          |--------|--------|--------|--------|<br>          00101010  00000011  11111111  00000001<br>          (42)      (3)       (255)     (1)</pre><p>If I want the 3rd number, I do one multiplication: start + (index × size_of_element_in_bits) = bit 16. Jump there. Done. Instant.</p><p>This is called <strong>random access</strong>. You can reach any element without looking at anything else.</p><p>Now try it with variable-width storage, where each number uses only the bits it needs:</p><pre>Address:  0      6     8        16       21<br>          |------|--|--------|------|<br>          101010  11  11111111  00001<br>          (42)   (3)  (255)     (1)<br>          6 bits 2bit  8 bits  5 bits</pre><p>Where is the 3rd number? You can’t compute it anymore. You have to scan from the beginning: read value 1’s length, skip forward, read value 2’s length, skip forward, and only then do you find value 3.</p><p>For the 3rd element, maybe that’s fine. For the millionth element? You’re scanning through 999,999 entries first. That’s the difference between O(1) and O(n), and at the scale computers operate at, that’s the difference between instant and unusable.</p><h3>Reason 2: The circuits are physically wired for fixed widths</h3><p>This is the part nobody ever explains, and it’s the part that made everything click for me.</p><p>A CPU is not a brain. It’s billions of switches connected by metal wires etched into silicon. Those wires have physical, permanent connections.</p><p>An addition circuit for 8-bit numbers has exactly 8 “<a href="https://www.geeksforgeeks.org/digital-logic/full-adder-in-digital-logic/">full adder</a>” units chained together. Each one takes one bit from number A, one bit from number B, and a carry-in, and produces a sum bit and carry-out:</p><pre>Bit 7 ──→ [Full Adder] ──carry──→<br>Bit 6 ──→ [Full Adder] ──carry──→<br>Bit 5 ──→ [Full Adder] ──carry──→<br>Bit 4 ──→ [Full Adder] ──carry──→<br>Bit 3 ──→ [Full Adder] ──carry──→<br>Bit 2 ──→ [Full Adder] ──carry──→<br>Bit 1 ──→ [Full Adder] ──carry──→<br>Bit 0 ──→ [Full Adder]</pre><p>This produces the answer in <strong>one clock cycle</strong> — about 0.3 nanoseconds on a modern CPU. Whether you’re adding 1+1 or 200+55, it takes the same time. All 8 adders fire simultaneously. The circuit doesn’t know what the values are. It doesn’t care.</p><p>If you wanted variable-width addition, the circuit would first need to figure out how wide each input is, then decide how many adders to activate, then handle the case where the two inputs have different widths. That’s not a simple circuit anymore — that’s a multi-step decision process. You’ve just traded a one-cycle hardware operation for something that takes 5–10 cycles.</p><p>At the scale GPUs operate (trillions of operations per second), that 5–10x slowdown is the difference between a model running in real-time and a model being completely useless.</p><h3>OK, but has anyone actually tried variable-width?</h3><p>Yes. It works. It’s everywhere. But not for computation — only for storage and transmission.</p><p><strong>UTF-8</strong> is the most famous example. Characters use 1, 2, 3, or 4 bytes:</p><pre>&#39;A&#39;  → 1 byte:   01000001<br>&#39;é&#39;  → 2 bytes:  11000011 10101001<br>&#39;中&#39; → 3 bytes:  11100100 10111000 10101101<br>&#39;😀&#39; → 4 bytes:  11110000 10011111 10011000 10000000</pre><p>English text at ~1 byte per character instead of 4. Great compression. But the tradeoff is exactly what I described: you can’t jump to the 50th character without scanning from the start. string[49] in UTF-8 is O(n), not O(1).</p><p>That’s why programming languages convert UTF-8 to fixed-width internally when they need random access.</p><p><strong>Huffman coding</strong> is another one — used in ZIP, JPEG, MP3. Frequent values get short codes, rare values get long ones. But decoding is sequential. You can never jump to the middle.</p><p><strong>Variable-length integers (varints)</strong> show up in Protocol Buffers, Google’s serialization format. Small numbers use 1 byte, large ones use up to 10. Saves space on the wire.</p><p>But here’s the pattern: <strong>every single one of these gets converted back to fixed-width before the CPU operates on it.</strong> Compress for storage, decompress into fixed containers for math. Every time.</p><h3>Why this matters if you care about AI</h3><p>This is where the rabbit hole connects back to the stuff I was actually studying.</p><p>When people talk about running Llama-3 in “4-bit quantization,” this is what’s happening under the hood:</p><pre>Storage (GPU memory):  4-bit weights, packed tight<br>                            ↓<br>Dequantization:        Unpack 4-bit → convert to FP16 (16-bit, fixed)<br>                            ↓<br>Computation:           FP16 matrix multiply on tensor cores (fixed-width circuits)<br>                            ↓<br>Result:                FP16 output</pre><p>The weights are stored in 4-bit to save memory. But the GPU doesn’t have 4-bit arithmetic circuits (at least not on older GPUs). So every weight gets unpacked to 16-bit before the math happens. That unpacking has a cost — it shows up as “dequantization overhead” in profiler traces.</p><p>Here’s the math that made me go “oh”:</p><p><strong>Llama-3–8B</strong> has 8 billion parameters.</p><p>At FP16 (16 bits each): 8,000,000,000 × 16 bits = 16 GB</p><p>At 4-bit: 8,000,000,000 × 4 bits = 4 GB</p><p>Same model. Same 8 billion weights. Each one is just stored in a 4-switch container instead of a 16-switch container. The value that used to have 65,536 possible representations (2¹⁶) now gets squeezed into one of 16 possible values (2⁴). The nearest one is picked. That rounding error is why quantization can hurt output quality.</p><p>And here’s the part that connects everything: <strong>NVIDIA’s newer GPUs (H100, B200) added native FP8 and INT4 tensor core instructions.</strong> That means they literally burned new fixed-width circuits into silicon — 4-bit and 8-bit adders and multipliers — because the inference workload proved the demand.</p><p>Instead of the expensive “decompress to FP16 -&gt; compute -&gt; store back” loop, these GPUs can do the math directly on the smaller containers. Fewer switches per operation, same circuits-fire-simultaneously principle, faster results.</p><p>The hardware caught up to the optimization. That’s the trend in AI inference right now: we figured out that most model weights don’t need 16-bit parking spaces, so NVIDIA is building parking lots with smaller spots.</p><h3>The mental model I wish I had from the start</h3><p>Here’s how I now think about all of this:</p><ol><li><strong>A bit is a physical switch.</strong> ON or OFF. That’s the atom of computing.</li><li><strong>Fixed-width containers exist because hardware circuits are etched in silicon.</strong> They can’t resize per operation. A 16-bit adder always processes 16 bits, whether the numbers are small or large.</li><li><strong>Variable-width saves space but kills speed.</strong> Great for storage (files, network), terrible for computation (CPU, GPU). Everything gets unpacked to fixed-width before math happens.</li><li><strong>Choosing a container size is choosing a tradeoff:</strong><br>Bigger container = more precision, more range, more memory. <br>Smaller container = less memory, less precision, potential quality loss.</li><li><strong>Quantization is literally choosing smaller parking spots.</strong> 32-bit -&gt; 16-bit -&gt; 8-bit -&gt; 4-bit. Every step halves the memory. Every step loses some precision. The entire field of quantization research is about making those smaller spots lose as little quality as possible.</li></ol><p>That last point is what made all the quantization papers (GPTQ, AWQ, SmoothQuant) suddenly make sense. They’re not doing magic. They’re figuring out clever ways to round 65,536 possible values into 16 possible values while losing the least important information.</p><h3>The takeaway</h3><p>I spent years using integers, floats, and data types without understanding what’s physically happening. “It’s 8 bits” was just a fact I memorized.</p><p>But once you see the light switches, the fixed-width circuits, and the reason variable-width doesn’t work for computation — everything else builds on top of it cleanly. GPU memory, quantization, KV cache sizing, VRAM budgeting, why FP8 on H100 is faster than “fake FP8” via dequantization on T4 — it all traces back to switches on silicon and the circuits wired between them.</p><p>Sometimes the most basic question — “but why are there extra zeros?” — is the one worth chasing.</p><p><em>I’m currently deep in the weeds of AI inference optimization — GPU memory hierarchies, quantization methods, serving systems, the whole stack. If this kind of low-level explainer helped you, I’ll write more as I learn. Connect with me on </em><a href="https://www.linkedin.com/in/varuntej07/"><em>LinkedIn</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e1661f5e69b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Managed to Build an iOS App from Windows Using Codemagic]]></title>
            <link>https://medium.com/@varuntej07/how-i-managed-to-build-an-ios-app-from-windows-using-codemagic-ff2f92d66580?source=rss-ce1906f9f6e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff2f92d66580</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Varuntej]]></dc:creator>
            <pubDate>Fri, 12 Dec 2025 20:27:21 GMT</pubDate>
            <atom:updated>2025-12-12T20:27:21.736Z</atom:updated>
            <content:encoded><![CDATA[<p>I don’t own a Mac. I don’t own an iPhone. Yet I just published an iOS app to the App Store. Here’s how.</p><h3>The Problem</h3><p>I’m building <strong>Ooink AI Assistant</strong> — a voice-enabled chatbot for a ramen restaurant. The client planned to deploy it on an iPad as a kiosk. Since I am proficient in Flutter and the project is relatively lightweigh — essentially a conversational bot answering menu queries. So, Flutter was the obvious choice.</p><p>But while flutter handles the code beautifully, the hardware reality hit hard. Apple demands you build on macOS with Xcode. MMy daily driver is a Windows laptop. Of course, buying or renting a Mac for one freelance project wasn’t happening.</p><h3>Enter Codemagic</h3><p>Codemagic is a CI/CD platform that gives you access to macOS build machines in the cloud. You push code to GitHub, integrate with Codemagic, then watch it build on a Mac Mini M2 instance on their cloud, and uploads directly to App Store Connect.</p><p>No Mac required. No Xcode installed locally. Just a codemagic.yaml file in your repo.</p><h3>The codemagic.yaml Breakdown</h3><p>Here’s the configuration that got my Flutter app from a Windows machine to TestFlight:</p><pre>workflows:<br>  ios-release:<br>    name: iOS Release<br>    max_build_duration: 60<br>    instance_type: mac_mini_m2<br>    integrations:<br>      # exact ref name you gave your key in Codemagic and appstoreconnect <br>      app_store_connect: codemagic <br>    environment:<br>      groups:<br>        # Define key id, issuer id, private key (.p8) file<br>        # Generated at https://appstoreconnect.apple.com/access/integrations/api<br>        # and stored in Codemagic&#39; env variables tab all under same group name<br>        - appstore_credentials<br>      flutter: stable<br>      xcode: latest<br>      cocoapods: default<br>      vars:<br>        BUNDLE_ID: &quot;com.ooinkramen.ai&quot;  # same bundleid from appstore<br>    scripts:<br>      - name: Fetch signing files from App Store Connect<br>        # Uses the private key (from env) to fetch or create the matching certificate from Apple<br>        script: |<br>          app-store-connect fetch-signing-files &quot;$BUNDLE_ID&quot; \<br>            --type IOS_APP_STORE \<br>            --create \<br>            --certificate-key=@env:CERTIFICATE_PRIVATE_KEY<br>      - name: Set up keychain<br>        script: |<br>          keychain initialize<br>      - name: Add certificates to keychain<br>        script: |<br>          keychain add-certificates<br>      - name: Configure Xcode signing<br>        script: |<br>          xcode-project use-profiles<br>      - name: Get Flutter packages<br>        script: |<br>          flutter pub get<br>      - name: Set iOS deployment target<br>        # Fixes common build errors where plugins default to older, unsupported iOS versions.<br>        script: |<br>          find . -name &quot;Podfile&quot; -exec sed -i &#39;&#39; &quot;s/^# platform :ios, &#39;.*&#39;/platform :ios, &#39;15.0&#39;/&quot; {} \;<br>          find . -name &quot;Podfile&quot; -exec sed -i &#39;&#39; &quot;s/^platform :ios, &#39;.*&#39;/platform :ios, &#39;15.0&#39;/&quot; {} \;<br>      - name: Install CocoaPods dependencies<br>        script: |<br>          cd ios &amp;&amp; pod install<br>      - name: Build iOS app ipa for release<br>        # Builds the .ipa using the export options generated by the fetch-signing-files step<br>        script: |<br>          flutter build ipa --release \<br>            --export-options-plist=/Users/builder/export_options.plist<br>    artifacts:<br>      - build/ios/ipa/*.ipa<br>    publishing:<br>      app_store_connect:<br>        auth: integration<br>        submit_to_testflight: true</pre><h3>What Each Section Does</h3><p><strong>instance_type: mac_mini_m2</strong> is the build machine. Codemagic spins up a Mac Mini M2 in the cloud. You’re renting Apple hardware without owning it</p><p><strong>integrations: app_store_connect</strong> — Links to App Store Connect API credentials you&#39;ve set up in Codemagic&#39;s UI. This is how the build machine authenticates with Apple to upload the build.</p><p><strong>environment.groups: appstore_credentials</strong> holds your secrets. It contains the App Store Connect API keys, but most importantly, it holds the <strong>CERTIFICATE_PRIVATE_KEY</strong>.</p><blockquote>Note<em>: Since I’m on Windows, I generated this private key manually using OpenSSL in Git Bash (</em><strong>openssl genrsa -out cert_key.pem 2048</strong><em>) and pasted the content here. This is the &quot;secret&quot; half of the signing certificate.</em>.</blockquote><p><strong>fetch-signing-files</strong>- This is where the magic happens. Codemagic uses the CERTIFICATE_PRIVATE_KEY (from my environment variables) to generate a signing certificate on the Apple Developer Portal. It then downloads the matching Provisioning Profile. Basically, it combines the <strong>Private Key</strong> I made on Windows with the <strong>Public Certificate</strong> from Apple to create a valid identity for signing the app.</p><p><strong>keychain initialize / </strong><strong>add-certificates</strong>- Sets up the macOS keychain on the build machine and imports the certificates. Standard code signing ritual, automated.</p><p><strong>xcode-project use-profiles</strong>- Configures your Xcode project to use the fetched provisioning profiles. Updates project.pbxproj automatically so you don’t have to open Xcode</p><p><strong>flutter build ipa --release</strong>- Builds the release IPA. The --export-options-plist points to Codemagic&#39;s generated export options.</p><p><strong>submit_to_testflight: true</strong>- After a successful build, the IPA uploads directly to TestFlight. You don&#39;t touch App Store Connect manually.</p><h3>Setting Up App Store Connect API Key</h3><p>Before Codemagic can talk to Apple, you need an API key:</p><ol><li>Go to App Store Connect → Users and Access → Integrations → App Store Connect API</li><li>Generate a new key with “Admin” or “App Manager” role</li><li>Download the .p8 file (you only get one chance)</li><li>Note the Key ID and Issuer ID</li></ol><p>In Codemagic:</p><ol><li>Go to Teams → Integrations → App Store Connect</li><li>Add the API key details</li><li>Name it (this name goes in integrations.app_store_connect in your yaml)</li></ol><h3>The Build Number Trap</h3><p>Apple rejects duplicate build numbers. Each upload needs a unique identifier. If you find a bug in your TestFlight build and want to push a fix, you cannot just rebuild, you must increment the version code first.</p><p>In pubspec.yaml update the version:</p><pre>version: 1.0.0+2</pre><p>The +2 is the build number. Increment it before every push. Or automate it:</p><pre>- name: Build with auto-incrementing build number<br>  script: |<br>    BUILD_NUMBER=$(($(date +%s)/60))<br>    flutter build ipa --build-number=$BUILD_NUMBER --release \<br>      --export-options-plist=/Users/builder/export_options.plist</pre><h3>Final Thoughts</h3><p>Codemagic works. I built, signed, and published an iOS app from Windows without ever touching a Mac or iPhone. The codemagic.yaml configuration handles certificates, provisioning profiles, and TestFlight uploads automatically.</p><p>The app is on TestFlight. The client is happy. I’m still on Windows.</p><p>If you’re building Flutter apps and want to avoid the “Mac tax,” this is the way.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff2f92d66580" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I built my AI clone that talks like me (Ollama + ChromaDB, Local & Real-Time)]]></title>
            <link>https://medium.com/@varuntej07/how-i-built-my-ai-clone-that-talks-like-me-ollama-chromadb-local-real-time-bb4d20020d8b?source=rss-ce1906f9f6e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb4d20020d8b</guid>
            <category><![CDATA[ai-chatbot]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[ai-clone]]></category>
            <category><![CDATA[ollama]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Varuntej]]></dc:creator>
            <pubDate>Thu, 21 Aug 2025 17:59:30 GMT</pubDate>
            <atom:updated>2025-08-21T17:59:30.669Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A step-by-step guide to creating a local, private AI assistant that understands my notes, projects, and personal style: an AI that talks better than I know myself.</em></p><p>I’ve always wanted an AI that could talk for me. Not the generic chatbots that give cookie-cutter responses, but something that actually <em>knows</em> me, my projects, my notes, my way of thinking. The catch? I wanted it completely private. No cloud APIs, no data leaving my machine, no monthly subscriptions. Just me, my computer, and an AI that gets smarter <em>about me</em> every day.</p><p>After days of tinkering, I built exactly that. Here’s the story of how it came together, what I learned, and why it changed how I think about personal AI. I used <strong>Ollama</strong> (for running an LLM locally) and <strong>ChromaDB</strong> (a simple vector database to store and search my files). The trick is using <a href="https://cloud.google.com/use-cases/retrieval-augmented-generation?hl=en"><strong>RAG </strong></a><strong>(Retrieval Augmented Generation),</strong> think of it like open-book exams: Instead of forcing the model to memorize everything, I let it ‘look up’ the right notes (relevant chunks) from my personal files, pass them into the model as context, and let it generate a grounded answer.</p><p>This blog post is a step-by-step breakdown of how I made it. If you’ve ever wanted your own AI agent talks like you and answer any question about you or your project<strong>, </strong>this guide is for you. The workflow is simple:</p><ol><li>Ingest personal files (for knowledge)</li><li>Chunk and embed them into vectors</li><li>Store embeddings in ChromaDB (persisted locally)</li><li>Retrieve top-k chunks for a question</li><li>Call Ollama with context and return an answer</li></ol><h3>Step 1. The Workflow</h3><p>I needed three things:</p><ul><li>A way to <strong>run a model locally</strong> -&gt; I picked <strong>Ollama</strong>, because it solved the “PhD in machine learning required” problem. One command gets you a working language model: ollama pull llama3.2:3b-instruct. No CUDA configuration, no memory management headaches, no Python environment conflicts.</li><li>For understanding meaning (of the data we feed), Embeddings turn text into numerical coordinates in a ‘meaning space’. Sentences about the same idea end up near each other, even if they use different words. I used <strong>MiniLM embeddings</strong> (via sentence-transformers) because they’re small, fast, and accurate to run instantly.</li><li>A way to <strong>store and search my files semantically, ChromaDB </strong>became my vector database. It’s like a search engine, but instead of matching keywords, it matches <em>meaning</em>. When I ask ‘project deadlines,’ it finds documents mentioning ‘sprint timeline’ or ‘delivery dates’ automatically.</li></ul><p>The beauty of this stack? Everything runs locally. No internet required after initial setup.</p><h3>Step 2. Setting Up Ollama</h3><p>The first thing I did was download and install <a href="https://ollama.com/">Ollama</a>. Once it was ready, I tested it by pulling the model</p><pre>ollama pull llama3.2:3b-instruct-q4_K_M<br>ollama run llama3.2:3b-instruct-q4_K_M</pre><p>The <strong><em>q4_K_M</em></strong><em> </em>variant is a quantized version which is smaller and faster while still decent quality, which matters when running locally. When I saw the model reply in my terminal, I knew Ollama was working fine. That gave me confidence to build the rest on top of it.</p><h3>Step 3. Turning Files Into Searchable Memory</h3><pre>varun-clone/<br>├── data/raw/          # data about me go here<br>├── scripts/<br>│   ├── ingest.py      # Turns chaos into searchable memory<br>│   └── server.py      # The brain that answers questions  <br>├── storage/           # ChromaDB lives here<br>└── app.py             # The friendly chat interface</pre><p>The raw idea is simple: I needed to turn my messy folder of PDFs, markdown notes, and HTML into structured, searchable memory and let the system understand them. That’s where embeddings and chunking come in. The first real breakthrough came when I figured out chunking. Here’s the problem: AI models have attention limits. Feed them a 50-page document, and they lose track of details. But if you split documents too aggressively, you lose context.</p><p>My solution was overlapping chunks, like shingles on a roof:</p><pre>CHUNK_SIZE = 800<br>CHUNK_OVERLAP = 120<br><br>def chunk_text(text: str, size: int = CHUNK_SIZE, overlap: int = CHUNK_OVERLAP) -&gt; list[str]:<br>    &quot;&quot;&quot;Split text into overlapping chunks that preserve context&quot;&quot;&quot;<br>    text = &quot; &quot;.join(text.split())  # Clean whitespace<br>    chunks, i = [], 0<br>    while i &lt; len(text):<br>        chunks.append(text[i:i+size])<br>        i += max(size - overlap, 1)  # Overlap prevents context loss<br>    return chunks</pre><p>The magic numbers (800 characters not tokens, with 120 characters overlapping) came from experimentation. Too small, and chunks lose meaning. Too large, and the model gets overwhelmed. This balance lets me maintain context while keeping chunks digestible.</p><p>For embeddings, I wrapped the sentence-transformers model in a clean interface:</p><pre>EMBED_MODEL_NAME = &quot;all-MiniLM-L6-v2&quot;<br><br>class MiniLMEmbeddingFunction(embedding_functions.EmbeddingFunction):<br>    def __init__(self, model_name: str = EMBED_MODEL_NAME):<br>        self.model = embedding_functions.SentenceTransformerEmbeddingFunction(model_name)<br>    <br>    def __call__(self, texts: list[str]) -&gt; list[list[float]]:<br>        return self.model(texts)</pre><p>Running python scripts/ingest.py once transformed my chaotic data/raw folder into a searchable knowledge base. PDFs, markdown files, text documents etc., all became vectors in my personal search engine - <strong>ChromaDB</strong> collection lives in storage/chroma, which stores those vectors and lets me search them by meaning, not just keywords.</p><h3>Step 4. The Brain: Connecting Retrieval to Generation</h3><p>The server became the heart of the system. When you ask a question, here’s the dance that happens:</p><ol><li><strong>Semantic Search</strong>: Your question gets converted to a vector, then ChromaDB finds the most similar document chunks</li><li><strong>Context Assembly</strong>: The top matches become context for the language model</li><li><strong>Prompt Engineering</strong>: Everything gets packaged into a carefully crafted prompt</li><li><strong>Local Generation</strong>: Ollama generates an answer grounded in your actual documents</li></ol><pre>LLM_MODEL = &quot;llama3.2:3b-instruct-q4_K_M&quot;<br>TOP_K = 4<br>MAX_OUT = 400<br><br>def retrieve_context(query: str) -&gt; list[str]:<br>    &quot;&quot;&quot;Find the most relevant chunks for a question&quot;&quot;&quot;<br>    client = chromadb.PersistentClient(path=&quot;storage/chroma&quot;)<br>    collection = client.get_collection(&quot;varun_kb&quot;)<br>    results = collection.query(query_texts=[query], n_results=TOP_K)<br>    return (results.get(&quot;documents&quot;) or [[]])[0]<br><br>@app.post(&quot;/ask&quot;)<br>def ask():<br>    query = request.get_json().get(&quot;query&quot;, &quot;&quot;).strip()<br>   <br>    # Get relevant context from my documents<br>    context_chunks = retrieve_context(query)<br><br>    prompt = f&quot;&quot;&quot;You are Varun&#39;s personal agent...<br>    User question: {query}<br>    Relevant context from Varun&#39;s files:<br>    {chr(10).join(context_chunks)}<br>    Answer naturally, as if you know Varun personally. If the context doesn&#39;t contain relevant information, politely throw a joke and divert the topic.<br>    &quot;&quot;&quot;<br><br>    response = ollama.chat(      # Ollama&#39; magic<br>        model=LLM_MODEL,<br>        messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt}],<br>        stream=False,<br>        options={&quot;temperature&quot;: 0.7, &quot;num_predict&quot;: MAX_OUT},<br>    )<br><br>    return jsonify({&quot;answer&quot;: response[&quot;message&quot;][&quot;content&quot;].strip()})</pre><p>This was the point where the pieces clicked together, I could post a question to /ask and see my own notes being pulled in as context.</p><h3>Step 5. Making It Feel Like a Chat</h3><p>The final step was to polish by adding a small Streamlit interface that made the whole system feel like a conversation rather than an API call:</p><ul><li>A textbox to type a question.</li><li>A button to send it to my Flask backend.</li><li>Two neat sections: the answer, and the snippets of context pulled from my files.</li></ul><p>Running it gave me a chat-like interface where the agent really felt like I was “talking for me.”</p><h3>The Complete Workflow in Action</h3><p>Here’s what actually happens when I use it now:</p><ul><li><strong>Ingest</strong> -&gt; Whenever I add new content, like an updated resume, fresh website copy, or social media exports, I just dump all the files into data/raw/.</li><li><strong>Process</strong> -&gt; Run python scripts/ingest.py to transform those files into embeddings stored in ChromaDB.</li><li><strong>Chat</strong> -&gt; Launch the interface with streamlit run app.py and ask questions like: <em>“How do I usually describe my technical skills?”, “What’s my professional background summary?”</em></li><li><strong>Retrieve &amp; Augment</strong> -&gt; The backend pulls the most relevant chunks from Chroma, adds them as context, and crafts a prompt.</li><li><strong>Generate</strong> -&gt; Ollama produces an answer grounded in those exact chunks.</li></ul><p>That’s Retrieval Augmented Generation in practice: <strong>Retrieve &gt; Augment &gt; Generate. </strong>The system has become my personal brand assistant, not replacing my self-knowledge, but organizing it in ways I never could manually. It remembers how I phrase things across platforms, connects themes in my content, and helps me maintain consistency in how I present myself.</p><p>What started as a random shower thought turned into a personal AI clone. Now it sits on my website, answering questions about me as if I were there, even when I am not. No salary, no sleep, no excuses. Just me on tap 24/7. Honestly, it feels both scary and amazing. If that’s not a win, I don’t know what is.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb4d20020d8b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>