<?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 Ujjwaldash on Medium]]></title>
        <description><![CDATA[Stories by Ujjwaldash on Medium]]></description>
        <link>https://medium.com/@ujjwaldash?source=rss-794441dc753f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*XDD57_RUkq_mYJ5y</url>
            <title>Stories by Ujjwaldash on Medium</title>
            <link>https://medium.com/@ujjwaldash?source=rss-794441dc753f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 11:52:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ujjwaldash/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[HTTP 200 OK, Yet Completely Wrong: How We Built an Observability Engine for AI Agents]]></title>
            <link>https://pub.towardsai.net/http-200-ok-yet-completely-wrong-how-we-built-an-observability-engine-for-ai-agents-f628b49e9f19?source=rss-794441dc753f------2</link>
            <guid isPermaLink="false">https://medium.com/p/f628b49e9f19</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[agent-observability]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[ai-engineering]]></category>
            <category><![CDATA[ml-engineering]]></category>
            <dc:creator><![CDATA[Ujjwaldash]]></dc:creator>
            <pubDate>Wed, 25 Nov 2026 14:05:51 GMT</pubDate>
            <atom:updated>2026-11-26T03:20:31.850Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>Traditional monitoring tells you if your agent is alive, not if it’s right. Here is the asynchronous architecture we built to evaluate thousands of production chats overnight.</em></h4><p>Arnav had just shipped his company’s first production AI assistant. Before launch, he tested it on a carefully curated set of 200 questions. It scored 92%. Everything looked green, response times were fast, and there were zero error logs.</p><p>Two weeks later, a major client sent an urgent message: <em>“Your AI has been giving us wrong policy answers since last week.”</em></p><p>Arnav stared at his monitoring dashboard. Every single API call showed 200 OK. His system was alive, fast, and completely confident—while quietly hallucinating. That afternoon, Arnav realized that traditional server monitoring only tells you if your AI is running, never if it is right.</p><h3>The Trap of the Static Test File</h3><p>At first, Arnav relied on his 200-question test dataset whenever he changed a prompt. That failed almost immediately. Real users didn’t talk like his neat test file — they asked messy follow-up questions, combined two requests into one, and triggered edge cases his static dataset never imagined.</p><pre>[Static 200-Question File] ──► [Manual Eval Script] ──► Score: 92% (Blind to real users)</pre><p>So Arnav abandoned offline-only testing and decided to pull real production conversations directly from cloud storage (S3) on a daily schedule.</p><p>To avoid adding latency to live user chats, he moved evaluation completely out of the request path into an asynchronous overnight pipeline. A daily scheduler (APScheduler) woke up once a day and sampled a manageable slice of yesterday’s chats from S3.</p><pre>[Live User] ──► [AI Agent] ──► Fast Reply (No eval delay!)<br>                    │<br>                    ▼<br>           [Raw Chat Logs (S3)]<br>                    │<br>         (Daily Scheduler + Sampler)<br>                    │<br>                    ▼<br>            [Background Grader]</pre><p>The very first night the scheduled job ran, it crashed halfway through. One of the teams had updated their agent and accidentally changed a field name in their chat logs, breaking Arnav’s script.</p><p>To stop a single malformed log file from taking down an entire night’s batch, Arnav added a strict YAML schema validator right after ingestion. Only conversations matching the standardized format — containing a conversation_id, tenant_id, user turns, assistant replies, and any retrieved RAG documents or tool calls—were copied into a validated evaluation bucket. Rather than throwing all those chats at the grader simultaneously (causing memory spikes and API rate limits), he dropped lightweight job tickets into an Amazon SQS queue so a sequential background worker could pull and grade them safely one by one.</p><pre>[Raw Chat Logs (S3)]<br>         │<br>         ▼<br> [YAML Schema Validator] ──► (Rejects broken logs safely)<br>         │<br>         ▼<br>[Validated Eval Bucket (S3)] ──► [Amazon SQS Queue] ──► [Sequential Worker]</pre><h3>Insight 1: Why an LLM Judge Confidently Lies (and Why a 0.98 Faithfulness Score Can Still Mean a Broken Agent)</h3><p>Once the pipeline stopped crashing, Arnav ran into a much subtler problem: he couldn’t trust the scores.</p><p>Initially, he sent each conversation to an LLM judge with a simple prompt: <em>“Rate this response from 0 to 1.”</em> Running the exact same conversation three times produced 0.78, 0.69, and 0.84. Worse, <strong>metric bleed</strong> crept in—if the agent used a slightly blunt tone, the judge quietly docked points from its <em>Relevance</em> score, blending unrelated flaws into a single blurry number. Meanwhile, paying an expensive frontier LLM just to verify basic math—like whether the search engine fetched the right document—was burning budget unnecessarily.</p><p>Arnav replaced his single vague prompt with a three-tier <strong>Evaluation Orchestrator</strong>:</p><ol><li><strong>Computational Metrics:</strong> Pure, free math (Precision@k and Recall@k) whenever ground-truth retrieval checks were possible.</li><li><strong>Embedding Metrics:</strong> Fast vector-similarity checks for semantic closeness.</li><li><strong>LLM-as-a-Judge via DeepEval (</strong><strong>GEval):</strong> Isolated, step-by-step rubrics using token probabilities where each metric ran independently—so tone never polluted <em>Relevance</em>, and every grade required a written explanation.</li></ol><pre>[Amazon SQS Queue]<br>         │<br>         ▼<br>[Sequential Worker]<br>         │<br>         ▼<br>[Evaluation Orchestrator]<br>   ├──► Computational Metrics (Precision@k, Recall@k — Fast &amp; Free)<br>   ├──► Embedding Metrics (Semantic similarity)<br>   └──► LLM Judge via DeepEval GEval (Isolated rubrics + written reasons)<br>         │<br>         ▼<br>[Results Bucket (S3)]</pre><p>Yet even with isolated metrics, Arnav noticed something bizarre a few weeks later: an agent’s <strong>Faithfulness</strong> score climbed to 0.98, while users were furiously clicking thumbs-down.</p><p>When Arnav inspected the turn logs, the realization hit him: <strong>a higher Faithfulness score does not mean a better agent.</strong> <em>Faithfulness</em> only measures whether the AI stuck to the retrieved documents without inventing facts. When the search engine retrieved an outdated or irrelevant policy document — and the agent faithfully summarized that wrong document — the judge awarded a near-perfect 0.98 for Faithfulness while the user got a useless answer.</p><p>That taught Arnav never to trust a single metric in isolation — <em>Faithfulness</em> had to be paired with <em>Contextual Precision</em> and <em>Goal Accuracy</em> to tell the true story.</p><h3>Insight 2: Why Evaluating 100% of Conversations Is Worse Than Smart Sampling</h3><p>As daily traffic grew into the tens of thousands of chats, a stakeholder asked: <em>“Shouldn’t we evaluate every single conversation so nothing slips through?”</em></p><p>Arnav ran the math and realized exhaustive evaluation wasn’t just expensive — it was actively counterproductive. Grading 100% of traffic with multi-metric LLM judges would burn through their monthly inference budget in four days, forcing the team to downgrade to a weaker, cheaper judge model that missed subtle multi-turn reasoning errors. Furthermore, because 70% of production traffic consisted of repetitive greetings and routine FAQ lookups, grading every chat drowned out rare, complex edge cases in a sea of trivial 1.0 scores.</p><p>To control both quality and scale, Arnav made the entire pipeline <strong>config-driven</strong>. Teams registered their agents in a central configuration store (configGroup: schedular-agents) specifying their agent’s name, S3 log location, sample percentage, judge model, and which of the <strong>27 available metrics</strong> to track—without touching a single line of pipeline code. Evaluating a curated, representative daily sample using a strong frontier judge model under consistent rubrics gave far sharper signal than running a weak judge over every chat.</p><h3>Insight 3: How a Healthy 0.85 Average Hid a Failing Client</h3><p>After running this orchestrator at scale, Arnav had a new headache: 10,000 raw JSON result files sitting in S3. Looking at thousands of text files — or a single company-wide average score — hid critical failures. When an agent’s overall weekly Goal Accuracy dipped slightly from 0.85 to 0.82, it looked like harmless noise.</p><p>So Arnav built a background sync service (backed by PostgreSQL) that read the daily S3 results and manifest files and organized them cleanly inside <strong>MLflow</strong>:</p><ul><li><strong>Workspaces:</strong> Separate workspaces for DEV, QA, and PROD so test runs never mixed with live traffic.</li><li><strong>Experiments:</strong> One dedicated experiment per AI agent.</li><li><strong>Runs:</strong> One run per conversation, tagged with conversation_id, tenant_id, judge_model, metric scores, and the judge’s written reasoning.</li><li><strong>Artifacts:</strong> Interactive <strong>Plotly HTML dashboards</strong> — weekly trend lines with smoothing sliders, tenant comparisons, token-cost charts, and conversation-by-metric heatmaps — attached directly inside MLflow.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_oEQuo8tYb_OnJDIwP6SJw.png" /></figure><h3>Five-Minute Debugging in Production</h3><p>Two months later, when Arnav opened the PROD workspace in MLflow and sliced a minor 0.82 Goal Accuracy dip by client, the company-wide average turned out to be hiding a localized outage: <strong>nine enterprise clients were sitting comfortably at </strong><strong>0.88, while Client B had plunged to </strong><strong>0.54.</strong></p><p>Arnav clicked into Client B’s monthly heatmap. <em>Faithfulness</em> was bright green (0.95), proving the LLM wasn’t hallucinating. <em>Retrieval Precision</em>, however, was solid red. He opened the lowest-scoring conversation run and read the judge’s exact note:</p><blockquote>“The retrieved context did not contain the client’s updated policy table.”</blockquote><p>In under five minutes — without grepping raw logs or blaming the LLM — Arnav knew Client B’s search index simply needed a refresh.</p><p>With the pipeline now running quietly on autopilot every night, Arnav is adding one final piece to the story: <strong>automated A/B testing</strong>, so whenever his team wants to test a new prompt or switch to a new model, they can run both versions side by side on the exact same real conversations and let the numbers decide which one ships.</p><h3>References</h3><h4>1. LLM-as-a-Judge &amp; Structured Rubrics (GEval)</h4><ul><li><strong>G-Eval: NLG Evaluation using GPT-4 with Better Human Alignment</strong> — Liu et al. (2023). The foundational paper introducing chain-of-thought evaluation criteria and token log-probability weighted scoring to reduce LLM judge variance.</li><li><em>arXiv:</em> [<a href="https://arxiv.org/abs/2303.16634">https://arxiv.org/abs/2303.16634</a>]</li><li><strong>DeepEval Documentation — G-Eval &amp; Custom Metrics</strong> — Official guide on building isolated, criteria-driven LLM evaluation metrics and extending custom evaluation classes.</li><li><em>Docs:</em> [<a href="https://docs.confident-ai.com/docs/metrics-llm-evals">https://docs.confident-ai.com/docs/metrics-llm-evals</a>]</li></ul><h4>2. RAG Evaluation &amp; Retrieval vs. Generation Metrics</h4><ul><li><strong>RAGAS: Automated Evaluation of Retrieval Augmented Generation</strong> — Es et al. (2023). Defines the distinction between retrieval quality (<em>Context Precision/Recall</em>) and generation loyalty (<em>Faithfulness</em> and <em>Answer Relevancy</em>), explaining why high faithfulness can coexist with poor retrieval.</li><li><em>arXiv:</em> [<a href="https://arxiv.org/abs/2309.15217">https://arxiv.org/abs/2309.15217</a>]</li></ul><h4>3. Experiment Tracking, Observability &amp; Scheduling Infrastructure</h4><ul><li><strong>MLflow Tracking &amp; GenAI Evaluation Documentation</strong> — Official documentation on structuring workspaces/experiments, logging per-run parameters/metrics, and attaching custom HTML/Plotly artifacts.</li><li><em>Docs:</em> [<a href="https://mlflow.org/docs/latest/tracking.html">https://mlflow.org/docs/latest/tracking.html</a>]</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f628b49e9f19" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/http-200-ok-yet-completely-wrong-how-we-built-an-observability-engine-for-ai-agents-f628b49e9f19">HTTP 200 OK, Yet Completely Wrong: How We Built an Observability Engine for AI Agents</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[KV Cache Explained: How LLMs Generate Tokens Faster and What It Costs in GPU Memory]]></title>
            <link>https://pub.towardsai.net/kv-cache-explained-how-llms-generate-tokens-faster-and-what-it-costs-in-gpu-memory-3504684a2bbd?source=rss-794441dc753f------2</link>
            <guid isPermaLink="false">https://medium.com/p/3504684a2bbd</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[llm-inference]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[ai-architecture]]></category>
            <dc:creator><![CDATA[Ujjwaldash]]></dc:creator>
            <pubDate>Wed, 25 Nov 2026 13:31:02 GMT</pubDate>
            <atom:updated>2026-11-25T13:31:02.377Z</atom:updated>
            <content:encoded><![CDATA[<p>At 2:14 AM, Rohan stared at his terminal in disbelief. His team had just deployed a fine-tuned 8B parameter model onto a dedicated GPU node, expecting crisp, real-time responses for their customer intelligence copilot. The first few words streamed out smoothly. By paragraph three, the stream sputtered like an engine running dry. By paragraph six, a single prompt was taking nearly twelve seconds to finish — and when ten users hit the endpoint at once, the GPU crashed with a dreaded CUDA out of memory error.</p><p>“The model weights are only 16 gigabytes,” Rohan muttered, staring at nvidia-smi on his 80GB A100. &quot;Where did the other 64 gigabytes go?&quot;</p><p>Welcome to the central paradox of modern Large Language Model (LLM) inference. Making an LLM think fast isn’t just about raw compute — it is about remembering what it already thought about, and paying the steep memory rent to store those memories. That mechanism is the <strong>KV (Key-Value) Cache</strong>.</p><h3>1. The Inference Problem: Why LLMs Slow Down Over Time</h3><p>Unlike traditional neural networks that take an input and spit out a complete answer in a single forward pass, decoder-only Transformers (like Llama, Qwen, and GPT) are <strong>autoregressive</strong>. They generate text one token at a time, feeding every newly generated token back into the model to predict the next one.</p><p>Suppose you give a model a 1,000-token prompt and ask for a 500-token summary:</p><ul><li>To generate token <strong>1,001</strong>, the model processes <strong>1,000</strong> tokens.</li><li>To generate token <strong>1,002</strong>, the model processes <strong>1,001</strong> tokens.</li><li>To generate token <strong>1,500</strong>, the model processes <strong>1,499</strong> tokens.</li></ul><p>Without optimization, the model recomputes the exact same internal representations for those first 1,000 prompt tokens <strong>500 separate times</strong>. Because self-attention compares every token against every preceding token, the total computational cost scales quadratically — O(N²) — with sequence length. Your GPU spends 95% of its energy re-reading the past instead of writing the future.</p><h3>2. Transformer Attention Fundamentals</h3><p>To understand how we eliminate this redundant work, we have to look inside a single Transformer layer’s self-attention block.</p><p>When a token’s embedding vector xₜ enters an attention layer, the model multiplies it by three learned weight matrices — W_Q, W_K, and W_V — to project the token into three distinct vectors:</p><ul><li><strong>Query (</strong>qₜ = xₜ · W_Q)<strong>:</strong> What this current token is looking for in the context.</li><li><strong>Key (</strong>kₜ = xₜ · W_K<strong>):</strong> What this token advertises about itself to future tokens.</li><li><strong>Value (</strong>vₜ = xₜ · W_V<strong>):</strong> The actual semantic information this token passes forward if a Query matches its Key.</li></ul><p>To compute the attention output for the newest token at position <em>t</em>, the model calculates how strongly its Query (qₜ) aligns with the Keys of <em>all</em> tokens from position <em>1 to t</em>, scales and normalizes those scores via Softmax, and takes a weighted sum of their Values:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*EcnyhpX1lHgyibCsIkJ2dA.png" /></figure><p>Here is the crucial insight: <strong>causal masking</strong>. In autoregressive generation, past tokens can never attend to future tokens. Because a past token’s embedding <em>x</em>ᵢ (where <em>ī </em>&lt; t) never changes once processed, its projections <em>k</em>ᵢ = <em>x</em>ᵢ · <em>W</em>_K and <em>v</em>ᵢ = <em>x</em>ᵢ · <em>W</em>_V remain <strong>completely static</strong> across every subsequent generation step.</p><h3>3. KV Cache Explained Visually</h3><p>Instead of recalculating k₁, k₂, …, kₜ₋₁ and v₁, v₂, …, vₜ₋₁ at every step, we save them in high-speed GPU High Bandwidth Memory (HBM) right after they are computed the first time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NXIc-3x94FTWhDaGs3ekOQ.png" /></figure><p>Look at what changes between the two workflows:</p><ul><li><strong>WITHOUT KV CACHE (Slow):</strong> To generate a new token (like “faster”), the model has to send every single previous token (“How”, “LLMs”, “generate”, “tokens”) along with the new one through the <strong>Transformer Attention</strong> block. This means the GPU must recalculate all previous keys and values at every single step. Compute effort grows with every word, making the system get slower and slower.</li><li><strong>WITH KV CACHE (Fast):</strong> The model processes the new token (“faster”) by calculating only its own brand-new query, key, and value (qₜ, kₜ, vₜ). It immediately appends kₜ, vₜ to the <strong>KV Cache</strong> stored in GPU Memory (HBM). To generate the output, <strong>Transformer Attention</strong> simply fetches the &quot;Saved Past KV&quot; from memory and combines it with the single new qₜ, kₜ, vₜ from &quot;faster&quot;. The past isn&#39;t recalculated—it’s just reused.</li></ul><p>We trade <strong>compute</strong> (FLOPs) for <strong>memory capacity and bandwidth</strong> (VRAM) to achieve a fast, constant generation speed.</p><h3>4. Step-by-Step Token Generation: Prefill vs. Decode</h3><p>When Rohan profiled his copilot’s latency the next morning, he discovered that LLM inference actually consists of two completely different phases with opposite hardware bottlenecks:</p><ul><li><strong>The Prefill Phase (Prompt Processing):</strong> You send the initial prompt: &quot;Summarize the Q3 revenue report...&quot; (say, 2,000 tokens). Because all 2,000 tokens are known upfront, the GPU processes them <strong>in parallel</strong> in one massive matrix-matrix multiplication (GEMM). During prefill, the model populates the initial KV Cache for all 2,000 tokens across every layer. This phase is <strong>compute-bound</strong>—it saturates the GPU&#39;s Tensor Cores and determines your <strong>Time to First Token (TTFT)</strong>.</li><li><strong>The Decode Phase (Autoregressive Generation):</strong> Now the model generates token 2,001, then 2,002, one by one. At each step, the GPU only multiplies a single token vector against the model weights and reads the entire stored KV Cache from HBM into on-chip SRAM to compute attention. Because the GPU reads gigabytes of weights and KV vectors just to perform math on <em>one</em> token, the Tensor Cores sit mostly idle waiting for memory transfers. This phase is <strong>memory-bandwidth-bound</strong> and determines your <strong>Time Per Output Token (TPOT)</strong>.</li></ul><h3>5. The Math: How Much GPU Memory Does the KV Cache Cost?</h3><p>Rohan pulled out a notepad to solve the mystery of his vanished 64GB of VRAM. Every single token in every active sequence stores a Key vector and a Value vector in every Transformer layer.</p><p>The exact memory footprint per token (in bytes) is:</p><pre>Bytes per Token = 2 × n_layers × n_kv_heads × d_head × bytes_per_param</pre><p>Let’s plug in the numbers for a classic <strong>Llama-2–7B</strong> architecture (which uses standard Multi-Head Attention where n_kv_heads = n_heads = 32, d_head = 128, n_layers = 32) running in FP16 (2 bytes):</p><pre>Bytes per Token = 2 × 32 × 32 × 128 × 2 = 524,288 bytes = 0.5 MB per token</pre><p>Now watch what happens at scale:</p><ul><li>A single request with an <strong>8,192-token</strong> context consumes 8,192 × 0.5 MB = <strong>4.0 GB</strong> of VRAM—just for one user!</li><li>With a batch size of <strong>16 concurrent users</strong>, the KV Cache alone demands <strong>64 GB</strong> of VRAM. Add 14 GB for the model weights, and an 80GB A100 runs completely out of memory.</li></ul><p>What about modern <strong>Llama-3–8B</strong>? Meta introduced <strong>Grouped-Query Attention (GQA)</strong> with n_kv_heads = 8 instead of 32—cutting the KV cache size by <strong>4x</strong> to <strong>128 KB per token</strong> (1 GB per 8K context). Even so, at 32K or 128K context windows across dozens of concurrent enterprise users, the KV cache easily dwarfs the model weights themselves.</p><h3>6. Performance Benchmarks: Compute vs. Bandwidth</h3><p>To see the impact empirically, consider an 8B parameter model (FP16) running on an NVIDIA A100–80GB GPU across varying sequence lengths:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aL-i7BgdZvbd5-9NogMKQg.png" /></figure><p>Notice two things:</p><ol><li>Without caching, moving from 512 to 4,096 tokens causes decode speed to collapse by <strong>nearly 8x</strong>. With KV caching, single-stream decode speed barely budges.</li><li>Increasing batch size from 1 to 32 only increases per-token latency slightly (from 13 ms to 28 ms) while multiplying total system throughput by <strong>15x</strong> — because the GPU loads the model weights once and amortizes that memory read across 32 users’ KV caches simultaneously.</li></ol><h3>7. Optimization Techniques: Taming the Memory Beast</h3><p>When Rohan realized his naive serving loop was pre-allocating contiguous memory chunks for maximum sequence lengths — wasting up to 70% of VRAM to fragmentation — he implemented four industry-standard optimizations:</p><ul><li><strong>Grouped-Query Attention (GQA) &amp; Multi-Query Attention (MQA):</strong> Architectural changes during training where multiple Query heads share a single Key and Value head. GQA (used in Llama 3, Mistral, and Qwen2.5) slashes KV memory by 4x–8x with virtually zero accuracy loss.</li><li><strong>PagedAttention (vLLM):</strong> Inspired by virtual memory paging in operating systems. Instead of reserving one giant contiguous block of VRAM per request, PagedAttention breaks the KV cache into small, non-contiguous fixed-size blocks (e.g., 16 tokens per block) mapped via a block table. Internal fragmentation drops below 4%, allowing 2x–4x larger batch sizes on the exact same GPU.</li><li><strong>FP8 / INT8 KV Cache Quantization:</strong> Compressing cached Keys and Values from 16-bit floats down to 8-bit numbers cuts KV memory footprint and HBM bandwidth pressure in half, preserving &gt;99% of model quality on long-context reasoning tasks.</li><li><strong>Prefix Caching (Automatic Context Reuse):</strong> If 500 user requests share the exact same 3,000-token system prompt or RAG document block, the serving engine computes those KV blocks once, hashes them, and shares the read-only physical memory blocks across all concurrent requests — dropping TTFT for cached prefixes by up to 80%.</li></ul><h3>8. Production Deployment and Trade-Offs</h3><p>In production inference engines like <strong>vLLM</strong>, <strong>TensorRT-LLM</strong>, or <strong>SGLang</strong>, every configuration knob balances three competing forces: <strong>latency (TTFT/TPOT)</strong>, <strong>throughput</strong>, and <strong>VRAM stability</strong>.</p><ul><li><strong>Throughput vs. Latency:</strong> Large batch sizes maximize GPU utilization and lower cost per million tokens, but once the combined size of model weights plus active KV caches saturates HBM bandwidth, every user experiences sluggish streaming.</li><li><strong>Preemption &amp; Swapping:</strong> When an unexpected spike of long-context prompts fills the KV block pool, the scheduler must either <strong>preempt</strong> lower-priority requests (evicting their KV cache and recomputing it later) or <strong>swap</strong> KV blocks over PCIe to CPU RAM — trading a temporary latency spike to prevent an OOM crash.</li><li><strong>Disaggregated Prefill and Decode:</strong> At massive scale, production architectures separate compute-heavy Prefill nodes from memory-heavy Decode nodes, transferring the newly computed KV cache over high-speed NVLink or InfiniBand so long prompts never stall active token streams.</li></ul><p>9. Conclusions</p><p>Before signing off that night, Rohan ran a quick benchmark script on his workstation to verify the exact speed and memory trade-off using PyTorch and Hugging Face transformers:</p><p>Python</p><pre>import time<br>import torch<br>from transformers import AutoModelForCausalLM, AutoTokenizer<br><br>model_id = &quot;Qwen/Qwen2.5-3B-Instruct&quot;<br>tokenizer = AutoTokenizer.from_pretrained(model_id)<br>model = AutoModelForCausalLM.from_pretrained(<br>    model_id, torch_dtype=torch.float16, device_map=&quot;cuda&quot;<br>)<br><br>prompt = &quot;Explain distributed consensus in detail. &quot; * 40  # ~320 tokens<br>inputs = tokenizer(prompt, return_tensors=&quot;pt&quot;).to(&quot;cuda&quot;)<br><br>def benchmark(use_cache: bool):<br>    torch.cuda.empty_cache()<br>    torch.cuda.reset_peak_memory_stats()<br>    start = time.perf_counter()<br>    with torch.no_grad():<br>        _ = model.generate(<br>            **inputs,<br>            max_new_tokens=256,<br>            use_cache=use_cache,<br>            do_sample=False,<br>        )<br>    torch.cuda.synchronize()<br>    elapsed = time.perf_counter() - start<br>    peak_mem_gb = torch.cuda.max_memory_allocated() / (1024 ** 3)<br>    print(f&quot;use_cache={use_cache:&lt;5} | Time: {elapsed:.2f}s | Peak VRAM: {peak_mem_gb:.2f} GB&quot;)<br><br>benchmark(use_cache=True)<br>benchmark(use_cache=False)</pre><p>With use_cache=True, generating 256 tokens finished in <strong>3.4 seconds</strong>. Turning it off (use_cache=False) stretched the exact same generation to <strong>14.8 seconds</strong>—and the gap widens exponentially as prompts grow longer.</p><p>By migrating his deployment to a PagedAttention engine with FP8 KV quantization and shared system-prompt prefix caching, Rohan brought his copilot’s p95 latency back under 400 milliseconds and tripled concurrent user capacity on the same A100.</p><p>The takeaway for every AI engineer moving from prototype to production is simple: <strong>model weights are a fixed entry fee, but the KV cache is the variable rent.</strong> Master how it is allocated, compressed, and reused, and you turn sluggish, memory-starved models into fast, scalable systems.</p><h3>References</h3><p>Kwon, W., Li, Z., Zhuang, S., Sheng, Y., Zheng, L., Yu, C. H., Gonzalez, J., Zhang, H., &amp; Stoica, I. (2023). Efficient Memory Management for Large Language Model Serving with PagedAttention. <em>Proceedings of the 29th Symposium on Operating Systems Principles</em>, 611–626. <a href="https://doi.org/10.1145/3600006.3613165">https://doi.org/10.1145/3600006.3613165</a> (arXiv PDF: <a href="https://arxiv.org/pdf/2309.06180">https://arxiv.org/pdf/2309.06180</a>) Cited by: 11608</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3504684a2bbd" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/kv-cache-explained-how-llms-generate-tokens-faster-and-what-it-costs-in-gpu-memory-3504684a2bbd">KV Cache Explained: How LLMs Generate Tokens Faster and What It Costs in GPU Memory</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Self-Hosted LLMs vs. Cloud APIs: How to Choose the Right Architecture]]></title>
            <link>https://pub.towardsai.net/self-hosted-llms-vs-cloud-apis-how-to-choose-the-right-architecture-91082ca28e41?source=rss-794441dc753f------2</link>
            <guid isPermaLink="false">https://medium.com/p/91082ca28e41</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[ai-systems-engineering]]></category>
            <category><![CDATA[ai-architecture]]></category>
            <category><![CDATA[mlops]]></category>
            <dc:creator><![CDATA[Ujjwaldash]]></dc:creator>
            <pubDate>Sun, 22 Nov 2026 18:35:20 GMT</pubDate>
            <atom:updated>2026-11-23T03:27:14.053Z</atom:updated>
            <content:encoded><![CDATA[<h4>A practical decision framework for AI engineers, architects !</h4><p>Imagine you are the lead AI engineer on a fast growing product team. Six months ago, you shipped an AI-powered document extraction feature in a weekend. You wired up a managed LLM API, wrote a clean prompt, and celebrated as your first thousand user fell in love with it.</p><p>Then the product took off.</p><p>One morning, your VP of Engineering drops a Slack message with a screenshot of the monthly cloud bill. Token costs have quietly climbed from a few hundred dollars to five figures. Right on cue, someone in the channel says the words every AI engineer eventually hears:</p><p>“Why don’t we just download an open-source model, rent a GPU, and host it ourselves? We’ll cut our bill in half.”</p><p>On paper, it sounds obvious. In production, that single sentence has launched dozens of expensive, half-finished infrastructure migrations.</p><p>The truth is, choosing between a cloud API and a self-hosted LLM isn’t a simple debate between <em>“APIs are easy”</em> and <em>“self-hosting is cheap.”</em> It is a systems engineering story about utilization, tail latency, hidden operational taxes, and knowing exactly when your workload crosses the mathematical tipping point.</p><p>Here is how that story actually plays out when you build it for the real world.</p><h3>Act I: Understanding Your Three Real Options</h3><p>When your team starts debating where to run the model, the first trap is thinking you only have two choices: pay a giant AI lab per token, or buy a GPU and build everything from scratch.</p><p>In reality, you are walking along a three-step spectrum of control and responsibility:</p><ol><li><strong>Managed LLM APIs (The Utility Grid):</strong> You call an endpoint like Amazon Bedrock, OpenAI, or Anthropic and pay strictly for the tokens you consume. You don’t know what GPUs are running in the background, and you don’t care. It works like electricity from a wall outlet — effortless to start, effortless to scale, linear in cost.</li><li><strong>Managed Model Hosting (The Leased Generator):</strong> Services like AWS SageMaker JumpStart, Together AI, or Fireworks sit right in the middle. You bring an open-weight or custom fine-tuned model — say, Llama-3–8B or Qwen2.5 — and the vendor manages the underlying serving infrastructure on a dedicated or serverless endpoint. You own the model weights without owning the Kubernetes headaches.</li><li><strong>Self-Hosted LLMs (Building Your Own Power Plant):</strong> You rent raw cloud GPUs (like an NVIDIA L4, A100, or H100) or use on-prem hardware, install an inference engine like <strong>vLLM</strong> or <strong>TensorRT-LLM</strong>, and tune everything yourself. (Remember: renting an AWS GPU instance is still “cloud” — it simply hands the steering wheel of the serving stack over to your team.)</li></ol><p>Before moving a single line of code, look at what changes as you walk from left to right across that spectrum:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nhn8VTKTqAOsJ1L70wKwTQ.png" /></figure><blockquote><strong>The first hard lesson:</strong> Self-hosting does not automatically buy you better privacy, lower latency, or lower cost. A poorly tuned open-weight model running on an underutilized GPU can easily be slower, pricier, and less secure than a SOC2-compliant enterprise API with Zero Data Retention (ZDR) turned on.</blockquote><h3>Act II: Doing the Math on the Whiteboard</h3><p>To settle the Slack debate, you pull your team up to a whiteboard. As the <strong>OECD’s 2026 analysis on AI openness and hosting economics</strong> points out, the financial break-even point between APIs and private hosting isn’t a fixed number — it shifts dramatically depending on your traffic patterns and hidden infrastructure costs.</p><p>You write down two simple equations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*uUhpGBfvTdWBSRvjePGb_Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*BysBYI-sB_jC5Pcs1SaEfg.png" /></figure><p>Here is what happens when you plug real numbers into your document-extraction pipeline, where every request processes <strong>1,500 input tokens</strong> and generates <strong>300 output tokens</strong>:</p><ul><li><strong>The Managed API Baseline:</strong> Using a fast, capable 8B-class managed API priced at <strong>$0.15 per 1M input tokens</strong> and <strong>$0.60 per 1M output tokens</strong>, every single request costs you <strong>$0.000405</strong> (about four-hundredths of a cent).</li><li><strong>The Self-Hosted Baseline:</strong> To run an equivalent open-weight 8B model smoothly with <strong>vLLM</strong>, you rent a 24GB GPU instance (like an NVIDIA L4 or A10G) at roughly <strong>$1,000/month</strong>.</li></ul><p>Now watch what happens as your company grows across three stages:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/909/1*2JiLrh9v7cSsRlfZcP9PhQ.png" /></figure><h3>Act III: When Speed and Memory Rewrite the Rules</h3><p>Suppose your traffic <em>does</em> hit 25 million requests a month. Does self-hosting automatically win? Not until you look at <strong>latency and memory</strong>.</p><p>On a multi-tenant cloud API, you are sharing massive clusters with thousands of other companies. Most of the time, responses fly back. Occasionally, noisy neighbors cause your <strong>Time to First Token (TTFT)</strong> to spike unpredictably — a nightmare if you are building real-time voice agents or interactive UI copilots.</p><p>When you self-host with <strong>vLLM</strong>, you take control of the engine room. Using <strong>PagedAttention</strong> and <strong>continuous batching</strong>, you eliminate memory fragmentation and lock in predictable P95 latency. Better yet, if every request shares a long system prompt or a 10,000-token compliance rubric, <strong>prefix caching</strong> lets your GPU compute that prompt once and reuse the KV cache across thousands of incoming queries.</p><p>On the flip side, if your users suddenly start uploading 50-page PDFs (32k+ context lengths), the KV cache explodes in size. Your neat little 24GB GPU runs out of VRAM, forcing an upgrade to scarce, expensive 80GB A100 or H100 nodes — pushing your break-even point right back up the mountain.</p><h3>Act IV: The Plot Twist — You Don’t Have to Pick One</h3><p>At the end of your whiteboard session, the team realizes the original Slack question was flawed. Asking <em>“Should we use an API or self-host?”</em> is like asking a logistics company whether it should only own semi-trucks or only use couriers.</p><p>Mature AI systems don’t pick a single winner. They build a <strong>tiered hybrid router</strong> that sends every request down the cheapest, fastest path capable of solving it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9ToJnrVJ-jnykVrAPPzDig.png" /></figure><p>Look at how cleanly this resolves every tension in the room:</p><ul><li><strong>Deterministic code goes first:</strong> Before touching a single GPU, clean Python logic, regex, or SQL handles the predictable 25% of inputs at zero token cost and sub-5ms latency.</li><li><strong>Your self-hosted model does the heavy lifting:</strong> The steady, high-volume middle tier — entity extraction, PII redaction, schema formatting — runs on your own tuned 8B model, keeping your GPUs humming near an optimal 75–80% utilization day and night.</li><li><strong>The managed API acts as your brain and safety net:</strong> The hardest 10% of ambiguous edge cases — plus any unexpected noon traffic spikes that would otherwise overwhelm your GPU cluster — route seamlessly to a frontier cloud API.</li></ul><h3>Epilogue: Your 5-Question Architecture Checklist</h3><p>The next time someone asks whether your team should self-host an LLM, skip the dogma and walk through these five questions:</p><ol><li><strong>Is our baseline traffic steady enough to keep at least 2 GPUs above 50–60% utilization?</strong> <em>(If no, stay on a Managed API.)</em></li><li><strong>Have we proven on our own eval dataset that an open-weight model matches the quality we need?</strong> <em>(If no, keep using a frontier API while you collect fine-tuning data.)</em></li><li><strong>Do strict compliance or data-residency laws forbid external APIs even under a Zero Data Retention contract?</strong> <em>(If yes, move to Managed Hosting in a VPC or Self-Host.)</em></li><li><strong>Do we have engineers ready to own CUDA memory tuning, model rollouts, and 3:00 AM GPU alerts?</strong> <em>(If no, let a managed provider carry that pager.)</em></li><li><strong>Can we separate our workload into high-volume routine tasks and low-volume complex reasoning?</strong> <em>(If yes, build a hybrid router and get the best of both worlds.)</em></li></ol><h3>Further Reading &amp; Technical References</h3><ul><li><a href="https://www.oecd.org/en/publications/oecd-digital-economy-and-society-outlook-2026_022ed474-en/full-report/digital-technology-diffusion-and-the-economy_b355e780.html"><strong>OECD (2026):</strong> <em>AI Openness and Hosting Economics</em> — Empirical modeling of compute utilization and break-even thresholds across deployment tiers.</a></li><li><a href="https://docs.vllm.ai/en/latest/"><strong>vLLM Documentation:</strong> <em>Production Metrics &amp; PagedAttention</em> — Deep dive into KV-cache memory management, TTFT, and continuous batching.</a></li><li><strong>Amazon Bedrock &amp; AWS Pricing Guides:</strong> Reference token pricing vs. dedicated EC2 GPU instance rates (g5 / p4d / p5).</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91082ca28e41" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/self-hosted-llms-vs-cloud-apis-how-to-choose-the-right-architecture-91082ca28e41">Self-Hosted LLMs vs. Cloud APIs: How to Choose the Right Architecture</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>