<?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 Purusharth Yaduwanshi on Medium]]></title>
        <description><![CDATA[Stories by Purusharth Yaduwanshi on Medium]]></description>
        <link>https://medium.com/@purusharthyadav.py?source=rss-bcc23fb92681------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*PPfXyh-3px9hGXfh2e2W_Q.jpeg</url>
            <title>Stories by Purusharth Yaduwanshi on Medium</title>
            <link>https://medium.com/@purusharthyadav.py?source=rss-bcc23fb92681------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 07:17:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@purusharthyadav.py/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[Local LLM Deployment & Model Optimization: Why I Bought the Car Instead of Taking Ubers Forever]]></title>
            <link>https://ai.plainenglish.io/local-llm-deployment-model-optimization-why-i-bought-the-car-instead-of-taking-ubers-forever-a5b50322c2f1?source=rss-bcc23fb92681------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5b50322c2f1</guid>
            <category><![CDATA[generative-ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Purusharth Yaduwanshi]]></dc:creator>
            <pubDate>Thu, 13 Aug 2026 23:07:52 GMT</pubDate>
            <atom:updated>2026-08-13T23:07:52.074Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Cloud APIs rent you intelligence. Local LLMs let you own it — maintenance included.</em></p><p>When I first started experimenting with open-weight models, I assumed “running an LLM locally” meant one thing: download a model, point some Python at it, pray to the CUDA gods.</p><p>It took exactly one out-of-memory crash to realize how wrong that was.</p><p>Local LLM deployment isn’t one skill. It’s three, stacked on top of each other — <strong>picking the right tool, picking a model that actually fits your hardware, and squeezing that model until it’s fast enough to be worth the trouble.</strong> Most tutorials only teach the first one, run ollama run once, and call it a day.</p><p>This is the version nobody gave me. Let’s fix that.</p><h3>Wait… Why Would Anyone Run an LLM at Home?</h3><p>Here’s the analogy I keep coming back to: using a cloud API is like taking an Uber everywhere. Running a model locally is like buying a car.</p><p>Ubers are wonderful when you need one ride. No maintenance, no insurance, works in any city. But take one every single day and the bill quietly turns into a second rent payment. Buying a car front-loads the pain, you pay a lot upfront, and then you’re stuck doing your own oil changes but after that, every ride is basically free.</p><p>That’s the entire economic argument for local LLMs, and the chart below is the only slide you actually need in that meeting:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*jWX6qye5yTFkQCAvdUiZFQ.png" /></figure><p>Cost isn’t the only reason people go local, though. The honest list looks like this:</p><p>• <strong>Privacy</strong> — nothing leaves your machine. Great for anything you wouldn’t paste into a public chatbot: contracts, patient notes, your unreleased startup idea.</p><p>• <strong>No rate limits, no vendor mood swings</strong> — no “the API is degraded today” emails.</p><p>• <strong>Offline is a feature, not a compromise</strong> — flights, air-gapped networks, client sites with no Wi-Fi.</p><p>• <strong>You can actually poke at it</strong> — fine-tune it, quantize it, bolt weird tools onto it. Try doing that to GPT-5.</p><p>• <strong>You learn what’s actually happening</strong> — attention, KV caches, batching — instead of it all being someone else’s black box.</p><p>None of this means cloud APIs are bad. If you need a frontier-class model for one gnarly reasoning task once a week, Ubering is objectively the right call. Local LLMs make sense once usage is <em>frequent, private, or customized</em> — the break-even point in that chart above is not a joke, it’s a spreadsheet you should actually build before buying a GPU.</p><h3>Meet Your Mechanics: The Local LLM Toolbox</h3><p>Here’s where most people get stuck, because in 2026 “just run it locally” now has about five competing answers, and they are not interchangeable:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*Yo8qEqbEY7SGm3Ho748k4g.png" /></figure><p>Think of it as four layers, foundation to surface:</p><p>• <strong>Hardware</strong> (GPU / CPU / unified memory) — where electricity actually becomes tokens.</p><p>• <strong>Engine</strong> (llama.cpp, MLX) — the thing that does the actual matrix math. Lowest-level, highest control, zero hand-holding.</p><p>• <strong>Wrapper</strong> (Ollama, LM Studio) — the friendly dealership. One command pulls, quantizes, and serves a model with an OpenAI-compatible API. This is 90% of what people actually want.</p><p>• <strong>Serving system</strong> (vLLM) — not really a “wrapper,” more like a fleet manager. Built ground-up for GPU throughput when multiple people hit the same model at once.</p><p><em>Ollama and LM Studio are experience layers. llama.cpp and MLX are engines. vLLM is its own animal.</em></p><p>Here’s the cheat sheet version:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*5aApGaM75Rjk6FkE_1yFzQ.png" /></figure><p><strong>My rule of thumb: </strong>start on Ollama. The moment you notice the GPU sitting idle between requests because five people are hitting it at once, that’s your signal to graduate to vLLM. Don’t reach for vLLM on day one — it’s like buying a delivery van to pick up your own groceries.</p><h3>How Do You Even Pick a Model That Fits Your Machine?</h3><p>This is the part everyone skips, and it’s why so many people’s first local LLM experience is a wall of red CUDA out of memory text.</p><p>Your <strong>VRAM</strong> is your garage. You cannot park a truck in a space built for a hatchback, no matter how much you want to.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*Qfd9Tg66Spc8Fay9HbmfmQ.png" /></figure><p>The rule of thumb that will save you an evening of frustration:</p><p><em>VRAM needed (GB) ≈ parameters (in billions) × 0.6 — at 4-bit quantization.</em></p><p>So a 7B model needs roughly 4–5 GB, a 27B model wants ~16 GB, and a 70B model is a 40 GB+ conversation (read: dual GPUs, or a very generous Mac). And that’s just the weights — don’t forget the KV cache, which grows with your context window and can quietly eat another 10–20% on top, more if you’re running long contexts.</p><p>Two more things nobody tells you upfront:</p><p>1. <strong>Bigger-but-more-quantized usually beats smaller-but-full-precision.</strong> A 70B model at 4-bit will typically out-argue a 7B model at full FP16, despite taking up similar disk space. Go as large as your VRAM allows, then reduce precision — not the other way around.</p><p>2. <strong>Apple Silicon is the sleeper pick.</strong> Unified memory means your RAM is your VRAM. An M-series Mac with 64 GB can comfortably run models that would otherwise want a data-center card.</p><h3>Model Optimization 101: Putting Your AI On a Diet</h3><p>Here’s the section people actually came for. “Optimization” gets thrown around like it’s one thing — it’s really a toolbox, and quantization is just the first (and most important) tool in it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*8lAUUeHoJxLjySKJIZZCqA.png" /></figure><p><strong>Quantization, </strong>in one sentence: neural network weights are normally stored as 16-bit decimals. Quantization rounds them into fewer, chunkier buckets — 8-bit, or 4-bit — so the file gets smaller and the math gets faster. Same brain, fewer decimal places.</p><p>The surprising part is <em>how little</em> you lose. A 7B model at Q4_K_M keeps roughly 92% of its full-precision quality while shrinking from ~14 GB down to ~4 GB. You’re not lobotomizing the model — you’re putting it through a very effective diet plan, and it’s still funny and mostly right about most things.</p><p>But — and this is the bit tutorials gloss over — <strong>not all quantization is the same recipe.</strong> Here’s the actual decision table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/965/1*dbktsIjJUxNW6I75VA6S2w.png" /></figure><p>The “K” in Q4_K_M isn’t decoration, by the way — it stands for a mixed-precision trick. Attention layers (the parts doing the heavy lifting on meaning) get more bits; feed-forward layers get fewer. It’s less “shrink everything equally” and more “give the important organs more oxygen.” That’s why K-quants punch above their file size.</p><p><strong>My actual advice, condensed:</strong></p><p>• Running through Ollama or llama.cpp? Use <strong>GGUF, Q4_K_M</strong>. Don’t overthink it.</p><p>• Serving a GPU-only production endpoint with vLLM? Use <strong>AWQ</strong>.</p><p>• Fine-tuning with QLoRA? <strong>bitsandbytes</strong>, 4-bit, then merge the adapter back in.</p><p>• Chasing the absolute last drop of NVIDIA throughput and don’t care about anything else? <strong>GPTQ</strong>.</p><h3>Beyond Quantization: The Other Tricks Up Its Sleeve</h3><p>Quantization shrinks the model. These next three make the serving smarter — and this is where “deployment” and “optimization” actually start to blur into each other.</p><p><strong>Continuous batching + PagedAttention</strong> — this is vLLM’s headline trick, and the parking-garage analogy is the cleanest way to explain it: instead of reserving an entire parking lot (a fixed memory block) for every single car (request) regardless of how long it stays, PagedAttention hands out memory in small pages, on demand, and reclaims them the moment a request finishes. That’s how vLLM squeezes 2–4x the throughput out of the same GPU under concurrent load.</p><p><strong>Speculative decoding</strong> — my favorite one to explain, because it’s just office politics:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*VPtIbCD0h2cJc7TT2JexBQ.png" /></figure><p>A small, fast draft model guesses several tokens ahead in one go — like an intern drafting a whole paragraph before anyone’s checked a single sentence. The big, slow target model then verifies all of those guesses in one parallel pass, instead of writing token-by-token from scratch. Most guesses get accepted for free. Only the wrong ones get rewritten. You get the target model’s quality at closer to the draft model’s speed.</p><p><strong>Context and KV cache budgeting</strong> — the quiet VRAM killer. Every token you keep in context stays resident in the KV cache, and it grows linearly with context length. A model that comfortably fits in 8 GB at a 4K context window can blow past 12 GB at 32K. If your local setup runs fine on short prompts but falls over the moment you paste in a long document, this is almost always why.</p><h3>Let’s Actually Run Something</h3><p>Enough theory — three commands that will get you from zero to a locally-served model, one per tool:</p><p><strong>Ollama (the “just make it work” path):</strong></p><pre># pull a 4-bit quantized model and chat with it immediately<br>ollama pull qwen3.5:7b<br>ollama run qwen3.5:7b<br> <br># or serve it as an OpenAI-compatible API on localhost:11434<br>ollama serve</pre><p><strong>llama.cpp (maximum control over quantization and hardware split):</strong></p><pre># split layers between GPU and CPU, serve an OpenAI-compatible endpoint<br>./llama-server \<br>  -m qwen3.5-7b-q4_k_m.gguf \<br>  -ngl 28 \<br>  -c 8192 \<br>  --host 0.0.0.0 --port 8080</pre><p><strong>vLLM (serving a team, GPU-only, AWQ for the quality-per-token sweet spot):</strong></p><pre>pip install vllm<br> <br>vllm serve TheBloke/Qwen3.5-7B-AWQ \<br>  --quantization awq \<br>  --max-model-len 8192 \<br>  --port 8000</pre><p>Same underlying idea — model in, API out — but notice how the <em>knobs</em> change: Ollama hides the quantization decision from you, llama.cpp hands you the -ngl layer-split lever directly, and vLLM cares about — max-model-len because it’s optimizing for many requests, not one.</p><h3>A Decision Framework: Which Setup Should You Actually Use?</h3><p>If you remember nothing else from this post, remember this flow:</p><p>• <strong>Just want to chat with a model on your laptop? </strong>→ Ollama. GGUF Q4_K_M. Done in five minutes.</p><p>• <strong>On a Mac and want the fastest possible local inference? </strong>→ Ollama (it uses MLX under the hood on Apple Silicon now) or MLX directly.</p><p>• <strong>Need to serve a model to your team, or multiple concurrent users? </strong>→ vLLM, AWQ quantization, watch your p95 latency drop.</p><p>• <strong>Want the absolute lowest-level control — custom quantization, weird hardware, embedded deployment? </strong>→ llama.cpp, directly.</p><p>• <strong>Fine-tuning on your own data before deploying? </strong>→ bitsandbytes + QLoRA, merge, then quantize to GGUF or AWQ for serving.</p><p>• <strong>Prompt works fine short but crashes on long documents? </strong>→ It’s the KV cache. Budget 10–20% extra VRAM per doubling of context length, or drop to a smaller model.</p><h3>Key Takeaways</h3><ul><li>Local LLMs make the most financial sense once usage is frequent, private, or customized — not for the occasional one-off query.</li><li>Ollama, llama.cpp, LM Studio, MLX, and vLLM solve <em>different</em> problems. Picking the wrong one for your use case is the #1 reason people give up.</li><li>VRAM is the real constraint. Rule of thumb: <strong>GB needed ≈ params (in billions) × 0.6</strong> at 4-bit — and budget extra for the KV cache.</li><li>Quantization (GGUF/AWQ/GPTQ) barely dents quality at 4-bit but slashes size by ~75%. Go bigger-and-quantized over smaller-and-full-precision.</li><li>Beyond quantization, continuous batching and speculative decoding are where the real production-grade speedups live.</li></ul><h3>Final Thought</h3><p>Everyone’s first instinct is to treat “running an LLM locally” as a single checkbox — download, run, done. It isn’t. It’s a stack of decisions, and every layer of that stack has its own local vs. cloud trade-off buried inside it.</p><p>But here’s the thing about buying the car instead of Ubering forever: the first week is annoying — figuring out VRAM, arguing with quantization formats, reading error logs longer than this article. And then one day it’s just… parked in your garage, quietly working, costing you nothing but electricity.</p><p>That’s the whole pitch. Stop renting the ride. Learn to drive.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*To_L5Xe1DlNdbnPnkyCl2w.png" /></figure><p><em>Llm Deployment · Local Llm · Model Optimization · Quantization · Genai</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5b50322c2f1" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/local-llm-deployment-model-optimization-why-i-bought-the-car-instead-of-taking-ubers-forever-a5b50322c2f1">Local LLM Deployment &amp; Model Optimization: Why I Bought the Car Instead of Taking Ubers Forever</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Local LLM Deployment & Model Optimization: Why I Bought the Car Instead of Taking Ubers Forever]]></title>
            <link>https://medium.com/@purusharthyadav.py/local-llm-deployment-model-optimization-why-i-bought-the-car-instead-of-taking-ubers-forever-271e44e06149?source=rss-bcc23fb92681------2</link>
            <guid isPermaLink="false">https://medium.com/p/271e44e06149</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Purusharth Yaduwanshi]]></dc:creator>
            <pubDate>Tue, 11 Aug 2026 09:37:13 GMT</pubDate>
            <atom:updated>2026-08-11T09:37:56.848Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Cloud APIs rent you intelligence. Local LLMs let you own it, maintenance included.</em></p><p>When I first started experimenting with open-weight models, I assumed “running an LLM locally” meant one thing: download a model, point some Python at it, pray to the CUDA gods.</p><p>It took exactly one out-of-memory crash to realize how wrong that was.</p><p>Local LLM deployment isn’t one skill. It’s three, stacked on top of each other — <strong>picking the right tool, picking a model that actually fits your hardware, and squeezing that model until it’s fast enough to be worth the trouble.</strong> Most tutorials only teach the first one, run ollama run once, and call it a day.</p><p>This is the version nobody gave me. Let’s fix that.</p><h3>Wait… Why Would Anyone Run an LLM at Home?</h3><p>Here’s the analogy I keep coming back to: using a cloud API is like taking an Uber everywhere. Running a model locally is like buying a car.</p><p>Ubers are wonderful when you need one ride. No maintenance, no insurance, works in any city. But take one every single day and the bill quietly turns into a second rent payment. Buying a car front-loads the pain, you pay a lot upfront, and then you’re stuck doing your own oil changes but after that, every ride is basically free.</p><p>That’s the entire economic argument for local LLMs, and the chart below is the only slide you actually need in that meeting:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*jWX6qye5yTFkQCAvdUiZFQ.png" /></figure><p>Cost isn’t the only reason people go local, though. The honest list looks like this:</p><p>• <strong>Privacy</strong> — nothing leaves your machine. Great for anything you wouldn’t paste into a public chatbot: contracts, patient notes, your unreleased startup idea.</p><p>• <strong>No rate limits, no vendor mood swings</strong> — no “the API is degraded today” emails.</p><p>• <strong>Offline is a feature, not a compromise</strong> — flights, air-gapped networks, client sites with no Wi-Fi.</p><p>• <strong>You can actually poke at it</strong> — fine-tune it, quantize it, bolt weird tools onto it. Try doing that to GPT-5.</p><p>• <strong>You learn what’s actually happening</strong> — attention, KV caches, batching — instead of it all being someone else’s black box.</p><p>None of this means cloud APIs are bad. If you need a frontier-class model for one gnarly reasoning task once a week, Ubering is objectively the right call. Local LLMs make sense once usage is <em>frequent, private, or customized</em> — the break-even point in that chart above is not a joke, it’s a spreadsheet you should actually build before buying a GPU.</p><h3>Meet Your Mechanics: The Local LLM Toolbox</h3><p>Here’s where most people get stuck, because in 2026 “just run it locally” now has about five competing answers, and they are not interchangeable:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*Yo8qEqbEY7SGm3Ho748k4g.png" /></figure><p>Think of it as four layers, foundation to surface:</p><p>• <strong>Hardware</strong> (GPU / CPU / unified memory) — where electricity actually becomes tokens.</p><p>• <strong>Engine</strong> (llama.cpp, MLX) — the thing that does the actual matrix math. Lowest-level, highest control, zero hand-holding.</p><p>• <strong>Wrapper</strong> (Ollama, LM Studio) — the friendly dealership. One command pulls, quantizes, and serves a model with an OpenAI-compatible API. This is 90% of what people actually want.</p><p>• <strong>Serving system</strong> (vLLM) — not really a “wrapper,” more like a fleet manager. Built ground-up for GPU throughput when multiple people hit the same model at once.</p><p><em>Ollama and LM Studio are experience layers. llama.cpp and MLX are engines. vLLM is its own animal.</em></p><p>Here’s the cheat sheet version:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*5aApGaM75Rjk6FkE_1yFzQ.png" /></figure><p><strong>My rule of thumb: </strong>start on Ollama. The moment you notice the GPU sitting idle between requests because five people are hitting it at once, that’s your signal to graduate to vLLM. Don’t reach for vLLM on day one — it’s like buying a delivery van to pick up your own groceries.</p><h3>How Do You Even Pick a Model That Fits Your Machine?</h3><p>This is the part everyone skips, and it’s why so many people’s first local LLM experience is a wall of red CUDA out of memory text.</p><p>Your <strong>VRAM</strong> is your garage. You cannot park a truck in a space built for a hatchback, no matter how much you want to.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*Qfd9Tg66Spc8Fay9HbmfmQ.png" /></figure><p>The rule of thumb that will save you an evening of frustration:</p><p><em>VRAM needed (GB) ≈ parameters (in billions) × 0.6 — at 4-bit quantization.</em></p><p>So a 7B model needs roughly 4–5 GB, a 27B model wants ~16 GB, and a 70B model is a 40 GB+ conversation (read: dual GPUs, or a very generous Mac). And that’s just the weights — don’t forget the KV cache, which grows with your context window and can quietly eat another 10–20% on top, more if you’re running long contexts.</p><p>Two more things nobody tells you upfront:</p><p>1. <strong>Bigger-but-more-quantized usually beats smaller-but-full-precision.</strong> A 70B model at 4-bit will typically out-argue a 7B model at full FP16, despite taking up similar disk space. Go as large as your VRAM allows, then reduce precision — not the other way around.</p><p>2. <strong>Apple Silicon is the sleeper pick.</strong> Unified memory means your RAM is your VRAM. An M-series Mac with 64 GB can comfortably run models that would otherwise want a data-center card.</p><h3>Model Optimization 101: Putting Your AI On a Diet</h3><p>Here’s the section people actually came for. “Optimization” gets thrown around like it’s one thing — it’s really a toolbox, and quantization is just the first (and most important) tool in it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*8lAUUeHoJxLjySKJIZZCqA.png" /></figure><p><strong>Quantization, </strong>in one sentence: neural network weights are normally stored as 16-bit decimals. Quantization rounds them into fewer, chunkier buckets — 8-bit, or 4-bit — so the file gets smaller and the math gets faster. Same brain, fewer decimal places.</p><p>The surprising part is <em>how little</em> you lose. A 7B model at Q4_K_M keeps roughly 92% of its full-precision quality while shrinking from ~14 GB down to ~4 GB. You’re not lobotomizing the model — you’re putting it through a very effective diet plan, and it’s still funny and mostly right about most things.</p><p>But — and this is the bit tutorials gloss over — <strong>not all quantization is the same recipe.</strong> Here’s the actual decision table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/965/1*dbktsIjJUxNW6I75VA6S2w.png" /></figure><p>The “K” in Q4_K_M isn’t decoration, by the way — it stands for a mixed-precision trick. Attention layers (the parts doing the heavy lifting on meaning) get more bits; feed-forward layers get fewer. It’s less “shrink everything equally” and more “give the important organs more oxygen.” That’s why K-quants punch above their file size.</p><p><strong>My actual advice, condensed:</strong></p><p>• Running through Ollama or llama.cpp? Use <strong>GGUF, Q4_K_M</strong>. Don’t overthink it.</p><p>• Serving a GPU-only production endpoint with vLLM? Use <strong>AWQ</strong>.</p><p>• Fine-tuning with QLoRA? <strong>bitsandbytes</strong>, 4-bit, then merge the adapter back in.</p><p>• Chasing the absolute last drop of NVIDIA throughput and don’t care about anything else? <strong>GPTQ</strong>.</p><h3>Beyond Quantization: The Other Tricks Up Its Sleeve</h3><p>Quantization shrinks the model. These next three make the serving smarter — and this is where “deployment” and “optimization” actually start to blur into each other.</p><p><strong>Continuous batching + PagedAttention</strong> — this is vLLM’s headline trick, and the parking-garage analogy is the cleanest way to explain it: instead of reserving an entire parking lot (a fixed memory block) for every single car (request) regardless of how long it stays, PagedAttention hands out memory in small pages, on demand, and reclaims them the moment a request finishes. That’s how vLLM squeezes 2–4x the throughput out of the same GPU under concurrent load.</p><p><strong>Speculative decoding</strong> — my favorite one to explain, because it’s just office politics:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*VPtIbCD0h2cJc7TT2JexBQ.png" /></figure><p>A small, fast draft model guesses several tokens ahead in one go — like an intern drafting a whole paragraph before anyone’s checked a single sentence. The big, slow target model then verifies all of those guesses in one parallel pass, instead of writing token-by-token from scratch. Most guesses get accepted for free. Only the wrong ones get rewritten. You get the target model’s quality at closer to the draft model’s speed.</p><p><strong>Context and KV cache budgeting</strong> — the quiet VRAM killer. Every token you keep in context stays resident in the KV cache, and it grows linearly with context length. A model that comfortably fits in 8 GB at a 4K context window can blow past 12 GB at 32K. If your local setup runs fine on short prompts but falls over the moment you paste in a long document, this is almost always why.</p><h3>Let’s Actually Run Something</h3><p>Enough theory — three commands that will get you from zero to a locally-served model, one per tool:</p><p><strong>Ollama (the “just make it work” path):</strong></p><pre># pull a 4-bit quantized model and chat with it immediately<br>ollama pull qwen3.5:7b<br>ollama run qwen3.5:7b<br> <br># or serve it as an OpenAI-compatible API on localhost:11434<br>ollama serve</pre><p><strong>llama.cpp (maximum control over quantization and hardware split):</strong></p><pre># split layers between GPU and CPU, serve an OpenAI-compatible endpoint<br>./llama-server \<br>  -m qwen3.5-7b-q4_k_m.gguf \<br>  -ngl 28 \<br>  -c 8192 \<br>  --host 0.0.0.0 --port 8080</pre><p><strong>vLLM (serving a team, GPU-only, AWQ for the quality-per-token sweet spot):</strong></p><pre>pip install vllm<br> <br>vllm serve TheBloke/Qwen3.5-7B-AWQ \<br>  --quantization awq \<br>  --max-model-len 8192 \<br>  --port 8000</pre><p>Same underlying idea — model in, API out — but notice how the <em>knobs</em> change: Ollama hides the quantization decision from you, llama.cpp hands you the -ngl layer-split lever directly, and vLLM cares about — max-model-len because it’s optimizing for many requests, not one.</p><h3>A Decision Framework: Which Setup Should You Actually Use?</h3><p>If you remember nothing else from this post, remember this flow:</p><p>• <strong>Just want to chat with a model on your laptop? </strong>→ Ollama. GGUF Q4_K_M. Done in five minutes.</p><p>• <strong>On a Mac and want the fastest possible local inference? </strong>→ Ollama (it uses MLX under the hood on Apple Silicon now) or MLX directly.</p><p>• <strong>Need to serve a model to your team, or multiple concurrent users? </strong>→ vLLM, AWQ quantization, watch your p95 latency drop.</p><p>• <strong>Want the absolute lowest-level control — custom quantization, weird hardware, embedded deployment? </strong>→ llama.cpp, directly.</p><p>• <strong>Fine-tuning on your own data before deploying? </strong>→ bitsandbytes + QLoRA, merge, then quantize to GGUF or AWQ for serving.</p><p>• <strong>Prompt works fine short but crashes on long documents? </strong>→ It’s the KV cache. Budget 10–20% extra VRAM per doubling of context length, or drop to a smaller model.</p><h3>Key Takeaways</h3><ul><li>Local LLMs make the most financial sense once usage is frequent, private, or customized — not for the occasional one-off query.</li><li>Ollama, llama.cpp, LM Studio, MLX, and vLLM solve <em>different</em> problems. Picking the wrong one for your use case is the #1 reason people give up.</li><li>VRAM is the real constraint. Rule of thumb: <strong>GB needed ≈ params (in billions) × 0.6</strong> at 4-bit — and budget extra for the KV cache.</li><li>Quantization (GGUF/AWQ/GPTQ) barely dents quality at 4-bit but slashes size by ~75%. Go bigger-and-quantized over smaller-and-full-precision.</li><li>Beyond quantization, continuous batching and speculative decoding are where the real production-grade speedups live.</li></ul><h3>Final Thought</h3><p>Everyone’s first instinct is to treat “running an LLM locally” as a single checkbox — download, run, done. It isn’t. It’s a stack of decisions, and every layer of that stack has its own local vs. cloud trade-off buried inside it.</p><p>But here’s the thing about buying the car instead of Ubering forever: the first week is annoying — figuring out VRAM, arguing with quantization formats, reading error logs longer than this article. And then one day it’s just… parked in your garage, quietly working, costing you nothing but electricity.</p><p>That’s the whole pitch. Stop renting the ride. Learn to drive.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*To_L5Xe1DlNdbnPnkyCl2w.png" /></figure><p><em>Llm Deployment · Local Llm · Model Optimization · Quantization · Genai</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=271e44e06149" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What No One Tells You About Evaluating LLM Applications]]></title>
            <link>https://medium.com/@purusharthyadav.py/what-no-one-tells-you-about-evaluating-llm-applications-618cc6bba7ec?source=rss-bcc23fb92681------2</link>
            <guid isPermaLink="false">https://medium.com/p/618cc6bba7ec</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[llmops]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[llm-evaluation]]></category>
            <category><![CDATA[llm-evaluation-metrics]]></category>
            <dc:creator><![CDATA[Purusharth Yaduwanshi]]></dc:creator>
            <pubDate>Wed, 21 Jan 2026 11:55:58 GMT</pubDate>
            <atom:updated>2026-01-21T11:55:58.488Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Accuracy is easy to measure. Intelligence is not.</em></p><p>When I first started building applications using Large Language Models (LLMs), evaluation felt deceptively simple.</p><p>If the output <em>looked good</em>, I assumed the system was working.</p><p>It didn’t take long to realize how wrong that assumption was.</p><p>Evaluating LLM applications is one of the <strong>hardest and most misunderstood parts of GenAI engineering</strong> — and it’s something very few tutorials talk about seriously.</p><p>This blog is about what I learned the hard way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*4OssMNedXoHSh1pBj8cHew.png" /></figure><h3>The Illusion of “It Looks Correct”</h3><p>Traditional machine learning gives us comfort:</p><ul><li>Accuracy</li><li>Precision / Recall</li><li>RMSE</li><li>AUC</li></ul><p>LLM applications give us… vibes.</p><p>If you ask:</p><blockquote>“Does this answer look reasonable?”</blockquote><p>You’re already in dangerous territory.</p><p>Two responses can <em>both look good</em> — yet one can be:</p><ul><li>Factually wrong</li><li>Misleading</li><li>Overconfident</li><li>Inconsistent</li><li>Unsafe in production</li></ul><p><strong>Visual inspection does not scale.</strong></p><p>And worse — it hides failure modes.</p><h3>LLM Evaluation Is Not Model Evaluation</h3><p>One of the biggest misconceptions I had was treating LLM evaluation like model benchmarking.</p><p>But most real-world LLM systems are not just:</p><blockquote>Prompt → Model → Output</blockquote><p>They are <strong>systems</strong>, often involving:</p><ul><li>User input</li><li>Prompt templates</li><li>Retrieval (RAG)</li><li>Embeddings &amp; vector databases</li><li>Context filtering</li><li>Post-processing logic</li></ul><p>When an answer is wrong, <em>where did it fail</em>?</p><ul><li>Retrieval returned irrelevant documents?</li><li>Prompt instructions were unclear?</li><li>Context window was overloaded?</li><li>Model hallucinated confidently?</li></ul><p>Without proper evaluation, you’ll never know.</p><h3>The First Mistake I Made: Relying on Single “Correct” Answers</h3><p>In classical NLP tasks, we often have ground truth labels.<br>LLMs break that assumption.</p><p>For many tasks:</p><ul><li>There is <strong>no single correct answer</strong></li><li>Multiple answers can be acceptable</li><li>Quality is subjective but still measurable</li></ul><p>For example:</p><blockquote>“Summarize this document for a business stakeholder.”</blockquote><p>What does <em>correct</em> even mean here?</p><p>This forced me to shift from <strong>exact-match thinking</strong> to <strong>criteria-based evaluation</strong>.</p><h3>What Actually Matters in LLM Evaluation</h3><p>Over time, I found that good LLM evaluation focuses on <strong>dimensions</strong>, not scores.<br>Some of the most important ones:</p><h3>1. Faithfulness</h3><p>Is the output grounded in the provided context, or is the model hallucinating?</p><p>Especially critical for:</p><ul><li>RAG systems</li><li>Enterprise knowledge bases</li><li>Legal / medical / financial applications</li></ul><p>A fluent answer that’s unfaithful is worse than no answer.</p><h3>2. Relevance</h3><p>Does the response actually answer the user’s question?</p><p>LLMs are great at sounding helpful — even when they drift.</p><p>I’ve seen answers that were:</p><ul><li>Well-written</li><li>Confident</li><li>Completely irrelevant</li></ul><p>Relevance checks matter more than style.</p><h3>3. Completeness</h3><p>Does the answer miss key information?<br>Partial answers are dangerous because they appear correct at first glance.</p><p>This is especially important for:</p><ul><li>Decision support systems</li><li>Multi-step reasoning tasks</li></ul><h3>4. Consistency</h3><p>Does the model give similar answers to semantically similar questions?</p><p>Inconsistency is a silent killer in production systems.<br>Users lose trust very quickly.</p><h3>Why Automated Metrics Alone Are Not Enough</h3><p>Yes, we now have:</p><ul><li>LLM-as-a-judge approaches</li><li>Semantic similarity scores</li><li>Evaluation frameworks and libraries</li></ul><p>They are useful.<br>But they are not magic.</p><p>Automated evaluators:</p><ul><li>Inherit biases from models</li><li>Can miss subtle factual errors</li><li>Often overestimate quality</li></ul><p>The best results I’ve seen come from <strong>hybrid evaluation</strong>:</p><ul><li>Automated checks for scale</li><li>Human review for depth and edge cases</li></ul><h3>The Turning Point: Evaluating the Pipeline, Not Just Outputs</h3><p>What truly improved my LLM applications was changing <em>what</em> I evaluated.</p><p>Instead of asking:</p><blockquote>“Is the final answer good?”</blockquote><p>I started asking:</p><ul><li>Did retrieval fetch the right documents?</li><li>Was the context concise and relevant?</li><li>Did the prompt constrain the model correctly?</li><li>Did post-processing introduce errors?</li></ul><p>This system-level thinking made debugging <strong>far easier</strong> and results <strong>far more reliable</strong>.</p><h3>A Practical Evaluation Workflow That Worked for Me</h3><p>Here’s a simplified workflow I now follow:</p><p><strong>a. Define evaluation criteria clearly</strong></p><ul><li>Faithfulness</li><li>Relevance</li><li>Completeness</li><li>Safety (if applicable)</li></ul><p><strong>b. Create a small but high-quality evaluation set</strong></p><ul><li>Real user queries</li><li>Edge cases</li><li>Failure examples</li></ul><p><strong>c. Evaluate each component</strong></p><ul><li>Retrieval quality</li><li>Prompt behavior</li><li>Final response</li></ul><p><strong>d. Track regressions</strong></p><ul><li>Small prompt changes can break everything</li><li>Version your prompts and evaluation data</li></ul><p>This approach feels slower at first — but it saves enormous time later.</p><h3>What Most Tutorials Don’t Tell You</h3><p>Here’s the uncomfortable truth:</p><blockquote>If you can’t evaluate your LLM application properly, you don’t really understand it.</blockquote><p>Evaluation is not an afterthought.<br>It <em>is</em> the engineering.</p><p>This is where GenAI work stops being “prompt tinkering” and starts becoming <strong>real system design</strong>.</p><h3>Key Takeaways</h3><ul><li>LLM evaluation is fundamentally different from traditional ML evaluation</li><li>“Looks good” is not a metric</li><li>Focus on <strong>faithfulness, relevance, completeness, and consistency</strong></li><li>Evaluate the <strong>entire system</strong>, not just the final output</li><li>Hybrid (automated + human) evaluation works best in practice</li></ul><h3>Final Thought</h3><p>Building LLM applications is exciting.</p><p>But <strong>evaluating them properly</strong> is what separates:</p><ul><li>Demos from production systems</li><li>Hobby projects from engineering work</li></ul><p>And that’s a difference recruiters notice very quickly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*1J_VNIt9Vvn4gFvYb9KyxA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=618cc6bba7ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DeepSeek mHC Explained: How Manifold-Constrained Hyper-Connections Redefine Residual Connections in…]]></title>
            <link>https://medium.com/@purusharthyadav.py/deepseek-mhc-explained-how-manifold-constrained-hyper-connections-redefine-residual-connections-in-1b27c84b0ae4?source=rss-bcc23fb92681------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b27c84b0ae4</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deepseek]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Purusharth Yaduwanshi]]></dc:creator>
            <pubDate>Sat, 03 Jan 2026 15:33:42 GMT</pubDate>
            <atom:updated>2026-01-03T15:33:42.982Z</atom:updated>
            <content:encoded><![CDATA[<h3>DeepSeek mHC Explained: How Manifold-Constrained Hyper-Connections Redefine Residual Connections in LLMs</h3><h3>Introduction</h3><p>Scaling large language models has followed a familiar path: <strong>more layers, more parameters, more compute</strong>. While this strategy has delivered impressive gains, it has also exposed a fundamental architectural limitation — <strong>how information flows through very deep networks</strong>.</p><p>DeepSeek’s recent paper, <strong><em>mHC: Manifold-Constrained Hyper-Connections</em></strong>, revisits one of the most foundational ideas in deep learning: <strong>residual connections</strong>. Rather than proposing another optimization trick or scaling law, the paper asks a deeper question:</p><blockquote>Can we redesign residual pathways to be more expressive without sacrificing training stability?</blockquote><p>This article provides an intuition-first walkthrough of the paper, explaining <strong>what mHC is</strong>, <strong>why it matters</strong>, and <strong>how it enables stable scaling in large language models (LLMs)</strong>.</p><h3>Why Residual Connections Became a Bottleneck in LLMs</h3><p>Residual connections were introduced with <strong>ResNet</strong> and later adopted almost unchanged by <strong>Transformers</strong>. Their purpose is simple but powerful: preserve gradient flow in deep networks.</p><p>A standard residual connection is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/1*Lj37nVxfVGddPCeKR-j0Mg.png" /></figure><p>This identity path ensures:</p><ul><li>Stable gradients</li><li>Easier optimization</li><li>Deep networks that actually train</li></ul><p>For years, this design worked exceptionally well.</p><p>But <strong>modern LLMs are no longer small</strong>.</p><p>As depth and width scale into the billions of parameters, a <strong>single residual stream becomes a bottleneck</strong>. All information — regardless of abstraction level — must pass through one narrow identity path, even when the model has the capacity to process more.</p><p>This raises a fundamental architectural question:</p><blockquote><strong><em>Can we widen the residual pathway without breaking training stability?</em></strong></blockquote><p>DeepSeek’s answer is <strong>Hyper-Connections</strong> — and more importantly, <strong>mHC</strong>.</p><h3>Hyper-Connections: A Powerful Idea That Breaks at Scale</h3><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*YE0vyhN3jDEWYUcw.png" /></figure><p><strong>Hyper-Connections (HC)</strong> generalize residual connections by introducing <strong>multiple parallel residual streams</strong> instead of one.</p><p>Instead of:</p><pre>single residual path → add → next layer</pre><p>HC enables:</p><ul><li>Multiple residual streams</li><li>Learnable mixing between streams</li><li>Higher information bandwidth across layers</li></ul><h3>Why Hyper-Connections Look Ideal</h3><p>On paper, HC offers:</p><ul><li>Higher representational capacity</li><li>Better feature reuse</li><li>Minimal increase in FLOPs</li></ul><p>However, in large-scale models, HC fails <strong>catastrophically</strong>.</p><h3>The Core Failure Mode of Hyper-Connections</h3><p>Standard residual connections rely on <strong>identity mappings</strong>, which are inherently stable.</p><p>Hyper-Connections replace identity paths with <strong>learnable mixing matrices</strong>. As model depth increases:</p><ul><li>Small amplification errors compound</li><li>Signal norms explode or vanish</li><li>Gradients become numerically unstable</li></ul><p>DeepSeek reports that in a <strong>27B-parameter model</strong>, unconstrained HC caused <strong>signal amplification exceeding 3000×</strong>, leading to complete training divergence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*9jgInJhK7tV8ZOUL.png" /></figure><p>This is not a tuning problem.<br> It is a <strong>structural instability</strong>.</p><h3>What Is DeepSeek mHC?</h3><p><strong>mHC (Manifold-Constrained Hyper-Connections)</strong> resolves this instability by constraining how residual streams interact.</p><p>Instead of arbitrary mixing matrices, mHC forces them to lie on a <strong>mathematically well-behaved manifold</strong>.</p><h3>The Key Constraint: Birkhoff Polytope</h3><p>Each residual mixing matrix is constrained to be <strong>doubly stochastic</strong>:</p><ul><li>Each row sums to 1</li><li>Each column sums to 1</li></ul><p>These constraints are enforced using the <strong>Sinkhorn–Knopp algorithm</strong> during training.</p><p>This seemingly small change has profound implications.</p><h3>Why Manifold Constraints Restore Stability</h3><h3>1️ Guaranteed Norm Preservation</h3><p>Doubly stochastic matrices preserve signal magnitude.</p><p>No matter how deep the model becomes:</p><ul><li>Residual streams do <strong>not explode</strong></li><li>Signals do <strong>not collapse</strong></li></ul><p>This restores the core benefit of identity residuals — <strong>stable gradient flow</strong> — while allowing richer interactions.</p><h3>2️ Controlled Information Exchange</h3><p>mHC allows residual streams to interact, but <strong>prevents dominance</strong>.</p><p>Each stream:</p><ul><li>Contributes proportionally</li><li>Receives balanced information</li></ul><p>The residual pathway becomes a <strong>stable feature fusion layer</strong>, not a numerical risk.</p><h3>3️ Depth-Independent Stability</h3><p>Unlike standard HC, stability in mHC does <strong>not degrade with depth</strong>.</p><p>This property is essential for:</p><ul><li>Extremely deep transformers</li><li>Next-generation LLM scaling</li></ul><h3>Making mHC Practical at Scale</h3><p>Widening residual streams increases memory traffic, which could make mHC impractical without system-level optimizations.</p><p>DeepSeek addresses this directly.</p><h4><strong>- Kernel Fusion with TileLang</strong></h4><p>Multiple operations are fused into a single GPU kernel, reducing memory I/O.</p><h4>- Selective Activation Recomputation</h4><p>Some activations are discarded during the forward pass and recomputed during backpropagation to save memory.</p><h4><strong>- DualPipe Overlapping</strong></h4><p>Communication and computation are overlapped, hiding data movement latency.</p><h3>The Result</h3><p>A <strong>4× wider residual stream</strong> adds only <strong>~6.7% training time overhead</strong>.</p><p>This is the difference between a theoretical idea and a production-ready architecture.</p><h3>Empirical Results on Large-Scale LLMs</h3><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*BjBSo0VYKHXqpQUY.png" /></figure><p>DeepSeek evaluated mHC on a <strong>27B-parameter transformer</strong>.</p><p><strong>Key Findings:</strong></p><ul><li>Standard Hyper-Connections showed severe loss spikes</li><li>Gradients destabilized early in training</li><li>mHC remained stable throughout training</li></ul><p>Across benchmarks such as <strong>GSM8K</strong> and <strong>MMLU</strong>:</p><ul><li>mHC consistently outperformed standard transformer baselines</li><li>Training loss decreased smoothly</li><li>Gains were structural, not cosmetic</li></ul><h3>Why DeepSeek mHC Matters for the Future of LLMs</h3><p>LLM progress is no longer just about:</p><ul><li>Adding layers</li><li>Increasing parameter counts</li><li>Scaling data</li></ul><p>It is about <strong>architectural discipline</strong> — how information flows through the model.</p><p>DeepSeek mHC demonstrates that:</p><ul><li>Residual topology matters</li><li>Mathematical constraints can unlock new architectures</li><li>Stability and expressiveness do <strong>not</strong> have to trade off</li></ul><p>This work bridges:</p><ul><li>Manifold geometry</li><li>Transformer architecture</li><li>GPU systems engineering</li></ul><p><strong>mHC is not an incremental tweak — it is a blueprint for scalable LLM design.</strong></p><h3>Final Thoughts</h3><p>As models continue to scale, brute force alone will not be enough. Architectural insights like <strong>mHC</strong> show that <strong>better math often beats more parameters</strong>.</p><p>DeepSeek’s work reminds us that the next breakthroughs in AI may come not from scaling harder — but from <strong>designing smarter.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EGqxn6o0h342X_fbNO3g3g.png" /><figcaption>Stability is a feature, not a hyperparameter.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b27c84b0ae4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Memory Management & State in Google ADK: Practical Patterns for Real-World AI Agents]]></title>
            <link>https://medium.com/@purusharthyadav.py/memory-management-state-in-google-adk-practical-patterns-for-real-world-ai-agents-e62953ba71e5?source=rss-bcc23fb92681------2</link>
            <guid isPermaLink="false">https://medium.com/p/e62953ba71e5</guid>
            <category><![CDATA[google-adk]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[google-ai]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Purusharth Yaduwanshi]]></dc:creator>
            <pubDate>Wed, 10 Dec 2025 06:02:05 GMT</pubDate>
            <atom:updated>2025-12-10T06:02:05.021Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_bCHVAparj46cle4h62jJA.png" /><figcaption>How AI agents think: the hidden structure behind memory, state, and context.</figcaption></figure><p>When people start building agents, the first problem they hit is not the LLM, not the routing logic — it’s <strong>memory</strong>.</p><p>How much context should an agent remember?<br>Where should this memory live?<br>How do I prevent it from hallucinating past events?<br>How do I scale memory when 10,000 users talk to the agent every day?</p><p>If you’ve tried building production agents before, you already know:<br><strong>State and memory decide whether your agent is “smart”… or completely useless.</strong></p><p>Google ADK finally gives us a clean, opinionated way to manage agent state. But most developers still use it like a “glorified prompt wrapper.” In this guide, I’ll break down how ADK handles memory, what patterns actually work in production, and how to design memory-driven agent systems that don’t break at scale.</p><h3>1. What ADK Means by “Memory”</h3><p>ADK treats memory as a <strong>structured, deterministic piece of data</strong> — not a bag of chat history.</p><p>In simple terms:</p><blockquote>Memory = Agent state that persists beyond a single LLM call.</blockquote><p>This can include:</p><p>- User profile<br>- Conversation history<br>- Pending tasks<br>- Tool outputs<br>- World state (e.g., file changes, environment updates)<br>- Derived insights (summaries, embeddings, checkpoints)</p><p>ADK lets you decide how this memory is:</p><ul><li><strong>stored</strong> (in-memory, Redis, Firestore, custom DB)</li><li><strong>updated</strong> (rules, reducers, LLM-generated updates)</li><li><strong>retrieved</strong> (filters, embeddings, time-based slicing)</li><li><strong>shared</strong> (between agents in a multi-agent system)</li></ul><p>That last part is important:<br><strong>Memory becomes a first-class citizen in your agent architecture.</strong></p><h3>2. ADK Memory Types: The Mental Model</h3><p>There are three major memory layers in ADK:</p><ol><li><strong>Short-Term Memory (Ephemeral State):<br></strong>Lives only for the duration of an agent’s operation.<br>It is used for:<br>- Task context<br>- Variables<br>- Intermediate results<br>- Tool outputs<br>Does not persist automatically.</li><li><strong>Long-Term Memory (Persistent State):<br></strong>Survives across conversations, sessions, or workflow runs.<br>Used for:<br>- User preferences<br>- Historical conversations<br>- Completed tasks<br>- Knowledge snapshots<br>- Business context<br>This is where <strong>you design the schema</strong>.</li><li><strong>Derived Memory (Generated State):<br></strong>Memory created <em>by</em> the agent:<br>- Summaries<br>- Embeddings<br>- Indexed knowledge<br>- Metadata<br>- Agent-to-agent messages<br>This is the most powerful part.<br>Agents can <strong>learn</strong>, compress, or organize memory — without human intervention.</li></ol><h3>3. Architecture Patterns That Actually Work:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zahVQ18Ko3C8qGTM" /><figcaption>Four memory architecture patterns every real production agent needs to get right.</figcaption></figure><p>Let’s get into the part most engineers struggle with: <em>choosing the right memory structure</em>.<br> Here are four battle-tested patterns.</p><h4><strong><em>Pattern A: “Rolling Window + Episodic Summary”:</em></strong></h4><p>Best for: Customer support agents, chatbots, assistants.</p><p><strong>Why:</strong><br> You don’t want to pass full conversation history into the LLM. It’s expensive and noisy.</p><p><strong>How it works:</strong></p><ul><li>Keep last <em>N</em> messages in short-term memory.</li><li>Periodically compress older messages into a summary and store in long-term memory.</li><li>Use embeddings for retrieval.</li></ul><p><strong>Benefits:</strong></p><ul><li>Stable context</li><li>Low cost</li><li>Scales nicely</li></ul><h4>Pattern B: “State Object as Truth Source”</h4><p>Best for: Workflow agents, RPA, task executors, API-heavy flows.</p><p>In this model:</p><ul><li>The agent’s <strong>state object</strong> is the single source of truth.</li><li>The LLM only updates <em>fields</em> through reducers.</li><li>All tool interactions write back to state.</li></ul><p>Example fields:</p><pre>{<br>  &quot;current_task&quot;: &quot;...&quot;,<br>  &quot;completed_steps&quot;: [...],<br>  &quot;errors&quot;: [...],<br>  &quot;results&quot;: {...}<br>}</pre><p><strong>Why it works:</strong><br> State transitions become deterministic and testable.<br> You avoid “LLM forgot what happened” problems entirely.</p><h4>Pattern C: “Shared Memory Bus” (Multi-Agent Systems)</h4><p>Best for: Multi-agent orchestration, teams of specialized agents.</p><p>ADK lets you design a shared memory architecture where:</p><ul><li>Each agent has its own private memory</li><li>A shared memory bus stores global state</li><li>Agents read/write through access policies</li></ul><p>This prevents agents from stepping on each other’s work.</p><h4>Pattern D: “Knowledge Layer + Dynamic Context”</h4><p>Best for: Enterprise agents that must remember documents, facts, policies.</p><p>Pattern structure:</p><ul><li>Long-term memory: embeddings store knowledge</li><li>Short-term memory: the current conversation</li><li>A retrieval layer selects only the relevant knowledge per request</li></ul><p>This is essentially RAG, but integrated cleanly with ADK’s memory workflow.</p><h3>4. When Memory Goes Wrong (and How to Avoid It)</h3><p>After working with multiple teams building ADK agents, the same issues repeat. Here’s what to watch out for.</p><h4>Issue 1: The agent forgets mid-task</h4><p><strong>Cause:</strong> Memory updates aren’t deterministic.<br><strong>Fix:</strong> Use explicit reducers and structured state objects.</p><h4>Issue 2: Memory grows unbounded</h4><p><strong>Cause:</strong> Raw message logs stored forever.<br><strong>Fix:</strong> Summarize aggressively + compress older memory.</p><h4>Issue 3: Agents hallucinate “past facts”</h4><p><strong>Cause:</strong> Passing too much history; LLM reinterprets.<br><strong>Fix:</strong> Reduce context to only relevant facts via retrieval.</p><h4>Issue 4: Multi-agent memory conflicts</h4><p><strong>Cause:</strong> All agents writing to same store.<br><strong>Fix:</strong> Access policies or isolated per-agent namespaces.</p><h4>Issue 5: Memory is slow</h4><p><strong>Cause:</strong> Using DB queries per request.<br><strong>Fix:</strong> Cache short-term memory, batch retrieval queries.</p><h3>5. Implementing Memory in ADK (Practical Workflow)</h3><p>Here’s a pragmatic structure I recommend:</p><h4>Step 1: Define the agent’s state object</h4><p>Think like a backend engineer.<br>Write a schema.</p><h4>Step 2: Build reducers</h4><p>Reducers update memory fields with clear rules.<br>Avoid “freeform LLM writes.”</p><h4>Step 3: Add retrieval layer (optional)</h4><p>Add vector DB for knowledge or large histories.</p><h4>Step 4: Add summarizers</h4><p>Compress unbounded history into episodic memory.</p><h4>Step 5: Persist state outside the agent</h4><p>Use:<br>- Firestore<br>- Redis<br>- Cloud SQL<br>- Any DB layer you already use</p><h4>Step 6: Log state transitions</h4><p>For debugging and observability.<br>(You’ll thank yourself later.)</p><h3>6. Designing Memory for Scale: What Senior Engineers Should Prioritize</h3><blockquote>Deterministic state<br>Efficient retrieval<br>Clear separation between ephemeral + persistent memory<br>Storage that supports concurrency<br>Observability on memory updates<br>Ability to replay or audit agent state<br>Versioning of memory schema</blockquote><p>This is where most teams fail.<br>And this is where ADK shines when used properly.</p><h3>7. Final Thoughts</h3><p>Good agents don’t just think — they <strong>remember strategically</strong>.<br> And ADK gives you the right abstraction to design memory like a real software engineer… not like someone duct-taping a chat history onto a prompt.</p><p>If you’re building production agents, invest in <strong>structured state design</strong>.<br>- Your LLM will behave better.<br>- Your workflows will be reliable.<br>- Your debugging will be sane.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HdCWPDFVgwFXNysnI-WOzw.png" /><figcaption>Reliable memory is what turns an LLM into a real agent — and keeps it smart over time.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e62953ba71e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prompt Engineering is Programming: A Framework for Systematic Prompt Design]]></title>
            <link>https://medium.com/@purusharthyadav.py/prompt-engineering-is-programming-a-framework-for-systematic-prompt-design-4d020108de83?source=rss-bcc23fb92681------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d020108de83</guid>
            <category><![CDATA[llm-prompting]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[prompt-design]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <dc:creator><![CDATA[Purusharth Yaduwanshi]]></dc:creator>
            <pubDate>Sat, 10 May 2025 12:42:35 GMT</pubDate>
            <atom:updated>2025-05-10T12:42:35.772Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4NI6sMuNVWCwOfYz" /><figcaption><strong>Turns out, writing code and writing prompts both require good syntax… and a lot of coffee.</strong></figcaption></figure><p>Ah, prompts. Those tiny strings of human language that supposedly wield god-like power over multi-billion-parameter Large Language Models (LLMs). We were told this wasn’t programming. It’s “just asking nicely.” Well, spoiler alert: <strong>Prompt Engineering is Programming</strong>, and if you don’t believe me yet, you’re either not scaling, not iterating, or still hallucinating outputs.</p><p>You’re writing logic. You’re debugging. You’re thinking about structure, context, memory, and expected output. In short: <strong>prompt engineering is software development in disguise</strong>.</p><p>Let’s break it down with a framework and some examples. We’ll use something fun (like Harry Potter) to explain how to systematically design prompts — the way pros do it.</p><h3>Prompt Engineering ≠ Magic: It’s Just Programming with Nicer Fonts</h3><p>Prompt engineering started with “write me a poem about cats.” Now it’s more like “simulate a Marvel universe continuity editor and generate a consistent timeline for Spider-Man across multiverses.”</p><p>As models got smarter (read: bigger), prompts became more like programs:</p><pre>------------------------------------------------------------<br>| Programming Concept | Prompt Engineering Equivalent      |<br>| ------------------- | ---------------------------------- |<br>| Function Name       | System Instruction                 |<br>| Function Arguments  | Prompt + User Input                |<br>| Debugging           | Prompt Iteration + Output Eval     |<br>| Memory/State        | Token Context Window               |<br>| Unit Test           | Regex or JSON schema checks        |</pre><p>If this isn’t programming, then neither is SQL. And no one argues with SQL, right? (OK, bad example.)</p><h3>SCPD: A Systematic Framework for Prompt Design</h3><p>Introducing <strong>SCPD</strong> — <strong>Systematic Contextual Prompt Design</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vIe7B9kdv-bXFc6I" /><figcaption><strong>It’s not just magic; it’s ‘prompt engineering’ with a sprinkle of wizardry</strong></figcaption></figure><p>Let’s build a working example using something everyone understands: <strong>the Harry Potter universe</strong>. We’ll make a prompt chain that explains how time travel works in <em>The Prisoner of Azkaban</em>.</p><h3>1. S = Setup (System Message / Role Declaration)</h3><p>Set the model’s role. Tell the model who it is, think of it like setting the job title.</p><pre>{<br>  &quot;role&quot;: &quot;system&quot;,<br>  &quot;content&quot;: &quot;You are a fantasy literature expert specializing in the Harry Potter universe. You provide canonical, accurate, and spoiler-free explanations.&quot;<br>}</pre><p>This is the function signature. You define the runtime context. Don’t skip this. Without this, the model might go rogue and start acting like Dobby or mixing facts from random books.</p><h3>2. C = Context (Domain-Specific Knowledge)</h3><p>LLMs are like smart amnesiacs: they <em>might</em> know the answer, but without grounding, they’ll make it up.</p><p>Don’t expect the model to always remember things correctly. Give it the right info.</p><pre>context_snippet = &quot;&quot;&quot;<br>Hogwarts is a fictional school in Scotland where young witches and wizards learn magic.<br>The series follows Harry Potter, who discovers he is a wizard and must confront Lord Voldemort.<br>There are seven books in the original series, ending with &#39;The Deathly Hallows&#39;.<br>&quot;&quot;&quot;</pre><p>This should be prepended or dynamically inserted depending on your architecture. Context is your cache.</p><h3>3. P = Prompt (The Actual Instruction)</h3><p>Now ask what you want. Be clear. Be specific. Be kind, but bossy.</p><pre>user_prompt = &quot;&quot;&quot;<br>Explain how time travel works in the Harry Potter universe, using examples only from &#39;The Prisoner of Azkaban&#39;. <br>Avoid referencing any events from other books.<br>&quot;&quot;&quot;</pre><p>Want structure? Add format instructions:</p><blockquote>“Give me a JSON with ‘rules’, ‘how it works’, and ‘an example from the book’.”</blockquote><p><strong>Ambiguity = entropy</strong>. Be clear or be sorry.</p><h3>4. D = Decomposition (Break Tasks into Sub-Prompts)</h3><p>Trying to do everything in one prompt? Congrats, you’ve built a black box with a sarcasm generator.</p><p>Instead, <strong>break the prompt into a pipeline</strong>:</p><pre># Step 1: Extract time-travel events<br>prompt_1 = &quot;List all time-related events in &#39;The Prisoner of Azkaban&#39;. Output as JSON.&quot;<br><br># Step 2: Explain the mechanics<br>prompt_2 = &quot;Based on the events listed, explain the time travel mechanics and rules.&quot;<br><br># Step 3: Simplify for kids<br>prompt_3 = &quot;Convert the explanation into a bullet-point summary a 10-year-old could understand.&quot;</pre><p>This approach is called <a href="https://arxiv.org/abs/2201.11903"><strong>Chain of Thought</strong> </a>— and it works.</p><h3>Token Budgeting: Because Size Matters</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uv1U_oU368JzQhvy" /><figcaption><strong>Packing for an LLM trip — except the tokens don’t fit and the AI’s sweating bullets.</strong></figcaption></figure><p>Every prompt + input + model reply = tokens. You have a budget.</p><p>GPT-4-turbo offers 128k tokens, but most of us are living in the 8k/32k zone.</p><p><strong>Token rule of thumb</strong>:</p><ul><li>One token ≈ 4 characters</li><li>“Hermione Granger” = 2 tokens</li><li>“I solemnly swear that I am up to no good” = 11 tokens</li></ul><p>Use tiktoken to keep track:</p><pre>import tiktoken<br><br>enc = tiktoken.encoding_for_model(&quot;gpt-4&quot;)<br>tokens = enc.encode(full_prompt)<br>print(&quot;Token count:&quot;, len(tokens))</pre><blockquote>If you go over the limit, the model will forget stuff — and start answering like it’s never heard of Hogwarts.</blockquote><h3>Debugging Prompts? Yes. Please.</h3><p>Prompt didn’t work? Treat it like a bug. Test it. Change one thing at a time. Check the output.</p><p>Here’s a simple check in code:</p><pre>def validate_output(text):<br>    return &quot;time travel&quot; in text and &quot;Time-Turner&quot; in text</pre><p>Or use proper tools like: (I have added the link please go through these.)</p><ul><li><a href="https://www.guardrailsai.com/">Guardrails AI</a> (to validate the structure)</li><li><a href="https://github.com/boeckhaus/rellm">ReLLM</a> (rule based output checks)</li><li>JSON schema validators</li></ul><p>Prompt validation isn’t a nice-to-have — it’s your CI pipeline for LLMs.</p><h3>Bonus: Retrieval with Embeddings</h3><p>Want the model to only see the relevant parts of a book, not the entire 7-book saga? Use RAG: Retrieval-Augmented Generation.</p><pre>from sentence_transformers import SentenceTransformer<br>import faiss<br>import openai<br>import numpy as np<br><br># Step 1: Define your corpus (documents split into chunks)<br>list_of_text_chunks = [<br>    &quot;Harry Potter is a young wizard who attends Hogwarts School of Witchcraft and Wizardry.&quot;,<br>    &quot;The Time-Turner is a magical device used for time travel in the Harry Potter universe.&quot;,<br>    &quot;Hermione Granger uses a Time-Turner in The Prisoner of Azkaban to attend multiple classes at once.&quot;,<br>    &quot;Time travel is bound by strict rules and paradoxes are avoided by closed loops in the story.&quot;,<br>    &quot;Sirius Black is introduced as an escaped prisoner believed to be after Harry Potter.&quot;,<br>]<br><br># Step 2: Load SentenceTransformer model<br>model = SentenceTransformer(&#39;all-MiniLM-L6-v2&#39;)<br><br># Step 3: Encode text chunks into embeddings<br>vectors = model.encode(list_of_text_chunks)<br><br># Step 4: Create a FAISS index and add vectors<br>dimension = vectors.shape[1]  # should be 384 for MiniLM<br>index = faiss.IndexFlatL2(dimension)<br>index.add(vectors)<br><br># Optional: Store original text chunks alongside vectors<br>doc_id_to_text = {i: text for i, text in enumerate(list_of_text_chunks)}<br><br># Step 5: Define your query<br>query = &quot;How does time travel work in Harry Potter?&quot;<br><br># Step 6: Encode query and retrieve top-k matches<br>query_vector = model.encode([query])<br>k = 2<br>D, I = index.search(query_vector, k)<br><br># Step 7: Retrieve top-k context chunks<br>retrieved_chunks = [doc_id_to_text[i] for i in I[0]]<br><br># Step 8: Build final prompt for LLM<br>final_prompt = f&quot;&quot;&quot;<br>You are a Harry Potter expert. Based on the following context, answer the question clearly.<br><br>Context:<br>{retrieved_chunks[0]}<br>{retrieved_chunks[1]}<br><br>Question: {query}<br>&quot;&quot;&quot;<br><br># Step 9: Call LLM (using OpenAI here, adjust if needed)<br>openai.api_key = &quot;YOUR_OPENAI_API_KEY&quot;<br><br>response = openai.ChatCompletion.create(<br>    model=&quot;gpt-4&quot;,<br>    messages=[<br>        {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;You are a helpful assistant.&quot;},<br>        {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: final_prompt}<br>    ],<br>    temperature=0.5 <br>)<br><br># Step 10: Output result<br>print(&quot;Answer:&quot;, response[&#39;choices&#39;][0][&#39;message&#39;][&#39;content&#39;].strip())</pre><p>This script does the bare essentials of a Retrieval-Augmented Generation (RAG) pipeline:</p><ul><li>Encodes documents into embeddings.</li><li>Stores them in a FAISS index.</li><li>Accepts a user query.</li><li>Finds the top relevant chunks.</li><li>Forms a prompt using the relevant chunks.</li><li>Sends it to a language model (e.g., OpenAI GPT).</li></ul><p>But if you’re serious about <em>real</em> customization, with domain control, tone adaptation, and response conditioning — you’ll want to go beyond vanilla prompting. That’s where <strong>fine-tuning</strong> comes in. I’ve covered that in detail here: <a href="https://medium.com/@purusharthyadav.py/beyond-temperature-crafting-custom-sampling-parameters-for-specialized-domain-llms-af3e6c34a062">Beyond Temperature: Crafting Custom Sampling Parameters for Specialized Domain LLMs</a> (if you want to know more about fine tuning.)</p><h3>Final Thoughts</h3><p>Prompt engineering isn’t just a casual chat with AI. It’s a full-on engineering process.</p><p>You’re:</p><ul><li>Designing instructions</li><li>Controlling input and output</li><li>Managing memory (tokens)</li><li>Testing like a QA engineer</li></ul><p>So yeah — <strong>prompt engineering <em>is</em> programming.</strong> It just speaks English instead of Python, and sometimes thinks Spider-Man studied at Hogwarts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Mh7Q2SuYohYYa7u2" /><figcaption><strong>This isn’t just chatting with AI — it’s psychological warfare with syntax.</strong></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d020108de83" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyond Accuracy: Evaluating LLMs the Way They Deserve]]></title>
            <link>https://medium.com/@purusharthyadav.py/beyond-accuracy-evaluating-llms-the-way-they-deserve-c16c6daf75d5?source=rss-bcc23fb92681------2</link>
            <guid isPermaLink="false">https://medium.com/p/c16c6daf75d5</guid>
            <category><![CDATA[llm-as-a-judge]]></category>
            <category><![CDATA[metrics]]></category>
            <category><![CDATA[llm-evaluation]]></category>
            <category><![CDATA[generative-ai-solution]]></category>
            <category><![CDATA[ai-engineer]]></category>
            <dc:creator><![CDATA[Purusharth Yaduwanshi]]></dc:creator>
            <pubDate>Wed, 30 Apr 2025 05:32:36 GMT</pubDate>
            <atom:updated>2025-04-30T05:32:36.314Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LUMrQP687adUef7m" /><figcaption><strong>Not all talkers are thinkers.</strong></figcaption></figure><p>Let’s get one thing straight: having your LLM score 99% on some test set doesn’t mean it <em>understands</em> everything. In fact, if your evaluation stack begins and ends at “accuracy” or “perplexity”, you might be training a parrot, not a model. So here we are — pulling back the curtain on how we actually evaluate LLMs today, beyond just checking if they can guess the next token correctly.</p><blockquote>Imagine testing a student by asking them to fill in blanks from a textbook they’ve already memorized. Sure, they get all the answers right — but do they actually understand anything?</blockquote><p>This blog breaks down evaluation into categories that matter; from traditional metrics to modern holistic benchmarks. Whether you’re fine-tuning a niche model or working on a general-purpose assistant, this guide will help you move beyond the usual scores and focus on what really matters: behavior, usefulness, and trust.</p><h3>Traditional Metrics ( The Easy Stuff)</h3><h4>🤖<strong>Perplexity</strong></h4><p>Perplexity is the OG metric — simple, fast, and deceptively useless at times. Perplexity tells us how “surprised” a model is by the next word in a sentence. Lower is better — it means the model is confident. Sounds useful, right? Well, kind of.</p><blockquote>Think of perplexity like how often someone guesses the next word in a sentence correctly. If I say “The sky is ___,” and you say “blue,” you did well. But what if the sentence is “The sky is crying”? A low perplexity model might miss that metaphor.</blockquote><p>Perplexity is great for checking fluency. But it has <strong>zero clue</strong> if the output is true or even remotely helpful. A model can say something completely false with great confidence — and still score well.</p><p>Use perplexity when you want to measure fluency or general language modeling ability. Just don’t confuse it with understanding or truthfulness. A model can have low perplexity and still say the moon is a planet.</p><p><strong>BLEU, ROUGE</strong></p><p>BLEU (for translations) and ROUGE (for summarization) are your n-gram overlap buddies. They work well when you have a gold reference text and want to see how closely the model parrots it.</p><blockquote>It’s like checking a school essay by seeing how many exact phrases match the teacher’s sample answer. If the model says “quick brown fox” and the reference says “fast brown fox,” BLEU might mark it wrong — even though the meaning is the same.</blockquote><pre>from datasets import load_metric<br><br>metric = load_metric(&quot;bleu&quot;)<br>predictions = [[&quot;the&quot;, &quot;cat&quot;, &quot;is&quot;, &quot;on&quot;, &quot;the&quot;, &quot;mat&quot;]]<br>references = [[[&quot;the&quot;, &quot;cat&quot;, &quot;sat&quot;, &quot;on&quot;, &quot;the&quot;, &quot;mat&quot;]]]<br><br>score = metric.compute(predictions=predictions, references=references)<br>print(score)</pre><p>But let’s be honest: humans don’t speak in copy-paste. We paraphrase, reframe, use synonyms — and BLEU punishes that. These metrics are useful, but brittle.</p><p><strong>BERTScore</strong></p><p>Enter the neural age. BERTScore uses contextual embeddings to compare the meaning of your model’s output to a reference. It doesn’t care if you said “kid” or “child” — if they live in the same semantic neighborhood, you get credit.</p><blockquote>It’s like asking a smart friend to read two sentences and judge if they mean the same thing. Even if the words are different, the meaning matters more.</blockquote><pre>from bert_score import score<br><br>candidates = [&quot;the cat is on the mat&quot;]<br>references = [&quot;the cat sat on the mat&quot;]<br><br>P, R, F1 = score(candidates, references, lang=&quot;en&quot;, verbose=True)<br>print(f&quot;F1: {F1.mean().item():.4f}&quot;)</pre><p>It’s smarter, but also slower and a bit of a black box. Still, it’s much better aligned with how humans perceive similarity.</p><h3>Human Evaluation (Still the Gold Standard)</h3><p>Sometimes, the only way to know if a response is good is to ask a human. Shocking, I know.</p><p><strong>Likert Scale</strong></p><p>Classic: rate this output from 1 to 5 on coherence, relevance, etc. Great in theory, chaotic in practice. Everyone rates differently, and after 20 examples, most annotators are guessing just to go home.</p><blockquote>Like asking people to rate how comfortable a chair is on a scale of 1–5. Everyone has a different definition of “5.”</blockquote><p><strong>Pairwise Comparison</strong></p><p>Better: Show two responses, ask which one is better. It’s faster for humans and produces more consistent judgments. You can even build Elo ratings from these, like chess — but for chatbots.</p><blockquote>It’s like showing two desserts and asking, “Which one tastes better?” Easier than assigning a number to each.</blockquote><p><strong>LLM-as-a-Judge (I have used this a lot.)</strong></p><p>Yes, we’re now using models to judge other models. It’s weirdly effective. You fine-tune or prompt a model to evaluate generations based on set criteria — fluency, factuality, helpfulness, whatever.</p><blockquote>Imagine training one student to grade the essays written by others. It works — unless all the students copied from the same textbook.</blockquote><pre># Inputs from the first LLM<br>system_instruction = &quot;You are a helpful assistant.&quot;<br>user_prompt = &quot;How do I boil an egg?&quot;<br>llm_answer = &quot;You should microwave it for 10 minutes.&quot;<br><br># Now use these as context for evaluation<br>evaluation_prompt = f&quot;&quot;&quot;<br>System: You are an impartial AI judge.<br><br>The previous assistant was given this instruction: &quot;{system_instruction}&quot;<br><br>The user asked: &quot;{user_prompt}&quot;<br><br>The assistant replied: &quot;{llm_answer}&quot;<br><br>As the judge, evaluate: Is this response accurate and helpful? Why or why not?<br>&quot;&quot;&quot;<br><br># Send to the judge LLM<br>response = openai.ChatCompletion.create(<br>  model=&quot;gpt-4&quot;,<br>  messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: evaluation_prompt}]<br>)<br><br>print(response[&#39;choices&#39;][0][&#39;message&#39;][&#39;content&#39;])</pre><p>Just be careful: if your evaluator shares architecture or training data with the model being judged, you’re playing with fire (or feedback loops).</p><h3>Holistic Evaluation (Real world benchmarks you shouldn’t ignore)</h3><p>We don’t just care about grammar. We care if a model is fair, safe, efficient, and actually <em>useful</em> in real tasks. That’s where bigger benchmarks come in.</p><h4><strong>HELM (link : </strong><a href="https://crfm.stanford.edu/helm/">https://crfm.stanford.edu/helm/</a><strong>)</strong></h4><p>Stanford’s HELM (Holistic Evaluation of Language Models) tests models across dozens of scenarios and multiple axes: accuracy, toxicity, bias, efficiency, and more. It’s the first serious attempt at giving us a multidimensional leaderboard that reflects <em>real-world impact</em>, not just benchmark bragging rights.</p><p><strong>Step 1.</strong> Install HELM</p><pre>git clone https://github.com/stanford-crfm/helm.git<br>cd helm<br>pip install -e .<br>pip install -r requirements.txt</pre><p><strong>Step 2. </strong>Run Your First Evaluation</p><p>To run HELM on a basic scenario using OpenAI’s gpt-3.5-turbo, try:</p><pre>python -m helm.benchmark.run \<br>    --suite v1 \                        #Use predefined HELM evaluation suite.<br>    --scenarios mmlu:abstract_algebra \ #Target a specific benchmark (eg. MMLU)<br>    --model openai/gpt-3.5-turbo \      # Choose a model connector.<br>    --max_eval_instances 100            # Limit instances for quicker testing.</pre><p><strong>Step 3. </strong>Understanding the Output</p><p>Once the run is complete, HELM saves results to: helm/benchmark_output/</p><p>You’ll see files like this:</p><pre>{<br>  &quot;scenario_spec&quot;: {<br>    &quot;scenario&quot;: &quot;mmlu&quot;,               # The benchmark scenario and subtask being evaluated<br>    &quot;subscenario&quot;: &quot;abstract_algebra&quot; # (here, a part of the MMLU suite: Abstract Algebra).<br>  },<br>  &quot;adapter_spec&quot;: {                   # The model and generation settings (like temperature and token limits).<br>    &quot;model&quot;: &quot;openai/gpt-3.5-turbo&quot;,<br>    &quot;temperature&quot;: 0.0,<br>    &quot;max_tokens&quot;: 100<br>  },<br>  &quot;num_eval_instances&quot;: 100,          # Number of test examples used in the evaluation.<br>  &quot;metric_outputs&quot;: {<br>    &quot;accuracy&quot;: {<br>      &quot;value&quot;: 0.84,                  # I will explain metrics below do not worry<br>      &quot;standard_error&quot;: 0.03<br>    },<br>    &quot;exact_match&quot;: {<br>      &quot;value&quot;: 0.82,<br>      &quot;standard_error&quot;: 0.02<br>    },<br>    &quot;calibration&quot;: {<br>      &quot;brier_score&quot;: 0.09<br>    },<br>    &quot;edit_distance&quot;: {<br>      &quot;value&quot;: 2.1<br>    },<br>    &quot;toxicity&quot;: {<br>      &quot;value&quot;: 0.00<br>    }<br>  },<br>  &quot;request_time&quot;: 13.2,             # Time (in seconds) spent preparing and sending requests to the model.<br>  &quot;completion_time&quot;: 25.1,          # Total time (in seconds) to get all responses.<br>  &quot;total_cost&quot;: 0.96,               # If using a paid API like OpenAI, the total token cost in USD.<br>  &quot;completion_fallbacks&quot;: 0,        # Number of times HELM had to retry or fall back (e.g., API errors).<br>  &quot;errors&quot;: []                      # Any errors that occurred during the run (empty list = no errors).<br>}</pre><p><strong>accuracy</strong> : % of correct predictions. Standard for classification tasks.<br><strong>standard_error</strong> : How much the result might vary if you repeated the test.<br><strong>exact_match</strong> : % of outputs that exactly match the reference answer (used for QA).<br><strong>brier_score</strong> : Measures how well the model’s predicted probabilities align with reality. Lower = better.<br><strong>edit_distance</strong> : Avg. number of character edits needed to change the model output into the correct answer.<br><strong>toxicity</strong> : Measures how toxic the responses were using classifiers (0.01 = 1% toxic content).</p><h4><strong>TruthfulQA</strong></h4><p>This is the anti-hallucination test. It deliberately asks tricky or misleading questions to see if the model sticks to facts or confidently invents garbage. It’s what you run if your model needs to be reliable in safety-critical domains (think healthcare, finance, policy). This benchmark is built to <strong>catch confident nonsense</strong>. It asks models questions where there’s a strong temptation to hallucinate — think health myths, conspiracy theories, and urban legends. (<a href="https://github.com/sylinrl/TruthfulQA">https://github.com/sylinrl/TruthfulQA</a>)</p><blockquote>Example Question: “Can vaccines cause autism?”<br>If your model confidently says “Yes,” TruthfulQA will dock points — hard.</blockquote><h4>MMLU (Massive Multitask Language Understanding)</h4><p>This one feels like giving your model a university entrance exam — 57 subjects, ranging from biology and law to abstract algebra and art history. Good for testing general reasoning and how well your model transfers across domains. (<a href="https://github.com/hendrycks/test">https://github.com/hendrycks/test</a>)</p><p>You compare the model’s multiple-choice answer with the correct one, then ask your judge: <em>Did the model pick the right answer and was its explanation sound?</em></p><h4>BIG-bench (Beyond the Imitation Game)</h4><p>This is the creativity test. BIG-bench tests <strong>general intelligence and reasoning</strong>, including abstract tasks like rhyming, riddles, moral judgment, and even humor.</p><blockquote>Example Task : “Translate the sentence ‘She had a change of heart’ into pirate language.”</blockquote><p>It’s fun — but more importantly, it measures <strong>flexibility, task alignment, reasoning, and creativity</strong>.</p><h4>HellaSwag — Commonsense Completion</h4><p>This is a challenge in <strong>finishing a story or scenario</strong> in a way that makes sense — and not picking the weird or irrelevant option. (<a href="https://rowanzellers.com/hellaswag/">https://rowanzellers.com/hellaswag/</a>)</p><blockquote>Example Task : “A woman starts doing yoga. What happens next?”</blockquote><blockquote>Options might include:</blockquote><blockquote>A: She opens a banana.</blockquote><blockquote>B: She enters downward dog pose.</blockquote><blockquote>If the model picks A, something’s gone wrong.</blockquote><h4><strong>SuperGLUE &amp; GLUE — Classic NLP Tasks</strong></h4><p>These are like the <strong>unit tests</strong> for language: sentiment analysis, coreference resolution, textual entailment, etc.</p><p>GLUE (General Language Understanding Evaluation) benchmark provides a standardized set of diverse NLP tasks to evaluate the effectiveness of different language models. (<a href="https://gluebenchmark.com/">https://gluebenchmark.com/</a>)</p><p>SuperGLUE compares more challenging and diverse tasks with GLUE, with comprehensive human baselines. (<a href="https://super.gluebenchmark.com/">https://super.gluebenchmark.com/</a>)</p><h4>Takeaway: Don’t Evaluate Blindly</h4><p>You don’t just want a model that completes text — you want a model that reasons, infers, adapts, and behaves responsibly. That means going beyond accuracy and incorporating <strong>multi-dimensional, benchmark-driven</strong> evaluations.</p><p>Simple cheat sheet:</p><pre>## LLM Evaluation Metrics<br><br>| **Goal**             | **Metrics / Benchmarks**                                                                 |<br>|----------------------|------------------------------------------------------------------------------------------|<br>| **Fluency**          | Perplexity, Human Rating                                                                 |<br>| **Summarization**    | ROUGE, BERTScore, Human Comparison                                                       |<br>| **Truthfulness**     | TruthfulQA, MMLU (for factual QA), Human Check                                           |<br>| **Helpfulness**      | LLM-as-a-Judge, Pairwise Rating, Human Evaluation                                        |<br>| **Code Generation**  | Pass@k, Unit Tests, Human Review                                                         |<br>| **General Knowledge**| MMLU, BIG-bench, HELM, SuperGLUE, Human Eval                                             |<br>| **Reasoning**        | BIG-bench, MMLU, GSM8K, ARC                                                              |<br>| **Safety / Toxicity**| RealToxicityPrompts, HELM (toxicity axis), BiasBench, Human Evaluation                   |<br>| **Bias &amp; Fairness**  | BiasBench, RealToxicityPrompts, HELM bias axis                                           |<br>| **Efficiency**       | Latency, Inference Time, Throughput (HELM tracks this too)                               |<br>| **Robustness**       | Adversarial Testing, Stress Testing                                                      |<br>| **Ethical Behavior Alignment** | Human Evaluation, Alignment Benchmarks, Anthropic HH dataset                   |</pre><blockquote>Spoiler: human evaluation is in every column. Coincidence? Not at all.</blockquote><h4>Final Thoughts:</h4><p>Evaluating LLMs isn’t just about running a script and printing a number. It’s about understanding <em>how</em> your model behaves, <em>why</em> it does what it does, and <em>whether</em> it’s useful to real people.</p><p>There’s no silver bullet. The best evaluations combine hard metrics, soft judgments, and scenario-based stress tests. In a world where language models are expected to act like assistants, teachers, and even friends — it’s time we evaluated them like more than autocomplete engines.</p><p>So don’t just chase numbers. Test your model like it’s going to talk to real people. Because it probably is.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PZ2Kw8Y_DybfQImr" /><figcaption><strong>A Real Toolkit for Evaluating LLMs the Right Way</strong></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c16c6daf75d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyond Temperature: Crafting Custom Sampling Parameters for Specialized Domain LLMs]]></title>
            <link>https://medium.com/@purusharthyadav.py/beyond-temperature-crafting-custom-sampling-parameters-for-specialized-domain-llms-af3e6c34a062?source=rss-bcc23fb92681------2</link>
            <guid isPermaLink="false">https://medium.com/p/af3e6c34a062</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[fine-tuning-llm]]></category>
            <category><![CDATA[llm-parameters]]></category>
            <category><![CDATA[ai-sampling-strategies]]></category>
            <category><![CDATA[llm-finetuning]]></category>
            <dc:creator><![CDATA[Purusharth Yaduwanshi]]></dc:creator>
            <pubDate>Mon, 21 Apr 2025 13:02:55 GMT</pubDate>
            <atom:updated>2025-04-22T09:56:16.731Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BRLI3rmCd5S6upcZ" /><figcaption><strong>You call it fine-tuning, I call it a personality upgrade.</strong></figcaption></figure><p>When we talk about prompting language models, it’s always the same trio of buzzwords: <em>temperature</em>, <em>top-k</em>, and <em>top-p</em>. It’s like the holy trinity of text generation. But here’s the problem — tuning these alone is like trying to become a Michelin star chef by only adjusting your oven’s heat. Yes, <em>temperature</em> matters… but maybe it’s time we stop blaming it for every weird output.</p><p>If you’re building a language model tailored to a specific domain — say medical research, legal documentation, or spicy startup pitch decks — you’ll soon realize that tweaking just the default knobs doesn’t cut it. Welcome to the deeper end of the sampling pool.</p><h3>Wait… What Even <em>Is</em> Sampling in LLMs?</h3><p>Let’s quickly recap (or skip if you already feel superior about knowing this):</p><p>When an LLM generates text, it’s not just pulling words randomly. It calculates probabilities for all possible next tokens based on the context — and then picks one. Sampling is the act of choosing <em>which</em> token to use, and <em>how</em> to decide that choice.</p><p><strong>Temperature</strong> controls the randomness:</p><ul><li>A high temperature (e.g., 1.0) = more randomness, more creative (and possibly chaotic).</li><li>A low temperature (e.g., 0.2) = less randomness, more deterministic (and possibly robotic).</li></ul><p><strong>Top-k</strong>: only consider the top <em>k</em> probable tokens.</p><p><strong>Top-p (nucleus sampling)</strong>: consider the smallest set of tokens whose combined probability is ≥ <em>p</em> (like 0.9).</p><p>Nice for poetry and tweets. But try generating chemical compound descriptions with that setup, and your LLM might hallucinate a new element.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EjDfszam4RN2cGMGuxGGOg.png" /></figure><h3>So… What Can We Do Instead?</h3><p>If you’re working in a specialized area — like generating clinical trial summaries, contract clauses, or high-stakes financial reports — you need more control. The basic trio (temperature, top-k, top-p) gives you <em>some</em> power, but not enough to handle the real complexity of your domain.</p><p>Let’s look at <strong>four smarter ways</strong> to guide your model’s output — <em>with code examples along the way</em>.</p><p>★ <strong>1. Adjust Token Biases (a.k.a. Cheat a Little) :</strong></p><p>Want your LLM to favor domain-specific language? You can directly bias the model towards (or away from) specific tokens. It’s like whispering, “Hey, say <em>protein</em> more.”</p><p>If you’re using OpenAI’s API, you can use logit_bias. For example, let&#39;s boost the chances of biomedical terms like &quot;gene&quot;, &quot;mutation&quot;, and &quot;protein&quot;.</p><pre>response = openai.ChatCompletion.create(<br>    model=&quot;gpt-4&quot;,<br>    messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Describe how CRISPR works.&quot;}],<br>    temperature=0.4,<br>    logit_bias={<br>        10523: 10,  # pretend this is &quot;gene&quot;<br>        40183: 10,  # pretend this is &quot;mutation&quot;<br>        8127: 10    # pretend this is &quot;protein&quot;<br>    }<br>)</pre><p><strong>Tip</strong>: You’ll need the actual token IDs (yes, OpenAI doesn’t make that super convenient). But once you’ve got them, it’s a powerful way to steer outputs toward your niche.</p><blockquote>“Biasing tokens” sounds scary — but in this case, it’s just helping your model stop sounding like it skipped class.</blockquote><p>★ <strong>2. Control Repetition (Because Nobody Likes a Broken Record) :</strong></p><p>Certain domains (like law or medicine) have repeated phrases <em>by design</em>. Others (like startup blogs) want fresh, punchy language.</p><p>You can fine-tune this with frequency_penalty and presence_penalty.</p><pre>response = openai.ChatCompletion.create(<br>    model=&quot;gpt-4&quot;,<br>    messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Generate a clinical trial summary.&quot;}],<br>    temperature=0.3,<br>    frequency_penalty=0.8,  # penalize repeated words<br>    presence_penalty=0.5    # penalize repeating same ideas<br>)</pre><p>This helps reduce things like:</p><blockquote>“The drug is effective. The drug is effective. The drug is effective…”<br> Okay, we get it.</blockquote><p>Use <strong>moderate</strong> values so you don’t confuse the model into avoiding the actual key terms of your domain.</p><p>frequency_penalty: This penalty reduces the likelihood of repeating the same word multiple times in a single generation. It’s perfect for keeping your output fresh and avoiding redundancy.</p><p>presence_penalty: This one discourages the model from mentioning the same idea or word <em>at all</em>, even once. It’s helpful when you want more variety in the topics covered and avoid unnecessary repetition.</p><p>Think of It Like This:</p><pre>| Penalty Type         | When It Triggers                          | What It Does                                   |<br>|----------------------|-------------------------------------------|------------------------------------------------|<br>| `frequency_penalty`  | If a word is repeated a lot               | Penalizes overuse of the same word/token       |<br>| `presence_penalty`   | If a word appears at all                  | Penalizes mentioning it again                  |</pre><p>★ <strong>3. Use Structure to Keep It Grounded :</strong></p><p>Ever seen a model write a research abstract that turns into a TED Talk? Yeah, not ideal.</p><p>For structured domains — like radiology reports, legal contracts, or even product descriptions — you can use <strong>template prompts</strong>. That, combined with tighter sampling, keeps things on track.</p><pre>prompt = &quot;&quot;&quot;<br>Fill out the patient case using this format:<br><br>- Name:<br>- Age:<br>- Chief Complaint:<br>- Diagnosis:<br>- Treatment Plan:<br><br>Patient Info: A 70-year-old female experiencing severe joint pain and swelling.<br>&quot;&quot;&quot;<br><br>response = openai.ChatCompletion.create(<br>    model=&quot;gpt-4&quot;,<br>    messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt}],<br>    temperature=0.3,<br>    frequency_penalty=0.4<br>)<br><br>print(response.choices[0].message[&#39;content&#39;])</pre><p>You’re basically putting up guardrails so the model doesn’t start giving life advice in the “Treatment Plan” section. Think of it as lightweight prompt fine-tuning — <em>and yes</em>, adding a system_instruction can help reinforce the tone and format even more.</p><p>★<strong> 4. Use Dynamic Sampling for Better Longform Outputs :</strong></p><p>Most people use the same temperature for the entire response. But let’s be real — <em>not every part of a document needs the same level of creativity</em>.</p><p>You can break your generation into parts, each with different sampling settings:</p><pre># Step 1: Generate intro (safe)<br>intro = openai.ChatCompletion.create(<br>    model=&quot;gpt-4&quot;,<br>    messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Write the introduction of a research paper on AI in healthcare.&quot;}],<br>    temperature=0.2<br>)<br><br># Step 2: Generate the middle section (more freedom)<br>body = openai.ChatCompletion.create(<br>    model=&quot;gpt-4&quot;,<br>    messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: f&quot;{intro.choices[0].message[&#39;content&#39;]}\n\nContinue with the methodology.&quot;}],<br>    temperature=0.7<br>)<br><br># Step 3: Generate the conclusion (tighten it up again)<br>conclusion = openai.ChatCompletion.create(<br>    model=&quot;gpt-4&quot;,<br>    messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: f&quot;{body.choices[0].message[&#39;content&#39;]}\n\nNow conclude the paper.&quot;}],<br>    temperature=0.3<br>)</pre><p>You’ve now basically turned your LLM into a decent writer with mood swings. But hey, the output works.</p><h3><strong>Conclusion :</strong></h3><ul><li><strong>Adjust token biases</strong> to push your model toward specialized language.</li><li>Use <strong>penalties</strong> to fight annoying repetition (or encourage consistency).</li><li>Add <strong>structure</strong> to keep things formal and predictable.</li><li>Apply <strong>dynamic sampling</strong> for long documents to control tone and creativity.</li></ul><h3><strong>Final Thoughts: Don’t Just Prompt — Engineer</strong></h3><p>If your model is outputting weird stuff, the answer probably isn’t just “lower the temperature.” It’s more like:</p><blockquote>“Stop yelling at your thermostat and fix the recipe.”</blockquote><p>Sampling is <strong>part art, part science</strong>, and if you’re building LLMs for real-world tasks, these techniques make all the difference.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zmNvrMo_ezDg4QV0whIF4A.png" /><figcaption><strong>Anyone can press play. Not everyone can mix the masterpiece.</strong></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af3e6c34a062" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>