<?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 sulav shrestha on Medium]]></title>
        <description><![CDATA[Stories by sulav shrestha on Medium]]></description>
        <link>https://medium.com/@sulavstha007?source=rss-1190d2c7f065------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*spkpd2gnZCWf5W2f</url>
            <title>Stories by sulav shrestha on Medium</title>
            <link>https://medium.com/@sulavstha007?source=rss-1190d2c7f065------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 06:02:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sulavstha007/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[How GPU Temperature Affects LLM Inference Performance]]></title>
            <link>https://medium.com/@sulavstha007/how-gpu-temperature-affects-llm-inference-performance-82c5beeaf43a?source=rss-1190d2c7f065------2</link>
            <guid isPermaLink="false">https://medium.com/p/82c5beeaf43a</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[sulav shrestha]]></dc:creator>
            <pubDate>Mon, 02 Nov 2026 17:42:55 GMT</pubDate>
            <atom:updated>2026-11-02T17:42:55.097Z</atom:updated>
            <content:encoded><![CDATA[<p>I was preparing to implement KV caching in <a href="https://huggingface.co/Majipa/axiom">Axiom</a>, my small language model.</p><p>Before changing the inference code, I needed a baseline. Same prompt, same model, generate some tokens, measure the time.</p><p>Initially, generating 512 tokens took around <strong>2.77 seconds</strong>.</p><p>Then I kept running it.</p><p>3.06 seconds.<br>3.49 seconds.<br>Eventually, <strong>4.04 seconds</strong>.</p><p>I had not changed the model or generation settings. So why was the same work taking longer?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*is0sORxhvc9EQDgebTZATg.png" /></figure><h3>What I was measuring</h3><p>My setup was <strong>Axiom v2</strong>, with a <strong>2,048-token context window</strong>, running on a <strong>GTX 1650 with 4GB VRAM</strong>.</p><p>I used batch size one, a three-token prompt, greedy decoding, and disabled gradients. No KV cache.</p><p>Each test started from the original prompt and generated <strong>512 new tokens</strong>. The context grew during generation, but that growth happened the same way in every repeated test.</p><p>Before timing, I ran <strong>five full warmup generations</strong> to get past first-use overhead. I also synchronized CUDA before and after the timed generation so the timer waited for completed GPU work.</p><p>Across one sequence of 20 runs:</p><ul><li><strong>Fastest:</strong> 2.7711 seconds — <strong>184.76 tokens/sec</strong>.</li><li><strong>Slowest:</strong> 4.0377 seconds — <strong>126.81 tokens/sec</strong>.</li></ul><p>That is <strong>45.7% more generation time</strong>, or a <strong>31.4% drop in throughput</strong>.</p><p>The percentages differ because throughput is tokens divided by time. They describe the same change using different denominators.</p><h3>Then I checked the GPU</h3><p>I opened another terminal and monitored temperature, clock speed, power draw, and utilization through <strong>nvidia-smi</strong>.</p><pre>nvidia-smi --query-gpu=temperature.gpu,clocks.sm,power.draw,utilization.gpu --format=csv -l 1<br>temperature.gpu, clocks.current.sm [MHz], power.draw [W], utilization.gpu [%]</pre><p>Separately logged cooler tests repeatedly finished near <strong>2.77–2.80 seconds</strong>. Later logs spent much more time around <strong>84–87°C</strong>, with some active clock readings dropping toward <strong>1,200 MHz</strong>.</p><p>Comparing the first and last <strong>60 active samples</strong> showed:</p><ul><li><strong>Mean temperature:</strong> 79.52°C → 85.30°C.</li><li><strong>Mean clock:</strong> 1,733 → 1,535 MHz — down <strong>11.4%</strong>.</li><li><strong>Mean power draw:</strong> 44.28 → 36.49 W — down <strong>17.6%</strong>.</li></ul><p>I classified samples with reported utilization of at least 20% as active.</p><p>GPUs dynamically adjust their clocks according to operating conditions. When thermal limits are approached, clocks can be reduced to control heat. Lower clocks can increase the time required for the same computation. Power constraints can also reduce clocks.</p><p>My measurements were consistent with thermal constraints contributing to the slowdown. However, those averages were <strong>early-versus-late telemetry samples</strong>, not readings paired with the fastest and slowest runs. Without timestamp alignment and recorded clock event reasons, I could not confirm the exact contribution of throttling.</p><h3>My warmups were also heating the laptop</h3><p>Five warmups plus one timed generation meant:</p><p><strong>6 × 512 = 3,072 generated tokens per invocation.</strong></p><p>Only the final 512 tokens appeared in the elapsed time.</p><p>The GPU still did the other five generations — and produced heat throughout them.</p><p>Warmup was useful for avoiding first-use overhead. Repeating the entire process also changed the machine’s thermal conditions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*AMtvvo1M15Pu4RmEY_3pkA.png" /></figure><h3>The correlation graph nearly fooled me</h3><p>Across all <strong>316 telemetry samples</strong>, temperature and clock speed had a <strong>positive correlation of +0.43</strong>.</p><p>After filtering for active samples, it became <strong>−0.31</strong>.</p><p>The direction flipped.</p><p>Idle periods often had both lower clocks and lower temperatures. Mixing them with active work changed the apparent relationship.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*hZyEZhGhIO-r2Z2k8VhtWA.png" /></figure><p>That taught me to check which operating states I was comparing before interpreting a correlation.</p><p>Utilization needed similar care. <strong>90% GPU utilization does not mean 90% of peak computing performance.</strong> It describes the fraction of the sampling period with kernels executing. A GPU can remain busy while running at reduced clocks.</p><h3>What changes for my next experiment</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8h4Lw7xDEk--q9RfOzceiA.png" /><figcaption>This image was generate by AI cuz I don’t have this good viz skills.😆</figcaption></figure><p>For the KV-cache comparison, I will timestamp telemetry, mark the timed intervals, and compare repeated measurements under similar operating conditions.</p><p>I also want to report sustained performance alongside cooler-machine results.</p><p>Otherwise, I could give one implementation a cooler GPU and mistake the difference for a software speedup.</p><p>I started with a timer around my generation loop.</p><p>Now, temperature and clock readings belong in the benchmark too.</p><p>Hugging face model: <a href="https://huggingface.co/Majipa/axiom">https://huggingface.co/Majipa/axiom</a></p><p>Github: <a href="https://github.com/majipa007/axiom-inference-lab">https://github.com/majipa007/axiom-inference-lab</a> ( note: the github is new and doesn’t even have a proper readme cuz I am just starting with the KV cache implementation in this new repo. )</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82c5beeaf43a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[60,000 Training Steps, a Loss Plateau, and a Simple Fix]]></title>
            <link>https://medium.com/@sulavstha007/60-000-training-steps-a-loss-plateau-and-a-simple-fix-cf9aba7fe0a9?source=rss-1190d2c7f065------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf9aba7fe0a9</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[sulav shrestha]]></dc:creator>
            <pubDate>Sat, 31 Oct 2026 17:36:47 GMT</pubDate>
            <atom:updated>2026-10-31T17:36:47.211Z</atom:updated>
            <content:encoded><![CDATA[<p>So, in the previous blog, I finally finished building my Transformer.</p><p>Four attention heads. Four Transformer blocks. Token embeddings, positional embeddings, LayerNorm, residual connections, MLP, the whole thing.</p><p>Around 7.55 million parameters.</p><p>Everything was connected. The tensor dimensions matched. Gradients were flowing.</p><p><strong>I had built a language model.</strong></p><p>Well, technically.</p><p>Because at that point, it was just a bunch of randomly initialized weights.</p><p>It couldn’t write a story. It couldn’t predict anything useful.</p><p>Basically, it was stupid.</p><p>And now I had to make it slightly less stupid.</p><h3>Training an LLM on a Potato</h3><p>My laptop has an NVIDIA GTX 1650 with 4GB VRAM.</p><p>Four.</p><p>Gigabytes.</p><p>Now, Axiom is a tiny model compared to today’s LLMs, so this wasn’t some impossible task.</p><p>But memory was still something I had to keep in mind.</p><p>I had already managed to exhaust my system RAM and swap during tokenization earlier in the project. Didn’t particularly want a repeat of that experience.</p><p>So I kept the model small.</p><pre>vocab_size = 8000<br>context_length = 128<br>d_model = 256<br>n_heads = 4<br>n_layers = 4<br>batch_size = 8</pre><p>The training pipeline was straightforward.</p><pre>TinyStories<br>    ↓<br>Custom BPE Tokenizer<br>    ↓<br>Token IDs<br>    ↓<br>Random Batches<br>    ↓<br>Axiom<br>    ↓<br>Predictions<br>    ↓<br>Cross-Entropy Loss<br>    ↓<br>Backpropagation<br>    ↓<br>AdamW<br>    ↓<br>Repeat</pre><p>I’d already spent enough time understanding forward passes.</p><p>Now I had to make the backward pass actually teach the model something.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*sJyFpl1lNYf5X4ZH1dKrkw.png" /></figure><h3>Making the Model Learn</h3><p>The training objective was next-token prediction.</p><p>Say we have:</p><pre>Input:   [10, 20, 30, 40]<br>Target:  [20, 30, 40, 50]</pre><p>For every position, the model predicts what token comes next.</p><p>Cross-entropy measures how wrong those predictions are.</p><p>Backpropagation calculates how the parameters contributed to that error.</p><p>AdamW updates them.</p><p>And we do this again. And again.And again.</p><p>The code isn’t the particularly interesting part here.</p><p>What mattered was finally understanding how all the components I’d built came together during learning.</p><p>Query, Key, and Value weren’t hand-designed rules.</p><p>The attention projections were learnable.</p><p>The embedding table was learnable.</p><p>The MLP weights were learnable.</p><p>All the parameters I’d initialized while building the Transformer were now being updated based on prediction errors.</p><p>That was pretty cool.</p><h3>First, the Loss Started Dropping</h3><p>I started training Axiom using AdamW and a learning rate of 3e-4.</p><p>Initially, the loss went down.</p><p>Which was good.</p><p>At least something was happening.</p><p>But watching a number decrease in the terminal doesn’t tell you everything.</p><p>I wanted to know whether the model had actually learned enough to produce text.</p><p>So I also implemented an autoregressive generator.</p><p>The model predicts a token, we sample it, append it to the sequence, and feed the updated sequence back into the model.</p><p>Repeat until generation stops.</p><p>I added temperature sampling and top-k sampling so generation wasn’t just picking the most likely token every single time.</p><p>And eventually…</p><p><strong>The thing started writing stories.</strong></p><p>One of the generated outputs included:</p><blockquote><em>The little girl was so happy and thanked the fairy for her help. She flew away.</em></blockquote><p>That was my model.</p><p>My little Transformer, trained on my laptop, producing an actual sentence that made sense.</p><p>Was it intelligent? No.</p><p>Was it writing groundbreaking literature? Absolutely not.</p><p>Did it sometimes repeat itself, restart stories, or produce weird characters?</p><p>Of course.</p><p>But it had learned enough structure from TinyStories to generate recognizable story-like text.</p><p>That’s a very different feeling from calling a model through an API.</p><p>I knew exactly what components were producing those tokens because I’d written them.</p><h3>50,000 Steps Later…</h3><p>I let Axiom train through a 50,000-step run, including an overnight session.</p><p>And by that point, something became obvious.</p><p>The loss wasn’t improving much anymore.</p><p>Training and validation loss were hovering around <strong>2.20</strong>, with fluctuations.</p><p>Now, to be clear, a fluctuating loss isn’t automatically a problem. Especially when validation is estimated using sampled batches.</p><p>But the broader trend had slowed.</p><p>The model was learning, but not making the kind of progress I was hoping for.</p><p>The first reaction is obvious.</p><p>Do I need a bigger model?</p><p>More layers?</p><p>More data?</p><p>Have I messed something up in the architecture?</p><p>But instead of changing everything, we looked at the training configuration.</p><p>And there was one thing I’d kept constant.</p><p><strong>The learning rate.</strong></p><h3>The Learning Rate Problem</h3><p>I’d been training with:</p><pre>learning_rate = 3e-4</pre><p>For the entire 50,000-step run.</p><p>Here’s the thing.</p><p>A learning rate controls the size of the optimizer’s parameter updates.</p><p>A larger learning rate can help make faster progress early in training.</p><p>But later, when the model is already in a better region of the loss landscape, smaller updates may help it settle into a better solution.</p><p>That doesn’t mean a constant learning rate can never work.</p><p>It just means my current training run had reached a point where reducing it was worth trying.</p><p>So instead of starting over, I resumed the checkpoint and lowered it.</p><pre>Steps 0–50,000<br>Learning rate: 3e-4<br>Validation loss: ~2.20</pre><pre>Steps 50,000–55,000<br>Learning rate: 1e-4<br>Validation loss: ~2.10</pre><pre>Steps 55,000–60,000<br>Learning rate: 3e-5<br>Validation loss: ~2.09</pre><p>And the loss improved.</p><p>Not by some ridiculous amount.</p><p>But enough to show that the model still had room to improve under a different optimization setting.</p><p>That was an important lesson.</p><p><strong>Sometimes the next improvement isn’t another layer of attention. It’s changing how you train the model you already have.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/889/0*TJftHsBPRSfynGk0.jpg" /></figure><h3>The Numbers Weren’t Always Consistent</h3><p>Another thing I ran into was validation loss fluctuation.</p><p>At different points, I saw readings around 2.0175, 2.02, and 2.09.</p><p>And naturally, I wondered why I couldn’t just use the lowest number.</p><p>But my validation procedure used sampled batches.</p><p>Different samples can produce different results.</p><p>So taking the single lowest reading would make the model look better than a typical evaluation supports.</p><p>That’s why I settled on reporting an <strong>approximate validation loss of 2.09</strong> for Axiom v1.</p><p>Not a standardized benchmark.</p><p>Not a carefully controlled comparison against other models.</p><p>Just an honest measurement from my training setup.</p><p>And that distinction matters, especially if I’m going to use this model for research experiments.</p><p>Because if I want to compare a future optimization against Axiom v1, I need to know what my baseline actually means.</p><h3>The Final 60,000-Step Model</h3><p>Eventually, I reached 60,000 training steps.</p><p>I now had a model that could generate TinyStories-style text.</p><p>A custom tokenizer.</p><p>A complete Transformer implementation.</p><p>A training pipeline with checkpointing and resumption.</p><p>And a working inference system.</p><p>But there was one more thing I wanted to do.</p><p>Make the model usable outside my training environment.</p><p>I’d been working with PyTorch checkpoints during development, but I wanted a cleaner way to package the final trained model.</p><p>So I exported the weights to Safetensors, saved the architecture configuration, and bundled the tokenizer.</p><pre>model.safetensors<br>config.json<br>tinystories_tokenizer.model</pre><p>I also made sure the model could be loaded for inference independently of the training checkpoint.</p><p>Then I published the result on Hugging Face.</p><p><a href="https://huggingface.co/Majipa/axiom"><strong>Axiom v1 — Hugging Face</strong></a></p><p>That was it.</p><p>My first language model, built from scratch, trained, and publicly available.</p><h3>So, Was It Worth It?</h3><p>Absolutely.</p><p>But not because I now have a 7.55-million-parameter model that can write tiny stories.</p><p>There are countless existing models that can do much more.</p><p>I built Axiom because I wanted to understand how these things work internally.</p><p>And now I can open my own code and follow a token through the entire process.</p><p>From an integer ID.</p><p>To an embedding vector.</p><p>Through Query, Key, and Value projections.</p><p>Through attention heads and Transformer blocks.</p><p>To vocabulary logits.</p><p>To loss, gradients, parameter updates, and eventually generated text.</p><p>I also learned a few things the hard way.</p><p>A working implementation isn’t necessarily a correct one.</p><p>A decreasing training loss doesn’t automatically mean good generalization.</p><p>One validation reading isn’t the whole story.</p><p>And throwing more training steps at a plateau isn’t always the smartest solution.</p><p>The biggest difference is that I now have a baseline I can actually experiment with.</p><h3>What’s Next?</h3><p>I’m not planning to spend the next few weeks building another identical Transformer just with more parameters.</p><p>That wasn’t the goal.</p><p>I wanted to understand the fundamentals well enough to start exploring research papers and implementing ideas myself.</p><p>Now I can.</p><p>I’m particularly interested in inference optimization, attention mechanisms, and getting more out of limited hardware.</p><p>The first thing I want to explore is <strong>KV caching</strong>.</p><p>Right now, my autoregressive generator recomputes attention over the available context every time it generates a new token.</p><p>That works, but it’s wasteful.</p><p>KV caching would let me reuse previously computed Keys and Values rather than recomputing them at every generation step.</p><p>Same model weights.</p><p>Different inference implementation.</p><p>And an actual performance comparison to run.</p><p>But that’s for another blog.</p><p>For now, Axiom v1 is done.</p><p>60,000 steps.</p><p>4GB VRAM.</p><p>A lot of confused moments, debugging, and learning.</p><p>And one tiny language model that can finally write its own stories.</p><p><strong>Not bad for a project that started with me trying to understand what </strong><strong>[B, T, C] meant.</strong></p><p><strong>Model:</strong> <a href="https://huggingface.co/Majipa/axiom">Axiom on Hugging Face</a></p><p><em>Built with PyTorch, TinyStories, Neovim, and an unreasonable amount of curiosity.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf9aba7fe0a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Stopped Watching Tutorials and Built a Transformer]]></title>
            <link>https://medium.com/@sulavstha007/i-stopped-watching-tutorials-and-built-a-transformer-5abbcfbfcc44?source=rss-1190d2c7f065------2</link>
            <guid isPermaLink="false">https://medium.com/p/5abbcfbfcc44</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[transformers]]></category>
            <dc:creator><![CDATA[sulav shrestha]]></dc:creator>
            <pubDate>Mon, 26 Oct 2026 15:46:19 GMT</pubDate>
            <atom:updated>2026-10-26T15:46:19.845Z</atom:updated>
            <content:encoded><![CDATA[<p>So, in my last blog, I started building my own language model.</p><p>Got the dataset, messed around with tokenization, nearly murdered my laptop’s RAM, and somehow made it to batching.</p><p>Now came the interesting part.</p><p><strong>Actually building the model.</strong></p><p>I thought I’d watch Andrej Karpathy explain the Transformer, understand everything, and then write the code.</p><p>Yeah, about that.</p><h3>The Tutorial Trap</h3><p>I started watching Karpathy’s GPT video, and man, there was a lot going on.</p><p>One minute we were dealing with embeddings. Next came matrix multiplication, attention heads, masking, normalization, residual connections…</p><p>And somewhere in between, my brain stopped processing information.<br>Then I discovered his <em>makemore</em> series.<br>Four more videos. Almost eight hours of content.<br>I genuinely considered watching all of them before touching the code.<br>But then I realized I was getting dangerously close to <a href="https://grokipedia.com/page/Tutorial_hell#:~:text=References-,Tutorial%20hell,-Fact%2Dchecked%20by">tutorial hell</a>.<br>I’d already spent enough time learning <em>about</em> building an LLM.</p><p><strong>It was time to build the damn thing.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/0*8dhAY5bUNobTn1WZ.jpg" /></figure><h3>B, T, C. What the Hell?</h3><p>The first thing I kept encountering was this:</p><p>[B, T, C]</p><p>Everywhere.</p><p>Eventually, I understood:</p><ul><li>B = Batch size</li><li>T = Number of tokens in a sequence</li><li>C = Embedding dimension</li></ul><p>My batching pipeline was already producing [B, T].<br>But those were just token IDs. Integers. <br>A neural network needs useful vector representations, not just arbitrary identifiers.</p><p>So I added:</p><pre>self.token_embedding = nn.Embedding(vocab_size, d_model)<br>self.position_embedding = nn.Embedding(context_length, d_model)</pre><p>And suddenly:</p><pre>Token IDs           [B, T]<br>                       ↓<br>Token Embeddings    [B, T, C]<br>                       +<br>Position Embeddings [T, C]<br>                       ↓<br>                    [B, T, C]</pre><p>BTC finally made sense.<br>One mystery down.<br>Unfortunately, that was the easy part.</p><h3>Query, Key, Value. Especially Value.</h3><p>Next came self-attention.</p><p>I’d heard about attention countless times. I’d worked with LLMs, used them in applications, and knew Transformers relied on it.</p><p>But knowing that attention exists and understanding what it actually does are two very different things.</p><p>I started with three linear layers.</p><pre>self.query = nn.Linear(d_model, head_size, bias=False)<br>self.key = nn.Linear(d_model, head_size, bias=False)<br>self.value = nn.Linear(d_model, head_size, bias=False)</pre><p>Simple enough. Except I didn’t really understand what was happening.</p><p>Query — what a token is looking for.<br>Key — what a token can be matched against.<br>And Value?</p><p><strong>I genuinely couldn’t wrap my head around Value.</strong></p><p>If Query and Key are already comparing tokens, what exactly is Value doing?<br>The explanation that finally helped was thinking of Query and Key as a routing system.</p><p>Query asks where to look.<br>Key helps determine which positions are relevant.<br>Value is the information that actually gets collected.</p><p>That distinction was important.</p><p>Because the attention formula stopped looking like random matrix multiplication.</p><pre>Q @ Kᵀ<br>   ↓<br>Attention scores<br>   ↓<br>Scale<br>   ↓<br>Mask<br>   ↓<br>Softmax<br>   ↓<br>Attention weights @ V<br>   ↓<br>Output</pre><p>Q and K decide how much attention each position receives.<br>V supplies the information being combined.<br>And one more detail clicked: Q @ Kᵀ produces a [B, T, T] matrix.<br>That’s token-to-token attention.<br>Not [B, T, C].</p><p><strong>A matrix describing how positions relate to other positions.</strong></p><p>Okay. Now we were getting somewhere.</p><h3>The Model Must Not Cheat</h3><p>I was building a decoder-only Transformer.</p><p>Meaning each token can use what came before it, but not what comes after it. Without a causal mask, the model could look at future tokens during training. And that rather defeats next-token prediction.</p><p>So I created a lower-triangular mask.</p><pre>torch.tril(<br>    torch.ones(context_length, context_length, dtype=torch.bool)<br>)</pre><p>Conceptually:</p><pre>Token 1  Token 2  Token 3  Token 4</pre><pre>Token 1    ✓        ✗        ✗        ✗<br>Token 2    ✓        ✓        ✗        ✗<br>Token 3    ✓        ✓        ✓        ✗<br>Token 4    ✓        ✓        ✓        ✓</pre><p>Future positions get attention scores of negative infinity.</p><p>Softmax turns their probabilities into zero.</p><h3>The First Attention Head Actually Worked</h3><p>After enough debugging, I finally had the complete flow:</p><pre>scores = query @ key.transpose(-2, -1)<br>scaled_scores = scores / (self.head_size ** 0.5)</pre><pre>masked_scores = scaled_scores.masked_fill(<br>    ~mask,<br>    float(&quot;-inf&quot;)<br>)</pre><pre>attention_weights = torch.softmax(masked_scores, dim=-1)<br>output = attention_weights @ value</pre><p>But I didn’t want to declare victory just because Python stopped throwing errors.</p><p>So I checked the output dimensions.</p><p>Checked for non-finite values.</p><p>Checked that changing future tokens couldn’t affect earlier outputs.</p><p>Checked gradients for Query, Key, and Value.</p><p>And finally:</p><pre>Output shape: torch.Size([2, 4, 2])<br>All output values are finite<br>Future token cannot affect earlier tokens</pre><pre>query.weight: gradient OK<br>key.weight: gradient OK<br>value.weight: gradient OK</pre><pre>Single-head attention passed all checks</pre><p>That was satisfying.</p><p>Not because I’d written some extraordinary algorithm.</p><p>But because, for the first time, I could follow the whole operation and explain why each part existed.</p><p>I’d built causal self-attention.</p><p>And I understood what it was doing.</p><h3>Apparently We Need Four of Those</h3><p>Single-head attention was done.</p><p>Then came multi-head attention.</p><p>The idea was to give the model multiple sets of learned Q, K, and V projections so it could learn different attention patterns.</p><p>For Axiom:</p><pre>d_model = 256<br>n_heads = 4<br>head_size = 64</pre><p>Four attention heads, each producing a 64-dimensional output.</p><p>Concatenate them, and we’re back to 256 dimensions.</p><p>There was also a final learnable output projection.</p><p>At this point, the concepts were getting easier.</p><p>Not because the code had become magically simple, but because the tensor shapes had started making sense.</p><p>I could finally look at:</p><p>[B, T, 256] → [B, T, 64]</p><h3>The Rest of the Transformer</h3><p>After attention, I built the MLP.</p><pre>Linear: 256 → 1024<br>         ↓<br>        GELU<br>         ↓<br>Linear: 1024 → 256</pre><p>Then came LayerNorm and residual connections.</p><p>The Transformer block used pre-normalization:</p><pre>x = x + self.attention(self.ln1(x))<br>x = x + self.mlp(self.ln2(x))</pre><p>Attention lets tokens exchange information.</p><p>The MLP transforms each position’s representation.</p><p>LayerNorm helps stabilize the computations.</p><p>Residual connections let the original representation flow around those transformations.</p><p>Put them together, and you have a Transformer block.</p><p>Stack four of those.</p><p>Add final LayerNorm.</p><p>Add a language-model head that maps the 256-dimensional representation into 8,000 vocabulary scores.</p><p>And suddenly, I had this:</p><pre>Token IDs<br>   ↓<br>Token + Position Embeddings<br>   ↓<br>Transformer Block 1<br>   ↓<br>Transformer Block 2<br>   ↓<br>Transformer Block 3<br>   ↓<br>Transformer Block 4<br>   ↓<br>Final LayerNorm<br>   ↓<br>Language Model Head<br>   ↓<br>Vocabulary Logits</pre><p><strong>My own decoder-only Transformer.</strong></p><p>I checked the output shapes, gradients, and the full forward pass.</p><p>Everything connected.</p><h3>What Actually Changed?</h3><p>I started this project thinking I needed to understand every mathematical detail before writing code.</p><p>But that wasn’t working.</p><p>What worked was building one component at a time, getting confused, understanding what was wrong, and moving forward.</p><p>And I learned something else.</p><p>Using an LLM to help build an LLM is easy.</p><p>Getting an LLM to explain something until <em>you</em> understand it, then implementing it yourself, is a completely different exercise.</p><p>That was the point of Axiom.</p><p>Not to write the most impressive Transformer implementation.</p><p>But to stop treating these architectures like black boxes.</p><p>By the end of this, the model architecture was finished.</p><p>I had embeddings, attention, Transformer blocks, and vocabulary logits.</p><p>There was just one tiny problem.</p><p><strong>The model hadn’t learned anything yet.</strong></p><p>It had millions of randomly initialized parameters and absolutely no idea how to write a story.</p><p>So naturally, my next step was to train the thing on a laptop GPU with 4GB VRAM.</p><p>What could possibly go wrong?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5abbcfbfcc44" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building My Own LLM on an 8 GB RAM Laptop]]></title>
            <link>https://medium.com/@sulavstha007/building-my-own-llm-on-an-8-gb-ram-laptop-1e77b4a767ea?source=rss-1190d2c7f065------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e77b4a767ea</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[sulav shrestha]]></dc:creator>
            <pubDate>Mon, 14 Sep 2026 12:32:29 GMT</pubDate>
            <atom:updated>2026-09-14T12:32:29.878Z</atom:updated>
            <content:encoded><![CDATA[<p>It has been some time since I did a deep dive, so here I am, a challenger trying to train my own model.</p><p>With Andrej Karpathy as my passive, one-sided teacher and GPT as my active lecturer, this is me trying to train and run an LLM model on my system, which has an i5–9300H, 8 GB RAM, and a GTX 1650 with 4 GB VRAM (Acer Nitro 5).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/0*uG5s1MufFqevvnTk.jpg" /></figure><p>Now, this is a puny system, I know, but as they say, curiosity killed the cat. Let’s see what’s ahead.</p><p>So this is me starting my model training and running it on my own system. And this is basically a start so that I can start looking into research papers and implement them.</p><h4>I started this because:</h4><ul><li>I wanted my lost Python skills back (too much AI offloading, I know learning these may be pointless, but let’s see).</li><li>I want to go deeper and understand what is the base of the system that gained so much hype.</li><li>I want to implement research papers and try new things, and maybe publish my own research if I get to that point (crossing fingers).</li></ul><h3>So now to the topic.</h3><p>This is the first one, where I start the project. I named it <strong>Axiom</strong> cuz axiom means a basic truth or rule that is accepted without needing proof. And that was my starting point: building a transformer by myself and training it.</p><p>I started Andrej Karpathy’s video and saw him talk about tokenizers and all, and I already knew about that stuff, so rather than building a character-level tokenizer, I thought I would get a BPE tokenizer and then run it. I am trying to understand things, but let’s not make it that simple. And also, I didn’t want to copy his full implementation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/0*pnpjLg_PiPfSX5PI.jpg" /></figure><p>Me being a Neovim user (I use Vim btw), I ditched Jupyter Notebook, which was my go-to for building, training, and all the stuff that I used to do in college. I went straight through the editor, made it like a solid python project setup, with all the error handling, data loading, all the sequential stuff, function by function, clean. Every cell in Jupyter Lab was now a function in an orchestrator pipeline.</p><p>I created different folders, first a .local for storing all my local stuff, like datasets, tokenizers, converted tokens from my dataset, and all that. The main purpose of this was to create a JupyterLab kind of environment where I don’t need to load stuff every time.</p><p>I created a config file where I stored all of my configurations, my models, my paths, my tokenizer names, all of that.</p><p>Then came pulling the dataset from Hugging Face, a simple download and store function. I added this dataset, roneneldan/TinyStories. I wanted a small but not too small dataset, and then ChatGPT gave me this one, and I was like, okay, let’s try this. It was not my research or smth. I wanted some data, GPT told me to get this, so I did.</p><p>The next thing was downloading tokenizers. Same as the dataset, I just wrote the downloader condition for when to download, and then that was done too. I used lakhera2023/gemma4-nano-tinystories, again suggested by GPT and implemented by me.</p><p>Then came tokenization. I was doing in-memory tokenization, and that thing just killed my puny 8 gigs of RAM. For that size of dataset, each token was a number, and it stored way more than the text itself. And then adding it to my array again and again to save it later just overwhelmed the RAM, and it froze my system. But it was fun understanding it. That was the only point where I choked this time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/0*9-1aBNO-3-IWe5_i.jpg" /></figure><p>But yeah, solved it by directly writing to disk for each story in the dataset.</p><pre>with open(output_file, &quot;wb&quot;) as f:<br>        for sample in dataset:<br>            text = sample[&quot;text&quot;]<br>            tokens = tokenizer.encode(text)<br>            tokens.append(tokenizer.eos_id())<br>            np.asarray(tokens, dtype=np.uint16).tofile(f)</pre><p>Then came the batching stuff. Creating a batch was again a simple task, just brushing up my brain to implement it. A simple stacker that would just keep the output of the nth item as the (n+1)th item so that the transformer would know the y to its x is just its position shifted by one.</p><p>And that is what has been going on. Now, next: building the model itself. Following Andrej Karpathy, and we’ll see where I can improvise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/0*uWVDh-pncd_lPgNC.jpg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e77b4a767ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Built a Go Inference Gateway for Ollama, Load Tested It, and Understood Why vLLM Exists]]></title>
            <link>https://medium.com/@sulavstha007/built-a-go-inference-gateway-for-ollama-load-tested-it-and-understood-why-vllm-exists-417e8bd144b8?source=rss-1190d2c7f065------2</link>
            <guid isPermaLink="false">https://medium.com/p/417e8bd144b8</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[sulav shrestha]]></dc:creator>
            <pubDate>Mon, 23 Mar 2026 19:18:36 GMT</pubDate>
            <atom:updated>2026-03-23T19:18:36.347Z</atom:updated>
            <content:encoded><![CDATA[<p>So I’ve been learning Go for about two months now. One month of that was me going home after 3 years and doing absolutely nothing productive. So really one month. But I built a thing, I load tested it, and I learned something that I genuinely could not have learned by reading a blog post.</p><p>Which is ironic because you’re currently reading a blog post. Anyway.</p><h3>What I Actually Built</h3><p>I built a small HTTP gateway in Go that sits in front of Ollama and adds some production-y things to it, middleware, concurrency limiting, timeouts, metrics. The kind of stuff that makes you feel like a real engineer even when you’re running a 0.5 billion parameter model on your laptop at 2am.</p><p>The middleware chain looks like this:</p><pre>var predhandler http.Handler = http.HandlerFunc(handlers.Predict)<br>predhandler = middlewares.ConcurrentLimitWare(2000)(predhandler)<br>mux.Handle(&quot;/predict&quot;, predhandler)</pre><pre>handlers := middlewares.TimeoutMiddleware(gatewayTimeout())(mux)<br>handlers = middlewares.MetricsWare(handlers)<br>handlers = middlewares.LoggerWare(handlers)<br>return handlers</pre><p>Logger → metrics → timeout → concurrency limiter → the problem now, Ollama.</p><p>The concurrency limiter uses a semaphore. If it’s full, meaning more than 200 clients are hitting it simultaneously: you get a 503 Service Unavailable immediately instead of waiting forever. This is the polite way of saying &quot;we are cooked, please try again later.&quot;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/0*0oiV0ZCIVBT0qPgD.jpg" /></figure><p>The handler itself passes the request context all the way through to the Ollama call. This means if you disconnect, the outbound request gets cancelled too. No zombie requests burning CPU for a client that already left.</p><pre>reqOllama, err := http.NewRequestWithContext(r.Context(), &quot;POST&quot;, url, bytes.NewReader(reqBytes))</pre><p>And it handles failure cases explicitly instead of just panicking and hoping:</p><pre>switch {<br>case errors.Is(err, context.DeadlineExceeded):<br>    metrics.IncTimedOut()<br>    http.Error(w, &quot;Ollama request timed out&quot;, http.StatusGatewayTimeout)<br>case errors.Is(err, context.Canceled):<br>    http.Error(w, &quot;Ollama request canceled&quot;, http.StatusRequestTimeout)<br>default:<br>    http.Error(w, &quot;Error communicating with OLLAMA&quot;, http.StatusBadGateway)<br>}</pre><p>I also built a load testing tool (cmd/spam — named honestly) and a metrics dashboard CLI to watch everything live. Did I write those myself? I wrote the <em>prompts</em> for them. AI did the rest.</p><p>The CLI dashboard is genuinely beautiful though. Braille area charts, live rolling history, everything updating every second:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4AhT4omlUTQXFf9e1JQl9Q.png" /></figure><p>Gateway built. Metrics dashboard running. Time to absolutely bully it.</p><h3>The Setup: My Hardware</h3><p>Before the numbers, some context on the machine doing the suffering:</p><ul><li><strong>GPU:</strong> GTX 1650–4GB VRAM</li><li><strong>CPU:</strong> i5–9300H</li><li><strong>OS:</strong> Ubuntu on WSL</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*TBcZCqnxiBP7xcW0hIqitw.png" /></figure><p>Yes I have a GPU. Yes it’s only 4GB. Yes Ollama was still struggling. We’ll get to why.</p><h3>The Benchmark</h3><p>I ran this:</p><pre>for c in 20 40 60 80 100 120; do<br>  go run ./cmd/spam \<br>    -addr http://localhost:8080/predict \<br>    -model qwen2.5:0.5b \<br>    -prompt &quot;1+1 only answer the output nothing else&quot; \<br>    -n 3000 \<br>    -c &quot;$c&quot; \<br>    -timeout 200s<br>done</pre><p>3000 requests. 6 concurrency levels. A prompt so simple a calculator could answer it. I wanted to stress the <em>server</em>, not the model’s brain.</p><p>My hypothesis going in: more concurrency = more throughput. More requests in flight = more work getting done. Basic intuition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*Kl0jNnSpFzFDBlmS.jpg" /></figure><p><strong>I was wrong.</strong></p><h3>The Numbers</h3><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fdatawrapper.dwcdn.net%2F3qXk9%2F1%2F&amp;type=text%2Fhtml&amp;schema=dwcdn&amp;display_name=Datawrapper&amp;src=https%3A%2F%2Fdatawrapper.dwcdn.net%2F3qXk9%2F1%2F" width="732" height="304" frameborder="0" scrolling="no"><a href="https://medium.com/media/c506c1a511590204e3488b60c908e570/href">https://medium.com/media/c506c1a511590204e3488b60c908e570/href</a></iframe><p>Zero errors. Zero timeouts. Zero rejected (because my limit was 200 concurrent clients and I never crossed it). All 18,000 requests succeeded.</p><p>Now stare at the throughput column.</p><p>5.14 | 4.95 | 5.07 | 5.01 | 4.90 | 5.07</p><p>It. Does. Not. Move.</p><p>I went from 20 concurrent requests to 120, a 6× increase — and throughput went from 5.14 to… also basically 5. Meanwhile p50 latency went from 3.6 seconds to 22.7 seconds. A 6× increase in concurrency. A 6× increase in latency. Throughput just sitting there unbothered like it didn’t cause all of this.</p><h3>What This Actually Means</h3><p>Here’s the thing. My Go gateway was fine. It handled 120 concurrent connections without breaking a sweat. The problem wasn’t my code.</p><p>The problem was Ollama itself.</p><p>Ollama, even with a GTX 1650 doing the work, processes requests one at a time. Whether it has an internal queue or just handles them sequentially, the effect is the same , every request waits its turn. So what actually happens when 120 requests show up at once isn’t 120 things happening in parallel. It’s one thing happening, 119 times in a row, while everyone else stands outside.</p><p>The math makes sense once you know what’s actually happening. At ~5 req/s, with 100 requests in flight, each request is sitting behind roughly 20 others. Under that load each request is taking ~4 seconds queue wait, prefill, generation, all blending together. The latency scales almost exactly linearly with concurrency c=20 gives 3.6s p50, c=40 gives 7.8s, c=60 gives 11.4s. Roughly 2× concurrency, roughly 2× latency, every time. Throughput stays flat. Textbook single-server queue.</p><p>My gateway was the world’s most organised queue manager… for a queue that already existed inside Ollama. Very professional. Very redundant.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F1prGpYm8k8q15l87w70Hw.png" /></figure><h3>Why This Is Actually Interesting</h3><p>This flat throughput + linear latency pattern is exactly the baseline that production inference servers are designed to destroy.</p><p>Systems like <strong>vLLM</strong> use something called <strong>continuous batching </strong>(got to know after some digging). Instead of “finish request A entirely, then start request B”, they do:</p><p><em>“oh you need the next token? you too? everyone get your token at the same time.”</em></p><p>Throughput actually <em>increases</em> with load, up to the hardware limit.</p><p>I could have read about continuous batching a hundred times and got it intellectually. But watching my own benchmark produce a flat line on a machine that has an actual GPU made it real. The GPU wasn’t the bottleneck. The <em>scheduling</em> was. Now when I read about vLLM’s batching engine I know exactly what problem it’s solving.</p><h3>What I’m Building Next</h3><p><strong>Streaming responses</strong> — Ollama supports SSE. Right now I wait for the full response before sending anything back. Streaming would mean the client sees tokens as they’re generated. p50 latency would feel dramatically better even though total generation time is identical.</p><p><strong>Real health checking</strong> — my /health endpoint currently returns 200 and lies to everyone. It should check if Ollama is actually alive.</p><p><strong>Understanding the queue</strong> — right now I don’t fully know where the queueing happens inside Ollama. Is it at the HTTP layer? The model runner? Understanding that is the next step before I can make intelligent decisions about how to handle backpressure properly.</p><p>Then: vLLM internals, continuous batching, and eventually figuring out why the numbers look so different when someone actually designs the scheduler instead of letting it happen by accident.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*yid-XOXpC7xQJ1N5.jpg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=417e8bd144b8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Naive Go to Thread Pools: A Tiny CLI That Taught Me Concurrency]]></title>
            <link>https://medium.com/@sulavstha007/from-naive-go-to-thread-pools-a-tiny-cli-that-taught-me-concurrency-f69310cf0198?source=rss-1190d2c7f065------2</link>
            <guid isPermaLink="false">https://medium.com/p/f69310cf0198</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[goroutines]]></category>
            <category><![CDATA[threading]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[terminal]]></category>
            <dc:creator><![CDATA[sulav shrestha]]></dc:creator>
            <pubDate>Sat, 31 Jan 2026 18:43:08 GMT</pubDate>
            <atom:updated>2026-01-31T18:43:08.063Z</atom:updated>
            <content:encoded><![CDATA[<p>I wanted a new language, something close to the system, and I wanted low-level control and CLI experience. So, I built a CLI to count code stats… and accidentally DDOS’d my own laptop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/0*hRYnTe0lyH45pLig.jpg" /></figure><h3><strong>WHY GO?</strong></h3><p>I picked Go because I wanted to add a second language to my stack (I’d only used Python), and I wanted something closer to the system that still feels simple. Go is compiled, fast, and fits terminal‑first tooling perfectly, so it was a great way to learn real systems fundamentals while building something practical.</p><h3>ENTER: CodeStats</h3><p>After finishing <a href="https://go.dev/tour/welcome/1">A Go Tour</a>, a great, structured learning environment, I wanted something real to build.<br> So I started to make my first go project:<strong> CodeStats</strong>.<br> Nothing flashy, just a CLI that counts lines and characters across my repos.<br> I built it because I genuinely wanted to see how big my codebases were, and it felt like a perfect small project with room to grow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/0*cBz8PG3vzMUsmm3H.jpg" /></figure><p>The start was honestly smooth. I kept it intentionally simple: a small struct to hold counts, a map keyed by file extension, and a straightforward traversal.</p><pre>type FolderData struct {<br> FileExtension string<br> NoOfLines int<br> NoOfChars int<br>}</pre><p>Once everything was wired up, I tested it on my own repo, and it felt great. Clean output, correct totals, and the CLI gave me exactly the stats I wanted. And I was <strong>Happy </strong>as it was working.</p><h3>LEVEL UP</h3><p>I had just learnt about channels, goroutines, mutexes, waitgroups … and all the concurrency stuff, so why not use it?</p><p>I set it up so every traversal ran in its own goroutine, each one pushed the result into a channel, and a single consumer goroutine merged everything into the stats map.</p><p>The first run in the current directory…</p><p>It worked, and I was like: “Was it that simple?”</p><p>Python async taught me cooperative concurrency, but this was my first real taste of thread‑style coordination, where I had to manage how work flows and synchronises. So, I felt genuinely proud.</p><h3>BENCHMARKING</h3><p>Benchmark time: let’s see what actually improved.</p><ul><li>I cloned Linus Torvalds’ Linux repo and ran the latest <strong>CodeStats </strong>version.</li><li>It immediately started throwing a goroutine stack trace like this, which told me I was spawning insane amounts of work:</li></ul><pre>goroutine 14583 … syscall.openat …<br>created by codestats/helper.Traverser …</pre><ul><li>I opened btop and saw the thread count and RAM spike hard.</li><li>That’s when it clicked. I’d built unbounded concurrency — basically a self‑inflicted DDoS.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*EEDkIohnkpPRfI6AtX9auQ.png" /></figure><h3>THE FIX (AND THE DEADLOCK)</h3><pre>type Semaphore chan struct{}<br><br>func (s Semaphore) Acquire() { s &lt;- struct{}{} }<br>func (s Semaphore) Release() { &lt;-s }<br><br>sem := make(helper.Semaphore, *workers)</pre><p>After the self‑DDOS, I added a thread pool using a semaphore to cap how many goroutines could run at once. The crash stopped — but I introduced a deadlock.</p><ul><li>I put the semaphore acquire/release in the wrong place, so some goroutines never released their slot.</li></ul><pre>wg.Add(1)<br>sem.Acquire()  // DEADLOCK: blocks main thread if pool is full<br>go func(path string) {<br>    defer wg.Done()<br>    defer sem.Release()<br>    Traverser(path, ...)<br>}(filepath.Join(cwd, entry.Name()))</pre><ul><li>A few defers never ran because the goroutine got stuck before it could finish.</li><li>That meant the semaphore stayed “full,” and new work couldn’t start.</li><li>I sat staring at the screen, wondering why nothing was finishing.</li></ul><p>Finally, I fixed that, but it also made me think about ownership.</p><blockquote>Who “owns” a goroutine’s lifecycle, who closes channels, and who releases semaphore slots?</blockquote><pre>wg.Add(1)<br>go func(path string) {<br>    defer wg.Done()<br>    sem.Acquire()        // acquire INSIDE goroutine<br>    defer sem.Release()<br>    Traverser(path, ...)<br>}(filepath.Join(cwd, entry.Name()))</pre><h3>RESULTS</h3><p>I benchmarked on the Linux kernel repository — one of the largest open-source codebases in existence:</p><ul><li><strong>38.6 million lines of code</strong></li><li><strong>1.4 GB of source text</strong></li><li><strong>66% C code</strong></li><li><strong>27% headers</strong></li><li>plus, everything from Rust to YAML</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*R3Z6Ht6IARVA_kBmyF1oyw.png" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2FgKzml%2F1%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2FgKzml%2F1%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2FgKzml%2Fplain-s.png%3Fv%3D1&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="324" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc328ea2a3ade06f6a98b39544e6a77a/href">https://medium.com/media/cc328ea2a3ade06f6a98b39544e6a77a/href</a></iframe><p>Performance scales nearly linearly from 1 to 50 workers, achieving close to a <strong>10x speedup</strong>. Beyond 50 workers, performance plateaus — everything from 50 to 5000 workers finishes within roughly the same time window (59s to 1m5s).</p><p><strong>Why the plateau at 50 workers?</strong> At this point, I’ve saturated the available parallelism. My laptop has 10 cores and 12 logical processors (i7–1355U), and at ~50 workers I’m maxing out either CPU capacity or disk I/O bandwidth. Adding more workers doesn’t help because the bottleneck has shifted from “not enough parallelism” to “hardware limits.”</p><p><strong>Why doesn’t performance collapse at 5000 workers?</strong> This is where Go’s runtime shines. Goroutines start small and grow on demand, which is why spawning thousands didn’t immediately kill the process, and the semaphore prevents resource exhaustion. There’s some overhead, 5000 workers is about 5 seconds slower than optimal — but the system stays stable. No crashes, no memory explosion, just graceful degradation.</p><p><strong>The sweet spot:</strong> 50–100 workers provides optimal performance for this I/O-bound workload without wasting resources on unnecessary overhead.</p><h3>LESSONS LEARNED</h3><ul><li>Concurrency isn’t free: without limits, it becomes a self‑DDOS.</li><li>Correctness beats speed: the program must finish every time.</li><li>Ownership matters: who starts, who waits, who closes, who releases.</li></ul><p><strong>A note on the environment:</strong> These benchmarks were run on WSL (Windows Subsystem for Linux) on a laptop with an i7–1355U. WSL adds virtualisation overhead, so performance on native Linux would likely be better.</p><p>These aren’t strict findings, just my personal learnings from trying something new. If I missed something or there’s a better way to do it, I’d genuinely love to hear it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f69310cf0198" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Get AI to Solve Complex Problems (Without Losing Your Mind)]]></title>
            <link>https://medium.com/@sulavstha007/how-to-get-ai-to-solve-complex-problems-without-losing-your-mind-580094079503?source=rss-1190d2c7f065------2</link>
            <guid isPermaLink="false">https://medium.com/p/580094079503</guid>
            <dc:creator><![CDATA[sulav shrestha]]></dc:creator>
            <pubDate>Sun, 21 Dec 2025 17:12:18 GMT</pubDate>
            <atom:updated>2025-12-21T17:13:25.563Z</atom:updated>
            <content:encoded><![CDATA[<p>Most people prompt AI like this:</p><p>“Build me a budget tracker that handles recurring expenses, one-time costs, and calculates monthly savings with rollover logic.”</p><p>Then they wonder why the output is wrong.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IJj_Sr94GwSwL9dXn4A3Zw.png" /></figure><p>Here’s what actually works, the <strong>Reflect-Then-Solve Method</strong>:</p><ol><li>Explain the problem as it exists</li><li>Give the task, but block the solution</li><li>Force the AI to confirm understanding and ask questions</li><li>Add constraints one at a time</li><li>Test rules with specific scenarios</li><li>Confirm everything is locked in</li><li>Only then, let it solve</li></ol><p>This turns ChatGPT and Claude from “confident but wrong” into “actually useful.”</p><h3>Why Normal Prompting Fails</h3><p>You give the AI everything at once. It tries to solve immediately. It makes assumptions about the 12 things you didn’t specify.</p><p>You get something that’s <em>close</em> but wrong in ways you don’t notice until later.</p><p>The Reflect-Then-Solve Method fixes this by forcing the AI to understand before it builds.</p><h3>1. Explain What Actually Exists</h3><p>Don’t start with what you want. Start with what you have.</p><p><strong>Bad:</strong> “Make a spreadsheet that tracks inventory.”</p><p><strong>Good:</strong> “I have a product list with stock levels. Some products get restocked weekly, some monthly. Right now I manually update quantities. No automation exists yet.”</p><p>Why this works: The AI now knows the starting point. It won’t assume you already have half the system built.</p><h3>2. Give the Task, Then Block the Solution</h3><p>Tell it what to do, then explicitly stop it from doing it.</p><p><strong>Say this:</strong> “Here’s what I need: [explain task]. But don’t build anything yet. Just tell me back what you understand, and ask me questions about anything unclear.”</p><p><strong>Example:</strong> “I need a system that tracks monthly expenses and shows running balance. Some months have no transactions. Don’t solve this yet, just explain back what I’m asking for and ask clarifying questions.”</p><p>This forces the AI to actually think instead of pattern-matching to the first solution it’s seen before.</p><h3>3. Make It Prove Understanding</h3><p>The AI will explain back what it understood. Read it carefully.</p><p><strong>This is where you catch problems early:</strong></p><p>The AI might say: “So you want every month to show a balance?”</p><p>You realize: “No, only months with activity or between active months.”</p><p>That’s a rule you forgot to mention. If you’d let it solve immediately, it would’ve been wrong.</p><p><strong>The AI should also ask questions.</strong> If it doesn’t, it’s guessing.</p><h3>Real Example: The Monthly Balance Tracker</h3><p>I wanted a running balance spreadsheet. Here’s how it actually went:</p><p><strong>Me:</strong> “I need a monthly balance tracker. Starting balance exists. Some months have transactions, some don’t. Don’t build it yet, tell me what you understand and ask questions.”</p><p><strong>AI:</strong> “You want a running balance by month. Should empty months show the previous balance, or stay blank?”</p><p><strong>Me:</strong> “Good question. Months before the first transaction should be blank. Months after the last transaction should be blank. Only months between transactions should carry the balance forward.”</p><p><strong>AI:</strong> “So if transactions happen in January and March, February shows January’s balance, but April stays blank?”</p><p><strong>Me:</strong> “Exactly.”</p><p><strong>Now</strong> the AI had the real rules. The formula it built worked perfectly on the first try.</p><p>If I’d just said “build a balance tracker,” it would’ve guessed wrong about empty months.</p><h3>4. Add Constraints One at a Time</h3><p>Don’t dump everything in one prompt.</p><p><strong>Instead:</strong></p><p>“Okay, now add this rule: [one constraint]”</p><p>Wait for confirmation.</p><p>“Now add this: [next constraint]”</p><p>Each time, the AI confirms understanding before moving forward.</p><p><strong>Why this works:</strong> The AI processes one rule at a time. It doesn’t get confused trying to juggle 8 requirements simultaneously.</p><h3>5. Pressure-Test with Scenarios</h3><p>Before letting the AI build anything, throw edge cases at it.</p><p><strong>Say:</strong> “Walk me through what happens if:</p><ul><li>The first month has no data</li><li>Two transactions happen in the same month</li><li>There’s a gap of 6 months between transactions”</li></ul><p>If the AI’s logic breaks, you catch it now instead of after it writes 200 lines of code.</p><h3>6. Lock It In</h3><p>Before solving, get explicit confirmation:</p><p>“Based on everything we discussed, here are the rules: [list them]. Is this correct?”</p><p>Once the AI confirms, you have a locked specification. No more guessing.</p><h3>7. Now Let It Solve</h3><p>Say: “Okay, now build it.”</p><p>At this point:</p><ul><li>No ambiguity</li><li>No assumptions</li><li>No surprise bugs from edge cases you forgot</li></ul><p>The solution works because you forced clarity first.</p><h3>Why This Actually Works with AI</h3><p>AI is fast but not psychic. It will:</p><ul><li>Fill gaps with assumptions</li><li>Pick the most common pattern it’s seen</li><li>Confidently solve the wrong problem</li></ul><p>The Reflect-Then-Solve Method forces the AI to <strong>slow down and think</strong> instead of pattern-matching.</p><p>It’s the difference between:</p><ul><li>“Give me your best guess” (normal prompting)</li><li>“Understand this completely, then solve” (this method)</li></ul><h3>When to Use This</h3><p><strong>Use it for:</strong></p><ul><li>Conditional logic (if X then Y, unless Z)</li><li>Multi-step workflows</li><li>Systems with edge cases</li><li>Anything where “close enough” creates problems</li></ul><p><strong>Don’t use it for:</strong></p><ul><li>Simple requests</li><li>Throwaway tasks</li><li>Exploration where you’re not sure what you want yet</li></ul><p>If the problem is complex enough that you’d struggle to explain it to a human, use this method with AI.</p><h3>The Real Lesson</h3><p>AI is excellent at execution. It’s terrible at mind-reading.</p><p>The Reflect-Then-Solve Method stops treating AI like a mind reader and starts treating it like a very fast, very literal partner who needs clear instructions.</p><p>Give it clarity, and it’s unstoppable.</p><p>Give it ambiguity, and it’s just expensive guessing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=580094079503" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My First Kafka Setup: Learning Real-Time Data Streaming with Agricultural Sensor Data (AgriIntel Pt.]]></title>
            <link>https://medium.com/@sulavstha007/my-first-kafka-setup-learning-real-time-data-streaming-with-agricultural-sensor-data-agriintel-pt-66dfb2cde396?source=rss-1190d2c7f065------2</link>
            <guid isPermaLink="false">https://medium.com/p/66dfb2cde396</guid>
            <dc:creator><![CDATA[sulav shrestha]]></dc:creator>
            <pubDate>Sun, 29 Jun 2025 10:18:24 GMT</pubDate>
            <atom:updated>2025-06-29T10:18:24.843Z</atom:updated>
            <content:encoded><![CDATA[<h3>My First Kafka Setup: Learning Real-Time Data Streaming with Agricultural Sensor Data (AgriIntel Pt. 3)</h3><p>I’ll be honest upfront — this is my first time setting up Apache Kafka. I’m sharing what I learned, the mistakes I made, and what I’d do differently next time. This isn’t production-ready; it’s a learning exercise that taught me the fundamentals of real-time data streaming.</p><p>If you’re also new to Kafka and want to see a realistic beginner’s journey (including the parts that didn’t work initially), this post is for you.</p><h3>What I Built (And What It Actually Is)</h3><p>I created a simple data pipeline that simulates agricultural sensor data streaming:</p><ul><li>Python script generates fake weather data</li><li>Kafka broker handles the message streaming</li><li>Python consumer reads and processes the messages</li><li>All containerized with Docker for easy setup</li></ul><p><strong>Important caveat:</strong> This is a single-node setup running on my laptop. It’s not fault-tolerant, not scalable, and definitely not production-ready. But it’s perfect for learning Kafka basics.</p><h3>System Architecture</h3><p>Here’s what the data flow looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JhAuat8-J0c8lPny_kL2EA.png" /></figure><p>Simple, right? That’s the point. I wanted to understand the core concepts before adding complexity.</p><h3>Docker Setup: Why I Chose KRaft Mode</h3><p>Setting up Kafka traditionally requires ZooKeeper, but I used KRaft mode (available since Kafka 3.3+) to avoid that complexity. Here’s my Docker Compose setup:</p><h3>Network Configuration</h3><pre>networks:<br>  kafka-learning-net:<br>    driver: bridge</pre><p>This creates an isolated network so containers can communicate reliably.</p><h3>Kafka Broker Setup</h3><pre>services:<br>  broker:<br>    image: confluentinc/cp-kafka:latest<br>    hostname: broker<br>    container_name: broker<br>    networks:<br>      - kafka-learning-net<br>    ports:<br>      - &quot;9092:9092&quot;<br>      - &quot;9101:9101&quot;<br>    environment:<br>      CLUSTER_ID: &#39;L8kR2vXzTqW_aBcDeFgHiJ&#39;<br>      KAFKA_PROCESS_ROLES: &#39;broker,controller&#39;<br>      KAFKA_NODE_ID: 1<br>      KAFKA_CONTROLLER_QUORUM_VOTERS: &#39;1@broker:29093&#39;<br>      KAFKA_CONTROLLER_LISTENER_NAMES: &#39;CONTROLLER&#39;<br>      KAFKA_LISTENERS: &#39;PLAINTEXT://:9092,PLAINTEXT_INTERNAL://:29092,CONTROLLER://:29093&#39;<br>      KAFKA_ADVERTISED_LISTENERS: &#39;PLAINTEXT://localhost:9092,PLAINTEXT_INTERNAL://broker:29092&#39;<br>      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: &#39;CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT,PLAINTEXT_INTERNAL:PLAINTEXT&#39;<br>      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1<br>      KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1<br>      KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1<br>    volumes:<br>      - kafka_data:/var/lib/kafka/data</pre><p><strong>What I learned:</strong> The listener configuration was the trickiest part. PLAINTEXT_INTERNAL allows containers to talk to each other, while PLAINTEXT exposes Kafka to my host machine.</p><h3>Kafka UI for Monitoring</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7HFKoliJ9WlUnZp4fr8Awg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SDyrTsMxiWFuo3uMsEg_2g.png" /></figure><pre>kafka-ui:<br>    image: provectuslabs/kafka-ui:latest<br>    hostname: kafka-ui<br>    container_name: kafka-ui<br>    networks:<br>      - kafka-learning-net<br>    depends_on:<br>      - broker<br>    ports:<br>      - &quot;8080:8080&quot;<br>    environment:<br>      KAFKA_CLUSTERS_0_NAME: &#39;Learning-Kafka&#39;<br>      KAFKA_CLUSTERS_0_BOOTSTRAPSERVERS: &#39;broker:29092&#39;<br>      DYNAMIC_CONFIG_ENABLED: &#39;true&#39;</pre><p>The web UI at localhost:8080 became invaluable for debugging. I could see topics, partitions, consumer lag, and message contents.</p><h3>The Producer: Simulating Sensor Data</h3><p>My producer generates fake weather data for different locations:</p><h3>Configuration (producer_config.yaml)</h3><pre>producer:<br>  bootstrap.servers: &quot;localhost:9092&quot;<br>  client.id: &quot;weather_producer&quot;<br>  acks: &quot;1&quot;<br>  retries: 3</pre><p><strong>Mistake I made initially:</strong> I forgot to set acks and retries. Lost messages during testing until I added proper acknowledgment settings.</p><h3>Producer Code</h3><pre>from confluent_kafka import Producer<br>import json, time, random, yaml<br># Load config<br>with open(&quot;producer_config.yaml&quot;, &quot;r&quot;) as f:<br>    config = yaml.safe_load(f)[&quot;producer&quot;]<br>producer = Producer(config)<br>def delivery_report(err, msg):<br>    if err:<br>        print(f&quot;❌ Failed to deliver message: {err}&quot;)<br>    else:<br>        print(f&quot;✅ Message delivered to {msg.topic()}[{msg.partition()}] at offset {msg.offset()}&quot;)<br>def generate_weather_data(location):<br>    return {<br>        &quot;location&quot;: location,<br>        &quot;temperature&quot;: round(random.uniform(20, 30), 2),<br>        &quot;humidity&quot;: round(random.uniform(40, 60), 2),<br>        &quot;timestamp&quot;: int(time.time())<br>    }<br>locations = [&quot;Kathmandu&quot;, &quot;Pokhara&quot;, &quot;Chitwan&quot;, &quot;Biratnagar&quot;, &quot;Butwal&quot;]<br>try:<br>    while True:<br>        for loc in locations:<br>            data = generate_weather_data(loc)<br>            try:<br>                producer.produce(<br>                    &#39;weather_data&#39;,<br>                    key=loc,<br>                    value=json.dumps(data).encode(&#39;utf-8&#39;),<br>                    callback=delivery_report<br>                )<br>                producer.poll(0.1)  # Allow time for delivery reports<br>            except BufferError:<br>                print(&quot;Producer buffer full, waiting...&quot;)<br>                producer.poll(1.0)<br>        time.sleep(1)<br>except KeyboardInterrupt:<br>    print(&quot;Shutting down producer...&quot;)<br>finally:<br>    producer.flush()</pre><p><strong>What I learned:</strong></p><ul><li>Using location as the key ensures messages from the same location go to the same partition (ordering guarantee)</li><li>producer.poll(0.1) is better than poll(0) - gives time for delivery callbacks</li><li>Buffer management matters even in simple setups</li></ul><h3>The Consumer: Processing the Data</h3><h3>Configuration (consumer_config.yaml)</h3><pre>consumer:<br>  bootstrap.servers: &quot;localhost:9092&quot;<br>  group.id: &quot;weather_consumer_group&quot;<br>  auto.offset.reset: &quot;earliest&quot;<br>  enable.auto.commit: &quot;true&quot;<br>  auto.commit.interval.ms: 1000<br>topics:<br>  - &quot;weather_data&quot;</pre><h3>Consumer Code</h3><pre>from confluent_kafka import Consumer, KafkaError, KafkaException<br>import json, yaml<br><br># Load config<br>with open(&quot;consumer_config.yaml&quot;, &quot;r&quot;) as f:<br>    config = yaml.safe_load(f)<br>consumer = Consumer(config[&quot;consumer&quot;])<br>topics = config[&quot;topics&quot;]<br>consumer.subscribe(topics)<br>print(f&quot;Subscribed to topics: {topics}&quot;)<br>try:<br>    while True:<br>        msg = consumer.poll(1.0)<br>        if msg is None:<br>            continue<br>        if msg.error():<br>            if msg.error().code() == KafkaError._PARTITION_EOF:<br>                print(&quot;Reached end of partition&quot;)<br>                continue<br>            else:<br>                raise KafkaException(msg.error())<br>        <br>        # Process message<br>        try:<br>            data = json.loads(msg.value().decode(&#39;utf-8&#39;))<br>            print(f&quot;Received from {data[&#39;location&#39;]}: {data[&#39;temperature&#39;]}°C, {data[&#39;humidity&#39;]}% humidity&quot;)<br>        except json.JSONDecodeError:<br>            print(&quot;❌ Invalid JSON received&quot;)<br>        except KeyError as e:<br>            print(f&quot;❌ Missing field in message: {e}&quot;)<br>            <br>except KeyboardInterrupt:<br>    print(&quot;Shutting down consumer...&quot;)<br>finally:<br>    consumer.close()</pre><h3>Challenges I Faced</h3><h3>1. Topic Creation</h3><p><strong>Problem:</strong> My consumer wasn’t receiving any messages. <strong>Solution:</strong> Kafka auto-creates topics, but I needed to ensure the producer ran first or manually create the topic.</p><h3>2. Network Connectivity</h3><p><strong>Problem:</strong> Spent 2 hours debugging connection issues. <strong>Solution:</strong> Docker network configuration was wrong. The PLAINTEXT_INTERNAL vs PLAINTEXT listeners distinction was crucial.</p><h3>3. Consumer Group Rebalancing</h3><p><strong>Problem:</strong> When I restarted the consumer, it would sometimes re-process old messages. <strong>Solution:</strong> Understanding auto.offset.reset and consumer group behavior. Set to &quot;latest&quot; for new messages only.</p><h3>4. Message Ordering</h3><p><strong>Problem:</strong> Messages from the same location weren’t always processed in order. <strong>Solution:</strong> Using location as the message key ensures partition-level ordering.</p><h3>What I’d Do Differently Next Time</h3><ol><li><strong>Add schema validation</strong> — JSON schema or Avro to catch data format issues early</li><li><strong>Better error handling</strong> — More robust retry logic and dead letter queues</li><li><strong>Monitoring</strong> — JMX metrics and proper logging</li><li><strong>Testing</strong> — Unit tests for producer/consumer logic</li><li><strong>Configuration management</strong> — Environment-specific configs</li></ol><h3>KRaft vs ZooKeeper: Why I Chose KRaft</h3><p>Traditional Kafka requires ZooKeeper for metadata management, but KRaft mode eliminates this dependency:</p><p><strong>Benefits for learning:</strong></p><ul><li>Simpler setup (one less component)</li><li>Faster startup times</li><li>Easier to understand the architecture</li></ul><p><strong>Trade-offs:</strong></p><ul><li>Still relatively new (though stable)</li><li>Some features might not be available yet</li></ul><p>For my learning purposes, KRaft was perfect.</p><h3>Lessons Learned</h3><ol><li><strong>Start simple</strong> — Don’t try to build a production system on day one</li><li><strong>Docker Compose is your friend</strong> — Makes experimentation much easier</li><li><strong>Monitoring is essential</strong> — Kafka UI helped in debugging</li><li><strong>Message keys matter</strong> — They affect partitioning and ordering</li><li><strong>Configuration is critical</strong> — Small config changes have big impacts</li></ol><h3>What’s Next?</h3><p>Now that I understand the basics, here’s what I want to explore:</p><ul><li><strong>Multi-broker setup</strong> for fault tolerance</li><li><strong>Kafka Streams</strong> for real-time processing</li><li><strong>Schema Registry</strong> for data evolution</li><li><strong>Kafka Connect</strong> for database integration</li><li><strong>Security configurations</strong> (SASL, SSL)</li><li><strong>Performance tuning</strong> and optimization</li></ul><h3>Getting Started Yourself</h3><p>To run this setup:</p><ol><li>Copy the configs above</li><li>Run docker-compose up -d</li><li>Wait for services to start (check logs with docker-compose logs)</li><li>Access Kafka UI at localhost:8080</li><li>Run the producer: python producer.py</li><li>Run the consumer: python consumer.py</li></ol><h3>Final Thoughts</h3><p>This setup taught me Kafka fundamentals without overwhelming complexity. It’s not production-ready, but it doesn’t need to be. The goal was learning, and it delivered.</p><p>If you’re starting your Kafka journey, don’t feel pressured to build enterprise-grade systems immediately. Start with something simple, understand the concepts, then gradually add complexity.</p><p>The agricultural sensor angle was fun to work with, but the same patterns apply to any real-time data streaming use case — IoT, web analytics, financial data, you name it.</p><p>Feel free to ask questions or share your own Kafka learning experiences. We’re all figuring this out together.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66dfb2cde396" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kafka + Spark for Simulated IoT (AgriIntel Pt. 2)]]></title>
            <link>https://medium.com/@sulavstha007/kafka-spark-for-simulated-iot-agriintel-pt-2-d6231ff502bd?source=rss-1190d2c7f065------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6231ff502bd</guid>
            <dc:creator><![CDATA[sulav shrestha]]></dc:creator>
            <pubDate>Sat, 14 Jun 2025 05:09:15 GMT</pubDate>
            <atom:updated>2025-06-14T05:09:15.091Z</atom:updated>
            <content:encoded><![CDATA[<p>This post kicks off the technical design of <strong>AgriIntel</strong> — a weather-aware farming assistant that provides real-time crop advice using live weather data and LLMs.</p><p>In Part 1, I laid out the goal: answer practical farmer questions like:</p><ul><li><em>“Do I need to water today?”</em></li><li><em>“Is fungal risk high this week?”</em></li></ul><p>To do that, I need fast, fault-tolerant pipelines that can handle both <strong>streaming</strong> (real-time weather) and <strong>batch</strong> (historical trends).</p><p>This post covers the high-level data architecture I’m building using:</p><ul><li><strong>Kafka</strong> for simulating sensor data</li><li><strong>Spark</strong> for batch transformation</li><li><strong>PostgreSQL</strong> for fast analytics</li></ul><p>The next posts will show <strong>how I simulate IoT weather sensors</strong>, produce Kafka events, and batch-transform with Spark.</p><h3>Project Pivot: Why I Switched From an API to Simulation</h3><p>Initially, I planned to use the <strong>OpenWeatherMap API</strong> to get weather data. But a few problems popped up:</p><ul><li><strong>API Rate Limits</strong> — hard to scale when calling every hour across multiple locations</li><li><strong>Pricing Tiers</strong> — free tier wasn’t enough; paid tiers quickly become expensive</li><li><strong>Lack of Control</strong> — limited ability to simulate edge cases or test with volume</li></ul><p>So, I decided to <strong>simulate sensor data using Kafka</strong> — this also gave me full control, speed, and flexibility.</p><h3>Architecture Overview</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*sl0rWEaEZhOAQVDXxLR4xg.png" /><figcaption>THE ARCHITECTURE</figcaption></figure><p>The architecture I’ve built (see diagram above) follows a pragmatic take on the <strong>lakehouse</strong> model — not in buzzword, but in function.</p><ul><li><strong>Raw weather data is streamed via Kafka</strong> and written as <strong>partitioned Parquet files</strong>. This acts as the “data lake” layer — cheap, append-only, and easy to replay or reprocess.</li><li><strong>Apache Spark</strong> periodically ingests these files, performing <strong>cleaning, aggregations, and transformations</strong>.</li><li>The processed output is stored in a <strong>PostgreSQL database</strong>, which serves fast, structured queries for both the <strong>dashboard</strong> and <strong>LLM-based assistant</strong>.</li></ul><p>This hybrid setup separates <strong>raw ingestion from analytical access</strong>, giving us:</p><ul><li>Rewind/replay capability during development.</li><li>Cost-effective storage at scale.</li><li>Optimized downstream performance (no row-by-row DB writes).</li><li>Flexibility to experiment with schema and transformations without touching the source.</li></ul><p>It’s not trying to replicate full-scale lakehouse stacks like Delta or Iceberg — but the principles apply: <strong>decoupled, resilient, and analytics-ready</strong>.</p><h3>Kafka for Real-Time Simulation</h3><p><strong>Apache Kafka</strong> is a distributed event streaming platform. You can think of it as a <strong>high-throughput message bus</strong> — producers write data to it, consumers read from it.</p><h3>In AgriIntel:</h3><ul><li><strong>Kafka Producer</strong> simulates weather sensors — pushing JSON-like weather events</li><li><strong>Kafka Consumer</strong> stores these events into files (JSON or Parquet), organized by timestamp</li></ul><p>Example path structure:</p><pre>/data/raw/year=2025/month=06/day=03/hour=14/</pre><h3>Why Kafka?</h3><ul><li><strong>Buffering</strong> — handles bursts of data without losing anything</li><li><strong>Scalable</strong> — easy to expand to more producers/consumers</li><li><strong>Durable</strong> — messages aren’t lost if the consumer crashes</li><li><strong>Streaming-ready</strong> — perfect for future real-time alerts</li></ul><h3>Raw Data Lake Strategy</h3><p>All Kafka-consumed data is written as <strong>raw files</strong>, not directly to a database.</p><p>Why?</p><ul><li>Avoids writing each tiny record into a database (which is expensive and noisy)</li><li>Makes it easier to replay data or fix mistakes</li><li>Lets us batch process later, on our terms</li></ul><h3>Batch Transformation with Apache Spark</h3><p>While Kafka handles real-time ingestion, <strong>Apache Spark</strong> (PySpark) takes care of batch processing.</p><p>Spark is a powerful engine for distributed data processing — perfect for cleaning, transforming, and summarizing big data.</p><h3>In AgriIntel:</h3><ul><li>Spark reads raw files every few minutes/hours</li><li>It aggregates values like <strong>daily temperature trends</strong>, <strong>average humidity</strong>, <strong>total rainfall</strong></li><li>Then writes this cleaned data into a <strong>PostgreSQL database</strong></li></ul><p>This DB is what powers the <strong>analytics dashboards</strong> and <strong>LLM-based assistant</strong>.</p><h3>Why Not Write Directly to the DB?</h3><p>It’s tempting to have the Kafka consumer write directly to the database. But:</p><ul><li>Inserting rows every few seconds → bloats the DB and slows everything down</li><li>Hard to index and query meaningfully</li><li>Can lead to frequent locking or crash issues</li></ul><h3>What’s Coming Next?</h3><p>In the upcoming post, I’ll be:</p><ul><li>Implementing this setup of <strong>Kafka</strong></li><li>Setting up the <strong>Spark job</strong> to transform daily weather trends</li><li>Designing the <strong>PostgreSQL schema</strong></li><li>Beginning to connect it to the <strong>LLM layer</strong> using FastAPI</li></ul><p>This is just the beginning — I’m learning in public, so stay tuned for more updates, design tweaks, and experiments!</p><p>Thanks for reading! If you’re working on something similar, or curious about the setup, feel free to drop a comment. Building this in public — one module, one blog post at a time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6231ff502bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Learning Full Stack Data with GenAI — Part 1: Project Kickoff]]></title>
            <link>https://medium.com/@sulavstha007/learning-full-stack-data-with-genai-part-1-project-kickoff-8e0c419641ac?source=rss-1190d2c7f065------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e0c419641ac</guid>
            <dc:creator><![CDATA[sulav shrestha]]></dc:creator>
            <pubDate>Tue, 03 Jun 2025 15:11:10 GMT</pubDate>
            <atom:updated>2025-06-03T15:11:10.078Z</atom:updated>
            <content:encoded><![CDATA[<h3>🌾 Learning Full Stack Data with GenAI — Part 1: Project Kickoff</h3><h3>Hey there! 👋</h3><p>Welcome to the first post in what might become a series — or maybe just a one-off project. I’m keeping things open, relaxed, and real here. The goal? To document my journey learning full stack data development in public, and build something genuinely useful along the way.</p><h3>Why I’m Doing This</h3><p>I’m a data enthusiast currently sharpening my skills across the <strong>full data stack</strong> — from data engineering and analytics to machine learning and GenAI. I know the basics of data engineering and LLMs, but there’s still a lot to learn, especially around real-time applications and analytics.</p><p>So instead of just reading docs or following tutorials, I decided to learn by doing — and let an LLM (like ChatGPT) act as my co-pilot through this process. Every decision I make, every error I hit, every design choice — I want to record it and share it. Maybe someone finds it useful. Maybe future-me just needs a place to look back. Either way, it’s a win.</p><h3>The Project Idea: AgriIntel</h3><p>I’m calling it <strong>AgriIntel</strong> — a weather-aware farming assistant. The idea is to help farmers make smarter decisions using real-time and historical weather data, plus a little help from LLMs.</p><h3>The Goal</h3><p>Build a system that gives personalized, location-specific insights for farmers. Stuff like:</p><ul><li>“Should I water my crops today?”</li><li>“How will this week’s weather affect my tomato farm in ‘a’ ?”</li><li>“Is this month unusually dry compared to average?”</li></ul><h3>What I’m Planning to Build</h3><p>Here’s a rough outline of what the system might include:</p><h4>1. Data Ingestion</h4><ul><li>Pull real-time weather data using the <strong>OpenWeatherMap API</strong></li><li>Use <strong>Kafka</strong> to stream the data in real-time</li><li>Schedule jobs with <strong>Airflow</strong></li></ul><h4>2. Processing + Storage</h4><ul><li>Store raw weather data in <strong>Azure Blob Storage</strong> or locally</li><li>Use <strong>Spark</strong> for both streaming and batch transformations</li><li>Build clean tables (daily, weekly, monthly aggregates) using <strong>dbt</strong></li></ul><h4>3. Analytics Layer</h4><ul><li>Create a dashboard (probably with <strong>Streamlit</strong> or <strong>Power BI</strong>) showing trends, anomalies, and comparisons across regions</li></ul><h4>4. LLM-Based Assistant</h4><ul><li>A chatbot built using <strong>FastAPI + OpenAI API</strong></li><li>Ask questions like:<br> <em>“What should I do for my wheat crop in “x” this week?”</em><br> And it’ll respond based on the weather trends and basic crop heuristics.</li></ul><h3>Tech Stack (For Now)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*D_daVs-pvebsBoB4" /></figure><p>Layer Tools Ingestion OpenWeatherMap, Kafka Scheduling Airflow Processing Apache Spark, dbt Storage Azure Blob / PostgreSQL Serving Layer FastAPI, Docker Analytics Streamlit / Power BI LLM Assistant OpenAI API + Prompt Logic</p><h3>What’s Next?</h3><p>In the next few posts (if I write them 😅), I’ll be diving into each layer of this system, one piece at a time. Starting with:</p><ul><li>Setting up the data ingestion pipeline with <strong>Kafka</strong> + <strong>OpenWeatherMap</strong></li><li>Streaming that into storage with <strong>Spark Structured Streaming</strong></li><li>Learning how LLMs can help me debug, plan, and even generate code as I go</li></ul><p>This isn’t a tutorial — it’s a logbook. Think of it as building a project with an LLM mentor watching over my shoulder (and you get to watch too).</p><p>If that sounds interesting, stay tuned.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e0c419641ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>