<?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 David Oy on Medium]]></title>
        <description><![CDATA[Stories by David Oy on Medium]]></description>
        <link>https://medium.com/@thedavidoy?source=rss-e20dc259cf29------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xD_BaZCcPvvm5HgIi6TEFQ.jpeg</url>
            <title>Stories by David Oy on Medium</title>
            <link>https://medium.com/@thedavidoy?source=rss-e20dc259cf29------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 02:16:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@thedavidoy/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[Your Inference Engine is Quietly Changing Your RL Training]]></title>
            <link>https://medium.com/why-david-y/your-inference-engine-is-quietly-changing-your-rl-training-1841c477718c?source=rss-e20dc259cf29------2</link>
            <guid isPermaLink="false">https://medium.com/p/1841c477718c</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <dc:creator><![CDATA[David Oy]]></dc:creator>
            <pubDate>Mon, 23 Nov 2026 21:36:41 GMT</pubDate>
            <atom:updated>2026-11-23T21:49:13.032Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How the serving stack turns on-policy RL off-policy and what to do about it.</em></p><h3>The run that went wrong</h3><p>Something strange happens around step 300. Your reinforcement learning has been climbing for days. Reward is up, the evaluations are up, the team is optimistic. Then the curve bends. Reward flattens, slides, and hands back a week of progress. The loss spikes once, twice. You do what everyone does: blame the reward model, the data mix, the KL coefficient, the learning rate schedule. You retune all of them. The next run dies the same way, a little later.</p><p>The bug is not in your training configuration. It is not in your algorithm. It lives in a different codebase, owned by a different team: the inference engine that generated your training data.</p><p>Your rollout engine and your trainer disagree about what your model is. They hold identical weights and produce different numbers. That disagreement is one of the most common silent causes of RL instability, and almost nobody outside the post-training world has heard of it.</p><h3>Two calculators, one homework assignment</h3><p>Two calculators sit side by side. You type the same addition equation into both and get answers that differ in the last digit. Annoying but trivial. Now imagine one calculator does the homework and the other grades it. The grader insists its answer key is right. The worker insists it followed the answer key exactly. Both are telling the truth. The homework still gets worse.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pT68W7z0B-OvCkHK" /><figcaption>Photo by <a href="https://unsplash.com/@towfiqu999999?utm_source=medium&amp;utm_medium=referral">Towfiqu barbhuiya</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>That is a modern RL post-training loop:</p><ol><li><strong>Rollout.</strong> The model generates completions to prompts, using a fast inference engine such as vLLM or SGLang.</li><li><strong>Scoring.</strong> A reward model or verifier scores each completion.</li><li><strong>Training.</strong> The trainer recomputes the probabilities of those completions and nudges the weights toward the good ones.</li></ol><p>Step 3 hides an assumption. Algorithms like PPO and GRPO are on-policy: they assume the completions were produced by the exact model being updated. The correction term in the loss is a ratio, the probability of a token under the training model divided by its probability under the model that sampled it. If the same model did both jobs, the ratio is exactly 1 and the term vanishes.</p><p>Two different engines did those jobs. Rollout ran on a serving stack tuned for speed: batched, quantized, kernel-optimized. Training ran on FSDP or Megatron, tuned for memory and throughput of a different kind. Different software results in different arithmetic.</p><h3>Why two engines give two answers</h3><p>Floating-point addition is not associative. In exact math, (a + b) + c equals a + (b + c). On a GPU, the last bits differ depending on the order of the sums. Every forward pass is a mountain of additions, the order is chosen by the kernel, and the kernel is chosen by the shape of the work.</p><p>Now consider what an inference server does all day. It batches requests together, and the batch changes every few milliseconds as requests arrive and finish. Small batch, one kernel. Large batch, another. <a href="https://vllm.ai/blog/2026-10-14-train-inference-consistency">vLLM’s write-up</a> on this non-determinism lists an example: its FP8 linear layer runs FlashInfer below 32 tokens and DeepGEMM at or above. The same request, submitted twice, can differ in the last bits depending on who else happened to share the batch.</p><p>Thinking Machines <a href="https://thinkingmachines.ai/blog/defeating-nondeterminism-in-llm-inference/">measured this last year</a>. They sent the same prompt, “Tell me about Richard Feynman,” to the same model 1,000 times at temperature zero, the setting that should be deterministic. They got 80 unique completions back. The most common appeared 78 times. 992 said Feynman was born in “Queens, New York.” Eight said “New York City.” Same prompt, same weights, same temperature. The only variable was the invisible one: server load.</p><p>Their post traced the cause to missing batch invariance and fixed it inside one engine. It became one of the most-read systems posts of 2025, framed around reproducibility. They addressed nondeterminism due to batch variance, though that leaves gaps due to other causes, such as the gap between two engines.</p><h3>On-policy, quietly off-policy</h3><p>On-policy learning means learning from your own moves as you play. Off-policy means learning from someone else’s game. Off-policy RL is harder: the data no longer matches the current policy, so the updates need corrections</p><p>The train-inference gap means your on-policy algorithm is becoming off-policy. The importance ratio you assumed was 1.000 is really 1.003, then 1.01, then worse. And it drifts. Each gradient step pulls the trainer’s version of the model slightly further from the sampler’s version, so the gap widens as training proceeds. A feedback loop with a slow fuse.</p><p>This is no longer folklore. In October, the vLLM team published a <a href="https://vllm.ai/blog/2026-10-14-train-inference-consistency">controlled experiment on DeepSeek-V4-Flash</a>: with a high-performance rollout stack and no correction, the KL divergence between trainer and sampler climbed from 0.002 to 29.9 over a hundred steps while reward fell back.</p><p>Mixture-of-experts models sharpen all of it. In an MoE model, a small router network decides which experts handle each token. A difference in the sixth decimal place doesn’t just nudge a probability. It can flip a routing decision, and a flipped route means a different set of experts, a different computation path, a different model for that token. A <a href="https://arxiv.org/abs/2510.11370">recent paper</a> from Xiaomi and Peking University shows this routing disagreement can collapse MoE RL training entirely. Their fix is direct: record which experts the inference engine chose, and replay those choices during training.</p><h3>The fix ladder</h3><p>Here is how I would work through this, starting with the lowest-effort steps.</p><p><strong>Rung 0: Measure.</strong> Log the KL divergence or the mean logprob gap, between trainer and sampler at every step. In most stacks this is a few lines of code, and it turns a silent failure into a visible one. <em>This first step is important.</em></p><p><strong>Rung 1: Correct the algorithm.</strong> Since the ratio isn’t 1, compute it for real and reweight, clipping the extremes so a few outlier tokens don’t dominate. This is truncated importance sampling, merged into <a href="https://github.com/huggingface/trl/pull/3867">Hugging Face’s Transformers Reinforcement Learning</a> in September 2025. It costs almost nothing, keeps your fast serving stack, and buys real stability. But it is a correction, not a cure. When the underlying gap grows large, the clipping throws away most of the signal in your data.</p><p><strong>Rung 2: Align the systems.</strong> Make the two sides share more than weights. R3 replays the rollout engine’s routing decisions. vLLM’s IsoExec work runs trainer and inference through unified execution so the same code paths serve both. Each removes a specific source of divergence instead of papering over all of them at once.</p><p><strong>Rung 3: Make them bitwise identical.</strong> The training forward pass calls the inference kernels directly, with every batch-size-dependent branch removed, so both sides produce literally the same bits. <a href="https://vllm.ai/blog/2026-10-14-train-inference-consistency">vLLM</a> did this and held the difference at exactly zero for a hundred consecutive steps, at about 91% of baseline rollout throughput, with a follow-up recipe reporting roughly 10% end-to-end overhead with training optimization pending. Impressively, for Nemotron, a hybrid Mamba model in FP4, the bitwise-consistent run held its SWE-bench score while the uncorrected baseline fell from 0.56 to 0.22.</p><p>Rungs 0 and 1 are table stakes for anyone doing RL post-training today; they are nearly free. Rung 2 is where serious MoE work is heading. Rung 3’s effort is significant but falling with frameworks and engines improving. Next to the cost of a collapsed training run, 10% looks pretty reasonable.</p><h3>The punchline</h3><p>For years, inference was downstream of training. The lab trained the model, handed over a weights file, and the serving team’s job was to run it fast and cheap. That division of labor is over. In the RL era the inference engine sits inside the training loop: it generates the data, and its numerics define which model the optimizer thinks it is improving. Every serving decision, batching, quantization, kernel dispatch, is now also a training decision.</p><p>When inference and training disagree numerically, on-policy training quietly becomes off-policy. Closing that gap is one of the central challenges of RL post-training today.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hHSW-o1JeRAwVUFi" /><figcaption>Photo by <a href="https://unsplash.com/@cashmacanaya?utm_source=medium&amp;utm_medium=referral">Cash Macanaya</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1841c477718c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/why-david-y/your-inference-engine-is-quietly-changing-your-rl-training-1841c477718c">Your Inference Engine is Quietly Changing Your RL Training</a> was originally published in <a href="https://medium.com/why-david-y">Why David Y</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Autoscaling the AI Subway]]></title>
            <link>https://medium.com/data-science-collective/autoscaling-the-ai-subway-tokenscale-99c9d93ce616?source=rss-e20dc259cf29------2</link>
            <guid isPermaLink="false">https://medium.com/p/99c9d93ce616</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[David Oy]]></dc:creator>
            <pubDate>Thu, 18 Dec 2025 10:19:05 GMT</pubDate>
            <atom:updated>2025-12-18T10:19:05.154Z</atom:updated>
            <content:encoded><![CDATA[<h4>A guide to token velocity and convertible trains</h4><p>Every AI team eventually has its rush hour story.</p><p>You launch a new feature, a demo goes viral, or the CEO mentions your chatbot on stage. For a while, everything looks fine. Then graphs spike, time to first token creeps up, answers start stuttering, and someone says, “But GPU utilization looks okay… why is it still slow?”</p><p>Autoscaling is supposed to save you: add machines when traffic spikes, scale down when it’s quiet. But with modern LLM setups where different machines handle the first pass (prefill) and the streaming replies (decode), simple rules — “scale when GPUs look busy” or “scale when requests per second go up” — aren’t enough.</p><figure><img alt="Disaggregated inference presented as a train station" src="https://cdn-images-1.medium.com/max/1024/0*AwzWuWTtNVt4ovzc" /><figcaption>Running disaggregated inference can feel like managing a train station. | Photo by <a href="https://unsplash.com/@marina_mv08?utm_source=medium&amp;utm_medium=referral">Marina Vitale</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The <a href="https://arxiv.org/abs/2512.03416">TokenScale</a> research paper tackles this problem for LLM systems that split prefill and decode and still have to survive sudden traffic spikes. It brings two big ideas: <strong>token velocity</strong>, a better way to measure how busy each stage really is; and <strong>convertible decoders</strong>, decode workers that can temporarily help with prefill during rush hour.</p><p>This post walks through those ideas in human terms, without equations, but with enough detail for infrastructure folks to see what’s going on.</p><h3>Why Autoscaling Disaggregated LLMs Is Harder Than It Looks</h3><p>If you’ve read about <a href="https://medium.com/data-science-collective/why-chatbots-feel-fast-ai-inference-72c175d53d59">disaggregated inference</a>, you’ve seen this pattern:</p><ul><li><strong>Prefill</strong>: a pool of workers runs the heavy first pass over each prompt (reading the full context, building up internal state).</li><li><strong>Decode</strong>: a separate pool streams tokens for ongoing conversations, reusing that state.</li></ul><p>This split is great for efficiency and latency: you can tune prefill for throughput, decode for smooth streaming, and scale each side independently.</p><p>It also makes autoscaling harder, especially under bursty traffic:</p><ul><li>A <strong>burst of new chats</strong> pounds prefill. Time to first token (TTFT) is at risk long before GPU utilization looks scary.</li><li>A few <strong>long, chatty sessions</strong> saturate decoders and memory, even if request counts look modest.</li><li>The <strong>network between prefill and decode</strong> can briefly become the bottleneck when lots of internal state is being shipped around.</li></ul><p>Traditional autoscaling signals such as CPU/GPU utilization, request counts, and average latency are lagging indicators. By the time they look bad, users have already felt the slowdown.</p><p>TokenScale, a new paper from December 2025, changes this paradigm: instead of watching just “how full are my trains,” it measures <strong>how many tokens per second actually flow through each stage</strong> and scales based on that.</p><figure><img alt="LLM work measured by tokens, not queries." src="https://cdn-images-1.medium.com/max/1024/0*-U9x9BaRZ7FoMukU" /><figcaption>Tokens are the main unit of work in LLMs, not queries. | Photo by <a href="https://unsplash.com/@scottsdalemint?utm_source=medium&amp;utm_medium=referral">Scottsdale Mint</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>A Quick Refresher: Prefill, Decode, and Promises to Users</h3><p>Imagine your LLM service as a subway at rush hour:</p><ul><li><strong>Prefill</strong> is the entrance turnstiles and escalators: everyone passes through once to enter. Heavy but short work per rider.</li><li><strong>Decode</strong> is the trains: once riders are on, they go station by station (token by token) until they reach their destination.</li><li>The <strong>network</strong> is the tunnel between lines: it moves passengers (the model’s internal memory, often called KV cache) from one line to another.</li></ul><p>You’re usually tracking two user-facing promises:</p><ul><li><strong>TTFT (Time To First Token)</strong> — “How long until the first train shows up?”</li><li><strong>TPOT (Time Per Output Token)</strong> — “Once we’re moving, how fast do the stations tick by?”</li></ul><p>Teams write these down as reliability targets like: “95% of users should see the first token in under 1 second, and tokens should stream at or below X milliseconds per token.” In practice, those guarantees are measured over windows (p95 over five minutes or an hour), but consistently missing them is what makes a system feel unreliable.</p><p>Under steady traffic, you can size your entrance and trains reasonably well. Under bursty traffic, it’s messier:</p><ul><li>A launch event sends a rush of new riders to the entrance: TTFT blows up if you don’t add turnstiles quickly.</li><li>A handful of people ride all the way to the end of the line: TPOT blows up if you don’t add trains or adjust batching.</li></ul><p>You need to scale the entrance and trains differently, and you need to see the spike coming <em>before</em> your “how fast does it feel?” promises are already broken.</p><p>That’s where token velocity comes in.</p><h3>Token Velocity: Watching the Flow, Not Just the Crowd</h3><p>Most autoscalers watch things like “how many people are in the station” (GPU utilization) or “how many arrived in the last second” (requests per second). TokenScale asks a different question:</p><blockquote><strong><em>How many tokens per second can this stage actually move when it’s fully busy, and how many tokens per second are currently arriving?</em></strong></blockquote><p>Think of <strong>token velocity</strong> as a stage’s sustainable speed: how many tokens it can push through each second when it’s fully loaded.</p><ul><li>For <strong>prefill</strong>, token velocity is input tokens processed per second under load.</li><li>For the <strong>network</strong>, it’s tokens of internal state moved per second.</li><li>For <strong>decode</strong>, it’s output tokens generated per second (for different request types/lengths).</li></ul><p>In practice, token velocity isn’t a magical constant; it’s measured empirically per model, hardware, and request bucket, so it already bakes in scheduler overheads, batching effects, and contention. TokenScale treats it as the realistic token rate this stage can sustain, not a theoretical upper bound.</p><p>The paper does two things with this:</p><ol><li>It profiles these speeds ahead of time for each model/GPU combo and request type.</li><li>At runtime, it watches how many tokens per second are actually arriving at each stage.</li></ol><p>Then autoscaling becomes conceptually simple:</p><ul><li>If incoming tokens/s for prefill approach prefill token velocity, you need more prefillers.</li><li>If incoming tokens/s for decode approach decode token velocity for that traffic mix, you need more decoders.</li><li>If the network’s token velocity is much higher than both, you can mostly ignore it as a bottleneck (which they find on modern clusters).</li></ul><p>Token velocity gives you an earlier warning signal than utilization or average latency, because you watch how quickly work is arriving relative to sustainable capacity. It’s still approximate , as there can be short windows and noisy workloads, but it moves the signal closer to where SLO violations actually come from.</p><figure><img alt="Using token velocity provides a warning to your autoscaler sooner that it needs to scale up or down prefill/decode workers." src="https://cdn-images-1.medium.com/max/1024/0*WtYkkT19BANTfMwh" /><figcaption>Token velocity provides signal to your autoscaler earlier. | Photo by <a href="https://unsplash.com/@bmpanaguiton?utm_source=medium&amp;utm_medium=referral">Breana Panaguiton</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote><strong><em>Sidebar: For infrastructure folks</em></strong></blockquote><blockquote><em>Formally, token velocity is the max token throughput each stage can sustain under full load, profiled offline per model/GPU and request bucket.</em></blockquote><blockquote><em>At runtime, TokenScale estimates token arrival rates per stage from recent history and picks the smallest number of prefillers/decoders whose aggregate Token Velocity, plus a safety margin, covers those rates for the target TTFT/TPOT. Compared to utilization-based autoscaling, this yields an anticipatory, service level objective-aligned signal, especially in disaggregated setups.</em></blockquote><h3>Why Traditional Metrics Struggle with Disaggregated Serving</h3><p>Two types of bursts stress different parts of the system:</p><ul><li><strong>Request burst</strong>: many short prompts with short answers → crushes <strong>prefill</strong>, risking TTFT.</li><li><strong>Token burst</strong>: a few prompts with very long outputs → crushes <strong>decode</strong>, risking TPOT, even if queries per second (QPS) is low.</li></ul><p>Older autoscalers have trouble here:</p><ul><li><strong>GPU utilization</strong>: lags both bursts. By the time it spikes, users have already seen bad latency. It also doesn’t tell you <em>which</em> stage is in trouble.</li><li><strong>Request-count scaling</strong>: sees the request burst but underestimates the token burst. A few long generations can saturate decode while request counts stay under threshold.</li><li><strong>Global metrics</strong>: one latency or utilization number ignores the prefill/decode split, so you either under-provision the stage that matters or over-provision both just in case.</li></ul><p>Token velocity fixes this by using <strong>tokens, not requests</strong>, as the unit of work and by <strong>modeling prefill and decode separately</strong>. In the paper’s examples, token velocity–based autoscaling catches both kinds of bursts and scales prefillers and decoders appropriately, where utilization/QPS policies either react too slowly or in the wrong place.</p><h3>Convertible Decoders: Trains That Change Lines During Rush Hour</h3><p>Even with better signals, spin-up time is still a problem. Starting new prefillers takes time:</p><ul><li>Initializing processes or containers.</li><li>Allocating GPU memory.</li><li>Loading model weights.</li></ul><p>In a real spike, by the time new prefillers are ready, TTFT may already have blown past your target.</p><p>TokenScale’s second idea, <strong>convertible decoders</strong>, addresses this:</p><blockquote><em>A subset of decoder workers are pre-configured so they can temporarily act as prefillers when new requests spike, then slide back into decode duty once the rush passes.</em></blockquote><p>Back to the subway:</p><ul><li>Most trains run their regular routes (decode).</li><li>A few trains are designated as convertible: during rush hour, they’re allowed to run extra service at the station entrances (prefill), then rejoin normal service.</li></ul><p>In TokenScale:</p><ul><li>A fixed number of decoders are marked as convertible. They hold the same model and are wired into routing.</li><li>When prefill token arrival rate spikes over a short window and threatens TTFT, the controller starts sending some new prefill work to convertible decoders instead of waiting for new prefillers.</li></ul><p>Convertible decoders:</p><ul><li>Run <strong>chunked prefill</strong> (short segments) so they don’t starve ongoing decode work.</li><li>Immediately decode for the requests they just prefilled, avoiding extra shuffling of internal state between machines.</li></ul><p>Conversion is just a smarter routing choice, not a full rebuild. Switching a decoder into prefill mode is fast because the model is already loaded on that machine. Decode work still gets priority: Convertible decoders only take on extra prefill when they have slack and drop back to pure decode once memory or decode latency nears a threshold. You’re trading a bounded amount of decode capacity to avoid big TTFT spikes, not turning decoders into full-time prefillers.</p><figure><img alt="An image of a Transformer to show that convertible decoders can also “transform” into the roll of a prefill worker." src="https://cdn-images-1.medium.com/max/1024/0*2NGT2KNvnj2tpF9r" /><figcaption>Convertible decoders can transform to play multiple roles. | Photo by <a href="https://unsplash.com/@tetrakiss?utm_source=medium&amp;utm_medium=referral">Arseny Togulev</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote><strong><em>Sidebar: For infrastructure folks</em></strong></blockquote><blockquote><em>Convertible decoders are a small, pre-reserved subset of decoders with their own capacity budget. TokenScale chooses their count offline based on burstiness, treats them as a special pool in the load balancer, and uses chunked prefill so per-iteration work stays bounded and TPOT SLOs are respected.</em></blockquote><blockquote><em>Decode is prioritized over prefill, and convertible decoders stop taking prefill once memory or decode latency crosses a threshold to avoid creating new tails on the decode side.</em></blockquote><h3>A Rush Hour Story: Where These Ideas Help</h3><p>Let’s put both ideas together in a concrete scenario.</p><h4>Scenario: Product launch, many short prompts</h4><p>You launch an LLM-powered summarization feature. Normally traffic is steady. Launch day brings a burst of new, short prompts:</p><ul><li>Prefill token arrival rate spikes sharply.</li><li>Decode remains moderate: most answers are short paragraphs.</li></ul><p>With utilization- or request-based autoscaling:</p><ul><li>Prefillers back up; TTFT climbs.</li><li>Metrics look bad only after machines are saturated.</li><li>By the time new prefillers spin up, users have already seen slow first words.</li></ul><p>With TokenScale’s approach:</p><ul><li>Token velocity profiles tell you how many tokens/s each prefiller can handle.</li><li>The controller sees prefill token arrival rate climbing toward that ceiling and predicts that, if the trend continues, TTFT will slip.</li></ul><p>The controller:</p><ul><li><strong>Scales up prefillers</strong> based on projected token load.</li><li><strong>Activates convertible decoders</strong> to take on burst prefill work immediately, hiding most of the spin-up delay.</li></ul><p>Result: TTFT stays within target more often, even under spiky traffic, without keeping massive prefill capacity idle for the quiet hours.</p><p>A similar story plays out for a few very long chats: request counts don’t change much, prefill is fine, but decode token load creeps up. Token velocity per decode bucket catches that and scales decoders, instead of blindly adding prefillers or reacting late to utilization.</p><h3>What the Paper Found</h3><p>Using a mix of real production traffic patterns and synthetic workloads on modern GPU clusters, the authors show that TokenScale:</p><ul><li><strong>Improves “promises kept” for latency</strong></li></ul><p>More requests meet TTFT and TPOT targets compared to autoscalers based on GPU utilization, request counts, or queue length.</p><p>Token velocity–based decisions better handle both request bursts and token bursts, reducing slow outliers.</p><ul><li><strong>Reduces resource cost for the same promises</strong></li></ul><p>By understanding token-level load per stage, the system needs fewer prefiller/decoder instances to stay within latency targets than more conservative, over-provisioning policies on the traces they test.</p><p>Convertible decoders help absorb spikes without permanently dedicating extra hardware to prefill.</p><ul><li><strong>Behaves better under prefill/decode disaggregation</strong></li></ul><p>Older autoscaling approaches weren’t designed for separate prefill/decode pools and often either starve the wrong stage or over-provision everywhere.</p><p>TokenScale’s split autoscaler keeps both stages closer to “just enough capacity” for the given service level objectives and traffic pattern.</p><p>The exact numbers depend on cluster and workload, but the pattern is consistent: <strong>better latency guarantees at lower or similar GPU cost</strong>, especially under bursty traffic.</p><figure><img alt="A chest of tokens, representing the treasure found while also alluding to tokens, both of which are related to the success of meeting SLAs better while saving on hardware costs." src="https://cdn-images-1.medium.com/max/1024/0*tyBrnjVExEMlRLu2" /><figcaption>With simple infrastructure tweaks, LLM users can be much happier. | Photo by <a href="https://unsplash.com/@bjornpierre?utm_source=medium&amp;utm_medium=referral">Bjorn Pierre</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Why This Matters Even If You Never Deploy TokenScale</h3><p>You might never run TokenScale itself, but its ideas point toward where LLM infra is going.</p><h4>If you work on product or DS</h4><ul><li>Bursty traffic and demo moments are normal for LLM features; average steady-state isn’t the whole story.</li><li>When you talk to infra engineers about “why is it slow sometimes?”, it’s worth asking:</li></ul><p>“Do we distinguish between prefill and decode load?”</p><p>“Do we think in tokens, not just requests?”</p><p>“What breaks first in a spike: TTFT or streaming speed?”</p><p>Even without touching autoscaler code, understanding that <strong>not all latency is the same</strong> (TTFT vs TPOT, prefill vs decode) makes it easier to design features that feel fast on purpose.</p><h4>If you work on infra or platforms</h4><p>TokenScale is one concrete example of a broader shift:</p><ul><li><strong>Better metrics: </strong>from generic utilization and request counts to per-stage metrics that count tokens.</li><li><strong>Flexible roles: </strong>workers that can temporarily change jobs under pressure (Convertible decoders, not rigid pools).</li><li><strong>Latency-aware decisions: </strong>scaling based on the risk of violating TTFT/TPOT, not just “more traffic = more machines.”</li></ul><p>Even without adopting this design, you can:</p><ul><li>Profile token velocity–like metrics yourself: how many tokens/s can your prefill and decode paths really sustain?</li><li>Separate <strong>prefill vs decode dashboards and targets</strong>.</li><li>Reserve a small pool of <strong>flexible workers</strong> or capacity that can shift roles during spikes, instead of permanent over-provisioning.</li></ul><h3>Closing Thoughts: Smarter Rush Hour for LLMs</h3><p>As LLMs move from experiments to everyday infrastructure, bursty workloads and disaggregated serving are becoming the norm. Naive autoscaling (“add nodes when it feels slow”) starts to look like guessing which subway line will get crowded by glancing at a single station.</p><p>TokenScale’s contribution is to show that you can do better:</p><ul><li>Watch <strong>how quickly tokens flow</strong> through each stage, not just how many requests show up.</li><li>Let some workers <strong>switch roles during rush hour</strong>.</li><li>Make scaling decisions tied to <strong>how close you are to breaking your TTFT/TPOT promises</strong>, not just to a utilization target.</li></ul><p>The core lesson is simple:</p><blockquote><em>As LLM systems get more complex, the best autoscaling policies will look less like “add nodes when it feels slow” and more like “shape the flow of tokens through a multi-stage pipeline, in real time, to protect user experience.”</em></blockquote><p>The next time graphs spike and someone asks, “Why did it suddenly feel so slow?”, it might be worth answering: “Because we were watching the wrong thing. We were counting people in the station, not how fast the trains were moving.”</p><figure><img alt="A bullet train that is moving quickly, referencing that watching token (train) velocity is important for better autoscaling that meets SLOs and saves money on hardware." src="https://cdn-images-1.medium.com/max/1024/0*w9gxWUifXPBj8K5M" /><figcaption>Monitoring the train (token) velocity can help meet SLOs and save money. | Photo by <a href="https://unsplash.com/@4000km?utm_source=medium&amp;utm_medium=referral">7</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99c9d93ce616" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science-collective/autoscaling-the-ai-subway-tokenscale-99c9d93ce616">Autoscaling the AI Subway</a> was originally published in <a href="https://medium.com/data-science-collective">Data Science Collective</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Your LLM Keeps Rewatching the Intro]]></title>
            <link>https://medium.com/data-science-collective/why-your-llm-keeps-rewatching-the-intro-prefix-caching-f8dd0ee5e674?source=rss-e20dc259cf29------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8dd0ee5e674</guid>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[David Oy]]></dc:creator>
            <pubDate>Wed, 10 Dec 2025 09:37:25 GMT</pubDate>
            <atom:updated>2025-12-10T09:37:25.649Z</atom:updated>
            <content:encoded><![CDATA[<h4>Prefix-caching and prefix-aware routing in practice</h4><p>Two teams ship the same AI feature with the same model and cloud provider.</p><p>Six weeks later, one team is complaining about latency and GPU bills. The other is bragging that their chat feels snappy and cheap.</p><p>The second team didn’t change the model. They changed what the model has to read.</p><p>In most products, every request sends the same long system prompt: who the assistant is, the tone it should use, the safety rules it must follow. Then, at the very end, there’s a short user question. From the model’s point of view, it’s like watching the same Netflix show intro again and again… and again.</p><p>If 90% of your prompt is boilerplate, you’re paying full price to rewatch your own intro.</p><p><strong>Prefix caching</strong> and <strong>prefix-aware routing</strong> are infrastructure tricks that finally let us hit “Skip Intro” for real. Let’s unpack what those mean in human terms and why infra teams are so excited about them.</p><figure><img alt="Prefix caching is like letting your LLMs hit “skip intro” to save compute." src="https://cdn-images-1.medium.com/max/1024/0*J1daxWxrGP8wEDSN" /><figcaption>LLMs keep rewatching the intros. Why? | Photo by <a href="https://unsplash.com/@glenncarstenspeters?utm_source=medium&amp;utm_medium=referral">Glenn Carstens-Peters</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Why Your LLM Keeps Rewatching the Intro</h3><p>In a lot of production systems, prompts aren’t just the user question.</p><p>They look more like:</p><ul><li>System prompt: “You are a careful assistant. Follow these rules…”</li><li>Policies: safety instructions, formatting rules, style constraints.</li><li>Template: “Given the customer’s ticket and history, draft a reply according to the guidelines below…”</li><li>Then finally: the user-specific bit.<br> “User: My shipment is late, can you help?”</li></ul><p>If you look at the actual text going into the model for thousands of requests, you’ll notice something: <strong>80–90% of each prompt is identical</strong> across many users. Only the end changes.</p><p>Without any optimization, the model:</p><ol><li>Reads the entire shared introduction.</li><li>Does a full first pass over it for every request.</li><li>Only then reaches the user-specific part and starts generating.</li></ol><p>It’s as if every person opening Netflix had to re-watch the full 60-second intro of the same show from scratch, instead of skipping ahead to the new episode.</p><p>That repeated intro doesn’t show up in your UI, but it silently dominates both latency and cost.</p><figure><img alt="Repeated intro processing is using your LLM’s precious compute resources." src="https://cdn-images-1.medium.com/max/1024/0*yLZnoUF3g8LSb3rv" /><figcaption>Repeated intro processing is eating your compute. | Photo by <a href="https://unsplash.com/@mbeero?utm_source=medium&amp;utm_medium=referral">Matt Bero</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What’s a Prefix and Why LLMs Keep Seeing the Same One</h3><p>In this context, a <strong>prefix</strong> is just the “intro” of the token sequence: everything before the user-specific part.</p><p>That often includes:</p><ul><li>System messages (“You are a legal writing assistant…”)</li><li>Safety and policy text</li><li>Tool or retrieval-augmented generation (RAG) wrappers (“Using only the information below, answer…”)</li><li>Fixed templates for a feature (“First summarize, then suggest improvements…”)</li></ul><p>If you break a prompt into pieces like<br> [system instructions] + [policy text] + [template text] + [user question],<br> the <strong>prefix</strong> is the long, shared sequence at the front. The rest is the user-specific tail.</p><p>Concrete examples:</p><ul><li>An <em>AI email composer</em> that always starts with the same “You are an empathetic support agent…” block and internal style guide, then adds the customer’s ticket and a one-line instruction.</li><li>A <em>code review copilot</em> that always uses the same reviewing rubric before reading the diff and user prompt.</li></ul><p>The model doesn’t see branding and policy. It just sees more text it has to plow through. In all of these, it is re-processing the same intro for every request. That intro is often long, and it costs real time and money.</p><h3>How Prefix Caching Works (Like Buffering the Intro Once)</h3><p>At a high level, <strong>prefix caching</strong> means:</p><blockquote>Run the intro once, keep the model’s internal state right after it, and reuse that state for later requests that start from the same intro.</blockquote><p>When the model reads a prompt, it doesn’t just read and forget. As it processes each token, it builds up an internal scratchpad, often called a KV cache. The KV cache is memory of what it has understood so far.</p><p>In practice, the cached state for a prefix is defined very strictly: the exact same token sequence, with the same model and template version, so you’re never reusing state from a slightly different prompt or model.</p><p>Prefix caching says:</p><ol><li>Take a stable intro (for example, your system prompt + fixed template).</li><li>Run it through the model once.</li><li>Store the resulting internal state (the KV cache right after that prefix) in fast memory on the same machine or in a nearby cache.</li><li>For every new request that starts with that exact intro:</li></ol><ul><li>Load the cached state.</li><li>Run the first pass only on the user-specific part.</li><li>Then continue as normal into the token-by-token generation phase.</li></ul><p>You’ve effectively buffered the intro. New viewers don’t re-watch the first minute; they pick up right afterward. You’re only reusing the part of the cache that corresponds to the shared intro; the rest still grows normally as the conversation continues.</p><p>A few important details:</p><ul><li>You don’t have to cache the whole prompt. Many systems cache just the truly static slice at the front (system prompt + fixed wrapper), even if later parts (like retrieved documents) change per request.</li><li>The cache is keyed by a precise identifier: template ID + version, or an exact hash of the intro tokens. You only reuse state when you know the intro is identical.</li></ul><p>For heavily-used templates, this can be a big deal: time to first token drops because there’s less heavy reading before the model can start talking, and GPU time per request goes down because you’re not recomputing the same intro hundreds or thousands of times. You only see that win once the cache is warm, though. If a prefix hasn’t been used in a long time, it will still pay the full first-pass cost, plus a bit of lookup overhead, so the trick is to focus on flows where hit rates stay high.</p><figure><img alt="Prefix caching speeds up time-to-first-token, delighting users." src="https://cdn-images-1.medium.com/max/1024/0*DLgh_Sxl_HfgYk1e" /><figcaption>Prefix caching can make it feel like you get your first token immediately. | Photo by <a href="https://unsplash.com/@1nimidiffa_?utm_source=medium&amp;utm_medium=referral">Nimi Diffa</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Prefix-Aware Routing: Sending Viewers of the Same Show to the Same Server</h3><p>Prefix caching only works if requests that share an intro actually hit the same cached state.</p><p>If you keep a simple random or round-robin routing strategy:</p><ul><li>Identical intros get scattered across workers.</li><li>Each worker might see that intro rarely.</li><li>They all rebuild the intro from scratch, and cache entries never get <em>hot</em> (recently used and still stored) locally.</li></ul><p>That’s where <strong>prefix-aware routing</strong> comes in.</p><p>In one sentence:</p><blockquote>Prefix-aware routing means using the intro as part of your routing key, so requests with the same prefix tend to land on the same worker or shard.</blockquote><p>Practically, that looks like this. When a request arrives, the router:</p><ul><li>Identifies the intro (for example, by template ID + version, or by hashing the intro tokens).</li><li>Uses that <strong>prefix key</strong> when picking a worker.</li></ul><p>Requests with the same prefix key:</p><ul><li>Get sent to the same worker, or</li><li>Get spread across a small, consistent subset of workers that share that cached state.</li></ul><p>Now your cache actually works: workers that serve a given template see that intro over and over, so the cached state for it stays in fast memory and gets reused. Cache hit rates go up; repeated first-pass work goes down.</p><p>If you don’t do this, you’re effectively caching intros into the void.</p><p>There is a tradeoff: if a single intro becomes extremely popular, you can accidentally create hot spots, where a few workers are overloaded while others sit mostly idle. In practice, you deal with that by:</p><ul><li>Replicating popular intros across more than one worker.</li><li>Being deliberate about how you map intros to machines, so traffic spreads out.</li><li>Watching for overloaded workers and relaxing locality if they get too hot.</li></ul><p>Some designs instead keep the cache in a shared service and fetch it over the network; the pattern here is the “locality first” version, keeping state next to the GPU/worker for speed and adding cross-machine sharing only when it’s worth the extra network hop. In real systems you usually iterate: start with simple rules, then refine the mapping as traffic patterns and hot prefixes become clearer in your metrics.</p><h3>Where This Shines and Where It Breaks Down</h3><p>Like most infrastructure tricks, prefix caching and prefix-aware routing are not magic bullets. They’re extremely powerful in the right workloads and mostly overhead in the wrong ones.</p><h4><strong>Where it shines:</strong></h4><ul><li><strong>Long, stable intros reused heavily.</strong><br>Common system prompts and templates used by thousands of users in an AI email composer or code review assistant.</li><li><strong>First-pass-heavy profiles.</strong><br>When the time spent on the shared intro dominates both time-to-first-token and cost, amortizing that work across many requests is a big win. A useful rule of thumb: if prefill (that first pass) is a big chunk of total latency, prefix caching is worth a serious look.</li><li><strong>Split prefill/decode setups.</strong><br>If you already run the heavy first pass on its own pool of machines, this is a natural optimization there: fewer full-prompt passes, more suffix-only passes.</li></ul><h4><strong>Where it breaks down or gets tricky:</strong></h4><ul><li><strong>Highly dynamic prefixes.</strong><br>If your intro changes constantly, cache entries churn and hit rates stay low.</li><li><strong>Decode-dominated workloads.</strong><br>If your main bottleneck is very long outputs, shaving first-pass cost on the intro doesn’t move the needle much compared to optimizing the token-by-token phase and its batching.</li><li><strong>Correctness and invalidation.</strong><br>You need to be strict about when cached state is valid: prompt/template versions, model versions, and any dynamic pieces must be encoded in the cache key, and when those change you treat that as a new season, not a reusable entry.</li><li><strong>Memory and skew.</strong><br>Cached state for long intros is large. If you cache everything, you can blow up memory. If one intro is extremely hot, it can overload the workers that own it unless you replicate and balance carefully.</li></ul><p>The patterns that usually win in practice:</p><ul><li>Cache only well-defined, stable intro slices for a small number of hot templates.</li><li>Use prefix-aware routing with simple, explicit keys (template ID + version).</li><li>Add basic metrics: time spent on the intro vs the rest, cache hit rates per template, load per prefix key, and how often you fall back to a cold prefill path.</li></ul><figure><img alt="With planning, most systems can be sped up with prefix caching and prefix-aware routing." src="https://cdn-images-1.medium.com/max/1024/0*w7aimVglsXI7vOKU" /><figcaption>Most systems can speed up TTFT with prefix caching done right. | Photo by <a href="https://unsplash.com/@brett_jordan?utm_source=medium&amp;utm_medium=referral">Brett Jordan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>So What? How to Use This in Real Systems</h3><p>You don’t need to be building a custom serving framework to care about this.</p><p>If you work on <strong>infra or platforms</strong>, start by asking:</p><ul><li>Do we have flows where most of the prompt is boilerplate and only the tail changes?</li><li>How much time are we spending on the intro versus the rest of the work?</li><li>Can we identify a truly stable intro slice (system prompt + wrapper) that we could cache safely?</li></ul><p>If yes, there’s a good chance prefix caching and prefix-aware routing can make those features cheaper and noticeably snappier, especially under load.</p><p>If you’re on the <strong>product or data science</strong> side, it’s worth noticing:</p><ul><li>Which of your prompts are templated and stable over time.</li><li>When you change templates, you’re not just changing behavior. You’re also changing whether infra can reuse work or has to start from scratch every time.</li><li>Features built around shared intros give your infra partners room to pull these levers and make things feel fast.</li></ul><p>As prompts get longer and more structured, the stacks that win on latency and cost won’t just be the ones with the biggest GPUs. They’ll be the ones that look at all those shared intros, finally hit “Skip,” and reuse what the model already knows.</p><figure><img alt="Prefix caching and prefix-aware routing help you get more performance out of your current hardware." src="https://cdn-images-1.medium.com/max/1024/0*6Ymd1V6qx3IzZbpP" /><figcaption>Prefix caching can help you win without buying bigger GPUs. | Photo by <a href="https://unsplash.com/@jdent?utm_source=medium&amp;utm_medium=referral">Jason Dent</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8dd0ee5e674" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science-collective/why-your-llm-keeps-rewatching-the-intro-prefix-caching-f8dd0ee5e674">Why Your LLM Keeps Rewatching the Intro</a> was originally published in <a href="https://medium.com/data-science-collective">Data Science Collective</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Makes AI Feel Fast]]></title>
            <link>https://medium.com/data-science-collective/what-makes-ai-feel-fast-b72a5422a959?source=rss-e20dc259cf29------2</link>
            <guid isPermaLink="false">https://medium.com/p/b72a5422a959</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[David Oy]]></dc:creator>
            <pubDate>Wed, 03 Dec 2025 09:40:37 GMT</pubDate>
            <atom:updated>2025-12-03T09:40:37.532Z</atom:updated>
            <content:encoded><![CDATA[<h4>A friendly guide to latency in LLMs</h4><p>Some AI chats feel like talking to a quick, attentive colleague. You ask a question, and words start appearing almost immediately. The answer unfolds while you watch. You never even wonder if the app froze.</p><p>Others feel very different. You stare at a spinner. One second. Two. Three. Then a wall of text arrives all at once, or the response stutters in bursts. Technically, both systems might be using similar models.</p><p>The difference is in <strong>latency, </strong>the delay between you doing something and seeing the system react: when the answer starts, how the words are paced, and how the system shares limited compute across thousands of users. That’s what this post is about.</p><figure><img alt="Users often expect chatbots to be able to maintain a conversational pace, so latency is a critical driver of LLM usage." src="https://cdn-images-1.medium.com/max/1024/0*KOxtqJIgECaK6jvb" /><figcaption>Chatbots need to be able to keep a conversational pace. Photo by <a href="https://unsplash.com/@wocintechchat?utm_source=medium&amp;utm_medium=referral">Christina @ wocintechchat.com</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a>.</figcaption></figure><p>We’ll mostly stay in human terms. We’ll talk about why small changes in <strong>time to first token (TTFT: </strong>the time between you hitting send and seeing the first piece of text appear), <strong>streaming</strong> (sending the answer piece by piece instead of all at once), and <strong>tokens per second</strong> (how fast the model talks) can make an AI feel either instant or broken. We’ll also talk about the tradeoffs that need to be weighed.</p><h3>Why Some Chatbots Feel Instant (and Others Feel Slow)</h3><p>You’ve probably had both of these experiences:</p><ul><li>You type a question, hit enter, and almost immediately see the first few words of a reply. The rest flows in steadily. Even if it takes a few seconds, it feels like a smooth conversation.</li><li>You type the same question into a different app. A loading spinner appears. You wait. Then an entire paragraph pops in at once.</li></ul><p>From the user’s point of view, one system feels fast and the other doesn’t, even if both are running similar large language models (LLMs) on similar hardware.</p><p>The difference is <strong>how</strong> they spend their time:</p><ul><li>How long before the first piece of text appears.</li><li>How the rest of the answer is paced.</li><li>How often very slow responses occur.</li></ul><p>We don’t think in milliseconds. We think in terms of “did you hear me?” and “does this still feel alive?” So we’ll start there.</p><h3>How We Feel Latency in Conversation (Before We Talk LLM Metrics)</h3><p>Before we talk about metrics, let’s think about ordinary conversations.</p><h4>The first beat: “Did you hear me?”</h4><p>Imagine sending a text to a friend.</p><ul><li>Sometimes, you see a “typing…” indicator almost immediately or get a quick “Got it, one sec” back.</li><li>Other times, nothing happens. Ten seconds go by. You start checking your signal and WiFi. Did they see it?</li></ul><p>Those first few moments matter. We’re not asking for a full answer yet, just a sign of life.</p><figure><img alt="Time-to-first-token is one of the most important metrics for the user experience in chatbots or any real-time LLM use cases." src="https://cdn-images-1.medium.com/max/1024/0*y8ojhCW9RDeg10ly" /><figcaption>Time to first token can really impact the user experience. Photo by <a href="https://unsplash.com/@miquel_parera_mila?utm_source=medium&amp;utm_medium=referral">Miquel Parera</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a>.</figcaption></figure><p>In LLM systems, the same moment exists: the delay between you hitting send and seeing the very first fragment of a reply. That’s <strong>time to first token (TTFT)</strong>, the time between your message arriving and the first piece of the model’s answer showing up, and it quietly sets the tone for everything that comes next.</p><h4>The flow: “Is this readable?”</h4><p>Now imagine how the rest of the reply shows up.</p><p>You’ve probably seen two patterns:</p><ul><li><strong>Gradual flow:</strong> Text appears line by line. You can start skimming, and your eyes follow along as it writes.</li><li><strong>One big dump:</strong> Nothing appears for a while, then a large block of text arrives in a single jump.</li></ul><p>The first feels conversational. The second feels like waiting for a file download.</p><p>These two experiences often come from the same model doing the same amount of work. The difference is whether the system uses <strong>streaming</strong> — sending the answer in small pieces as they’re generated — or waits until everything is done before showing you anything.</p><h4>The rare stalls that break trust</h4><p>One more pattern matters: the truly bad stall.</p><p>Most of the time, the chatbot responds in under a second or two. But here and there:</p><ul><li>A normal question suddenly takes ten seconds.</li><li>The loading indicator spins with no visible progress.</li><li>You close the tab or try again because it feels broken.</li></ul><p>We don’t average these experiences in our heads. We remember the failures. Engineers sometimes call these tails and measure them with numbers like <strong>p95</strong> and <strong>p99</strong>, shorthand for the slowest 5% or 1% of all responses.</p><p>Even with a great average, bad tails can make the whole system feel unreliable.</p><p>Now that we’ve got the human side in mind, we can look at what actually happens inside an LLM when you send a message.</p><h3>LLM Latency 101: The Anatomy of a Chatbot Answer</h3><p>When you hit send, the system doesn’t just think once. It usually goes through two broad phases:</p><ol><li>A listening and understanding step.</li><li>A long series of small “talk a bit more” steps.</li></ol><p>In many serving stacks, that heavy first pass is often called <strong>prefill</strong> — a one-time, expensive first pass where the model reads and digests your whole message — and the smaller, repeated steps are <strong>decode</strong> — the loop where it keeps adding more words to the answer. Prefill cost tends to grow with input length and the size of each <strong>batch</strong> (a group of user requests the system processes together), while decode cost grows with how long the conversation runs, how many tokens you generate, and how many active conversations share the decode batch.</p><p>Each phase affects different parts of what you feel.</p><h4>Time to First Token (TTFT): the answer’s first heartbeat</h4><p><strong>TTFT</strong> is the time between your request arriving and the very first <strong>token</strong> of the model’s reply being sent back. A token is a small chunk of text the model works with, often part of a word or a short word.</p><p>That time usually comes from a mix of:</p><ul><li>Any time your request spends waiting in line behind others.</li><li>A heavy prefill pass where the model reads your full prompt (and often previous messages) and forms its internal understanding.</li><li>Extra work to move your request through <strong>middleware</strong> (other services inside your backend that it passes through on the way to the model) and set up the stream back to you, plus ordinary network overhead between client and server.</li></ul><p>For long prompts, that first pass is expensive: the model has to run through many layers with a lot of text in memory at once. If the system is also trying to group requests into <strong>batches</strong> — bundles of requests it processes together to be more efficient — it might wait briefly to see if more prompts arrive. TTFT isn’t a single fixed number: it tends to grow with prompt length and with how full the current batch is when your request gets picked up.</p><p>From the outside, you don’t see any of that. You just feel the delay before the first word appears. That’s why TTFT is so important for the user experience, even if the total answer time is the same.</p><figure><img alt="You do not want your users to get impatient waiting for your LLM’s first token. That’s why time-to-first-token is such an important LLM metric to optimize." src="https://cdn-images-1.medium.com/max/1024/0*FCltOHHKkEF6J5U8" /><figcaption>Systems often optimize for time to first token to ensure their users do not get impatient. Photo by <a href="https://unsplash.com/@rruprrup?utm_source=medium&amp;utm_medium=referral">Aleksandra Sapozhnikova</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a>.</figcaption></figure><h3>Streaming vs Non-Streaming LLMs: progress vs silence</h3><p>Once the model has done that first heavy pass, it starts generating your answer. Under the hood, this happens token by token:</p><ul><li>Look at everything you’ve said so far.</li><li>Generate a bit more text.</li><li>Update its memory.</li><li>Send those tokens out.</li></ul><p>The system has a choice:</p><ul><li><strong>Non-streaming:</strong> Keep partial results on the server, and send them only when the entire answer is ready.</li><li><strong>Streaming:</strong> Send each small chunk (or every few chunks) to the client as soon as they’re available.</li></ul><p>To a model, these paths can look similar. To a human, they don’t:</p><ul><li>Non-streaming collapses the entire answer into a single wait-then-send experience.</li><li>Streaming turns that into a visible process. You can start reading while the system is still thinking.</li></ul><p>This is why you can take two systems with similar total response times, turn on streaming in one of them, and suddenly users report that it feels faster. Streaming also comes with tradeoffs. For example, you send many small chunks over the network, so the server does a bit more work per token. Most teams accept that cost because the perceived speed gain is so large.</p><h4>Tokens Per Second: how fast the model talks</h4><p>Once the stream has started, another factor kicks in: how quickly tokens show up.</p><p>You can think of <strong>tokens per second</strong> as the model’s speaking speed once it has started answering — how many of those tiny text chunks it can send each second.</p><p>Higher tokens per second generally mean:</p><ul><li>The answer finishes sooner.</li><li>The stream feels denser and more continuous.</li></ul><p>Internally, you often track both: how fast a single stream progresses, and how many tokens per second the whole system produces across all users. That total rate is part of what engineers call <strong>throughput</strong> — how much work the system gets done per second overall.</p><p>But perception is not purely linear. A model that starts responding quickly and delivers a steady stream of text will <em>feel</em> fast even if it’s slightly slower in raw tokens per second. A model that takes a long time to start, then gushes out text very quickly, will feel worse, even if the total time is shorter.</p><p>The balance between TTFT, streaming, and tokens per second is what defines a system’s conversational feel.</p><figure><img alt="Just like a river stream, a stream of tokens is fast once it starts. Generating the first token takes a while, then each one after is usually pretty quick." src="https://cdn-images-1.medium.com/max/1024/0*IN5OX3XlzGrWlajG" /><figcaption>Like a river stream, once tokens start getting generated, they tend to generate quickly. Photo by <a href="https://unsplash.com/@jachan_devol?utm_source=medium&amp;utm_medium=referral">Jachan DeVol</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a>.</figcaption></figure><blockquote><strong><em>Sidebar for engineers:</em></strong><em> why tails matter more than averages</em></blockquote><blockquote><em>For infra folks, the interesting part is often not the average, but the </em><strong><em>tails</em></strong><em> — the rare, unusually slow responses:</em></blockquote><blockquote><strong><em>- p95 / p99 TTFT:</em></strong><em> the slowest small fraction of first tokens (the slowest 5% or 1% of all responses).</em></blockquote><blockquote><strong><em>- p95 / p99 decode latency:</em></strong><em> the slowest streams to deliver a complete answer.</em></blockquote><blockquote><em>Those bad cases are usually caused by things like long prompts, long outputs, overloaded machines, noisy neighbors (other workloads sharing the same machine and competing for resources), unlucky batches, or background events like </em><strong><em>cold starts</em></strong><em> (machines starting from scratch) and </em><strong><em>autoscaling</em></strong><em> (servers being added or removed as traffic changes). Users experience them as slow chats.</em></blockquote><blockquote><em>You can have a great average latency and still a terrible experience if your tails are uncontrolled. That’s why many teams optimize for p95/p99 rather than just mean latency.</em></blockquote><h3>Under the Hood: How LLM System Design Shapes Latency</h3><p>Once you see the visible behavior, you can start to trace it back to a few architectural choices: how you group work, how you prioritize it, and how you split it across machines.</p><h4>Prefill and decode: listening once, speaking many times</h4><p>Most modern LLM systems roughly split the model’s work into:</p><ul><li><strong>Prefill:</strong> the heavy, one-time pass over your entire prompt and conversation history.</li><li><strong>Decode:</strong> the repeated, lighter passes to generate each new token (or small group of tokens) and update the model’s internal memory.</li></ul><p>Prefill, plus any queuing in front of it, largely determines TTFT. Decode, plus how you batch and schedule it, determines how the stream feels after that: whether tokens arrive smoothly or in fits and starts.</p><p>Understanding that split is important because the next decisions — batching, scheduling, and disaggregation — tend to treat these phases differently.</p><h4>Batching and Latency: answering multiple people at once</h4><p><strong>GPUs</strong> — specialized chips built to do a lot of math in parallel and commonly used for AI — like big workloads. If you run a single small prompt through a big model, a lot of hardware sits idle. To fix that, LLM serving stacks usually <strong>batch</strong> requests:</p><ul><li>Multiple prompts are processed together in one prefill pass.</li><li>Multiple active conversations are processed together in each decode step.</li></ul><p>This is great for the system:</p><ul><li>You get higher throughput (more tokens per second across the cluster).</li><li>You drive down cost per token by keeping hardware busy.</li></ul><p>The cost shows up in TTFT and tails:</p><ul><li>To form a batch, you often wait briefly to see if more requests arrive.</li><li>That waiting time is pure overhead for the unlucky few who arrive just after a batch closed.</li><li>At low traffic, waiting for a big enough batch can make TTFT noticeably worse.</li></ul><p>Prefill and decode also feel batching differently: large prefill batches can noticeably push up TTFT, while decode batches mostly affect how smooth latency between tokens feels. At very high traffic, the system may fill batches quickly, but at lower traffic you really feel the extra wait to form a batch. Many production systems adjust batching windows based on load so they can take advantage of fuller batches at peak while keeping TTFT tolerable when traffic is light.</p><p>Scheduling rules sit on top of this. The system decides:</p><ul><li>Which requests go into which batch.</li><li>Whether interactive chat gets priority over background jobs.</li><li>Whether short requests get to cut in line ahead of long ones.</li></ul><p>Good batching and scheduling can make the system much more efficient without hurting most users. It also means that a handful of requests will occasionally wait longer so the group as a whole does better.</p><figure><img alt="LLMs need to balance multiple conversations with different users. That provides an opportunity for optimizing system performance." src="https://cdn-images-1.medium.com/max/1024/0*Szi86CMJq_wVIMqI" /><figcaption>Each user may feel like they are the only ones talking to the LLM, but the system needs to be able to efficiently manage conversations with many users. Photo by <a href="https://unsplash.com/@brookecagle?utm_source=medium&amp;utm_medium=referral">Brooke Cagle</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote><strong><em>Sidebar for engineers: </em></strong><em>batching vs TTFT in practice</em></blockquote><blockquote><em>The practical knobs include:</em></blockquote><blockquote><em>- Max batch size.</em></blockquote><blockquote><em>- Max batching window (how long you wait to form a batch).</em></blockquote><blockquote><em>- Priority queues for interactive vs batch workloads.</em></blockquote><blockquote><em>Larger batches and longer windows improve throughput and GPU utilization, but increase TTFT and can worsen p95 for unlucky arrivals. Smaller batches and shorter windows improve TTFT but reduce throughput and raise cost.</em></blockquote><blockquote><em>A lot of speed questions come down to where those knobs are set for a particular product and traffic pattern.</em></blockquote><h3>How Disaggregated Inference Changes LLM Latency</h3><p>In a separate blog post, I talked about <strong>disaggregated inference</strong>: splitting LLM serving into separate pools of machines for prefill and decode instead of having every node do everything.</p><p>From a latency perspective, this matters because it lets you tune and scale the two phases separately.</p><h3>Separate listeners and talkers</h3><p>In one common disaggregated setup, you might have:</p><p>A <strong>prefill pool</strong>:</p><ul><li>Machines that specialize in the heavy first pass over new prompts.</li><li>You add more of them when lots of new conversations are starting.</li><li>They’re tuned to balance TTFT against how many requests each machine can handle.</li></ul><p>A <strong>decode pool</strong>:</p><ul><li>Machines that specialize in the token-by-token part for ongoing chats.</li><li>You add more of them when many conversations are active at once.</li><li>They’re tuned for smooth streaming and a good speaking speed across many users.</li></ul><p>In some systems, these are different hardware shapes. In others, these are logical roles running on the same cluster with different scheduling policies.</p><p>A small routing layer in front decides where each request goes:</p><ul><li>New request? Send it to prefill, then hand off its conversation state to the decode side.</li><li>Ongoing request? Keep sending its next decode steps to the appropriate decode workers.</li></ul><p>The implementation details get subtle, especially around where that conversation state lives and when it has to cross the network, but the key idea is simple: <strong>you don’t have to optimize TTFT and streaming on the same machines in the same way.</strong></p><h4>What users actually feel</h4><p>With that split in place, you can:</p><ul><li>Add more prefill capacity during spikes of new traffic to keep TTFT under control.</li><li>Add more decode capacity when you see many long, chatty sessions.</li><li>Use different batching and scheduling strategies on each side.</li></ul><p>Users never see prefill or decode in the responses. They feel things like:</p><ul><li>“This assistant starts answering quickly, even during peak times.”</li><li>“It keeps streaming without freezing halfway through a long answer.”</li><li>“I don’t see as many random, unexplained pauses anymore.”</li></ul><p>Disaggregation isn’t required for a good latency story, especially at small scale. But it’s one of the big levers modern systems use once they start pushing hardware hard.</p><h3>The Latency Tradeoffs: You Can’t Optimize Everything at Once</h3><p>It’s tempting to ask for the best of all worlds:</p><ul><li>Instant TTFT.</li><li>Perfectly smooth streaming.</li><li>No bad tails.</li><li>Maximum throughput.</li><li>Minimal cost.</li></ul><p>In practice, you’re always choosing a latency <em>profile</em>, not perfection in every dimension.</p><h4>TTFT vs throughput: snappy vs efficient</h4><p>The first big tradeoff is between individual responsiveness and overall efficiency.</p><p>For snappy TTFT, you want to:</p><ul><li>Run smaller batches.</li><li>Keep some excess capacity on machines so new requests can start quickly.</li></ul><p>For maximum throughput and lower cost, you want to:</p><ul><li>Run large batches.</li><li>Keep machines as close to fully utilized as possible.</li></ul><p>A research tool that generates long reports might accept slower TTFT for better throughput. A real-time chat assistant might accept higher cost to keep TTFT low.</p><h4>Smooth streaming vs total completion time</h4><p>You can also trade off a smooth stream of words against how quickly the full answer finishes:</p><p>To keep tokens flowing steadily, you might:</p><ul><li>Give decode work higher priority over new prefills.</li><li>Limit how much a single long answer can hog a worker.</li></ul><p>That can slightly reduce overall throughput, but users feel the stream as continuous and reliable.</p><p>On the other hand, you can push the hardware as hard as possible and still end up with streams that stutter when things are busy, even if the total time in logs looks fine.</p><h4>Tails vs cost and complexity</h4><p>Finally, there’s the question of tails:</p><p>To shrink p95/p99, you often need to:</p><ul><li>Over-provision capacity.</li><li>Use smarter routing and isolation (e.g., keep noisy workloads separate).</li><li>Impose timeouts, limits, or degradation paths on extreme requests.</li></ul><p>In practice, the worst tails often come from a few very large requests with very long prompts or outputs, or from requests that weren’t cancelled quickly when a user navigated away, plus the occasional cold start or autoscaling event. Guardrails like maximum allowed lengths and timeouts are unglamorous, but they matter a lot for keeping p95/p99 in check.</p><p>Those techniques help keep longer-than-average pauses rare. They also increase operational complexity and can raise cost. Every team ends up placing its own bets:</p><ul><li>Are a few bad experiences acceptable if the system is cheaper?</li><li>Or do we want to pay more (and build more complex infrastructure) to keep the worst cases under tight control?</li></ul><p>There’s no universal answer. There’s only what fits your product and users.</p><h3>So What? Designing AI That Feels Fast on Purpose</h3><p>You don’t need to be an infrastructure engineer to think about latency. If you work anywhere near AI products, it helps to be explicit about what fast actually means for your users.</p><h4>For product teams and PMs</h4><p>A few questions to ask your infra or ML partners:</p><p>For this feature, what matters most:</p><ul><li>Quick acknowledgment (low TTFT)?</li><li>Quick full answer?</li><li>Extremely consistent behavior with very few bad delays?</li><li>Where in the flow is a pause unforgivable, and where is it acceptable?</li><li>Are we designing our UI around the latency profile we actually have?</li></ul><p>Sometimes, simple changes help a lot:</p><ul><li>Show something as soon as the system has started (even a short partial answer).</li><li>Make streaming the default where it makes sense.</li><li>Be honest in the user interface when something is taking longer than usual, instead of pretending nothing is happening.</li></ul><figure><img alt="The right set of system tradeoffs depend on your product’s user requirements." src="https://cdn-images-1.medium.com/max/1024/0*r8twTr33Z8dc4ZZE" /><figcaption>Like most product, your LLM’s requirements depend on your users’ needs. Photo by <a href="https://unsplash.com/@airfocus?utm_source=medium&amp;utm_medium=referral">airfocus</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a>.</figcaption></figure><h4>For infra and ML engineers</h4><p>On the systems side, the biggest step is usually measurement:</p><p>Break down latency into:</p><ul><li>TTFT (queue + prefill).</li><li>Inter-token latency / tokens per second (decode).</li><li>p95/p99 for both phases.</li></ul><p>Correlate those with:</p><ul><li>Batch sizes.</li><li>Scheduling policies.</li><li>Request lengths and workloads (interactive vs batch).</li></ul><p>From there, you can run controlled experiments:</p><ul><li>Change batch sizes and batching windows.</li><li>Try simple prefill/decode separation.</li><li>Introduce priority queues or routing rules for interactive traffic.</li></ul><p>The goal isn’t just to make it faster. It’s to shape a latency profile that matches what the product actually promises to users.</p><h3>Where This Is Going</h3><p>We’re still early in figuring out what good latency looks like for AI systems.</p><p>Models are getting larger and more capable. At the same time, they’re being woven into more interactive experiences:</p><ul><li>Assistants that sit next to you while you work.</li><li>Agents that operate tools and APIs on your behalf.</li><li>Multi-modal systems that see, listen, and respond in real time.</li></ul><p>As that happens, latency stops being just a behind-the-scenes metric and becomes part of the product’s personality. Users will expect:</p><ul><li>Very low TTFT for common flows.</li><li>Smooth, readable streaming that feels conversational.</li><li>Rare tail events, even under heavy load.</li></ul><p>Behind the scenes, we’ll see more:</p><ul><li>Split designs that treat prefill and decode as different kinds of work.</li><li>Smarter systems that decide which request gets served next based on type and priority.</li><li>Layered setups that do as much work as possible close to the user, and only send what’s necessary to heavier back-end systems.</li></ul><p>The next time a chatbot feels surprisingly fast, it probably isn’t just because the model is smarter. It’s because a lot of quiet engineering work went into when the first word appears, how the rest of the answer is paced, and how rarely it lets you sit there wondering, “Is this thing still there?”</p><figure><img alt="The user experience is very improtant for LLM chatbots." src="https://cdn-images-1.medium.com/max/1024/0*RIp2hM3NhFmeQJKM" /><figcaption>Chatbots are becoming friendlier and faster. Photo by <a href="https://unsplash.com/@rozetsky?utm_source=medium&amp;utm_medium=referral">Ant Rozetsky</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a>.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b72a5422a959" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science-collective/what-makes-ai-feel-fast-b72a5422a959">What Makes AI Feel Fast</a> was originally published in <a href="https://medium.com/data-science-collective">Data Science Collective</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inside the AI Warehouse: How Modern Systems Keep Chatbots Fast]]></title>
            <link>https://medium.com/data-science-collective/why-chatbots-feel-fast-ai-inference-72c175d53d59?source=rss-e20dc259cf29------2</link>
            <guid isPermaLink="false">https://medium.com/p/72c175d53d59</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[infrastructure]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[David Oy]]></dc:creator>
            <pubDate>Wed, 03 Dec 2025 09:32:17 GMT</pubDate>
            <atom:updated>2026-05-29T21:34:36.651Z</atom:updated>
            <content:encoded><![CDATA[<h4>An unscary guide to disaggregated inference</h4><p>Every time you ask a large language model a question, two things happen behind the scenes: a bill and a wait.</p><p>The bill is the time on specialized hardware it takes to think through your request. At scale, this adds up to millions of dollars a year. The wait is the <strong>latency: </strong>the delay before you see anything on your screen. A few hundred milliseconds feels snappy; a couple of seconds feels broken.</p><p>We talk a lot about model architecture: how the model is built, how much text it can see at once, how we compress its numbers. But a surprising amount of what you <em>feel</em> as a user (and what you <em>pay</em> for as a company) comes down to something less glamorous: <strong>how we organize the work behind the scenes.</strong></p><figure><img alt="Modern warehouse with workers and pallets representing how AI systems organize work behind the scenes." src="https://cdn-images-1.medium.com/max/1024/0*EN9QyqkP1w9o8jTY" /><figcaption>Behind every instant chatbot answer is a warehouse of invisible work. Photo by <a href="https://unsplash.com/@ruchindra?utm_source=medium&amp;utm_medium=referral">Ruchindra Gunasekara</a>.</figcaption></figure><p>This post is about one of those architectural choices: <strong>disaggregated inference</strong> for large language models. We’ll use an AI warehouse metaphor to make it concrete, then peek under the hood at how “prefill” and “decode” phases really work.</p><h3>When LLMs Feel Fast — and When They Don’t</h3><p>You’ve probably seen both sides of modern AI:</p><ul><li>In one app, you ask a question and the answer starts streaming almost immediately.</li><li>In another, you wait through a long spinner, then get a big chunk of text all at once.</li></ul><figure><img alt="A screenshot of an LLM used for chat." src="https://cdn-images-1.medium.com/max/1024/0*YnfwHinB2tZQGew0" /><figcaption>The same model can result in very different user experiences, depending on whether the system is fast or slow. Photo by <a href="https://unsplash.com/@solenfeyissa?utm_source=medium&amp;utm_medium=referral">Solen Feyissa</a>.</figcaption></figure><p>Under the hood, both apps might be using similar models. The difference is often not the model itself, but <strong>how the system handles two very different kinds of work</strong>:</p><ol><li>A <strong>heavy, one-time computation upfront</strong> to read your entire prompt and understand “what’s going on” in the conversation.</li><li>A <strong>long series of small, repeated steps</strong> to generate the answer token by token while you watch. A token is the main unit LLMs process: small chunks of text, often shorter than a word.</li></ol><p>Many older or simpler stacks treat those two phases the same way: the same machines do everything. Many modern AI systems split “prefill” and “decode” onto different groups of machines, each managed and scaled in its own way. Even in “do everything” setups, there’s often plenty of engineering under the hood. Disaggregation doesn’t replace those; it adds another layer of control on top.</p><p>To see why that matters, let’s spend a day in an AI warehouse.</p><h3>A Day in the Life of an AI Warehouse (A Metaphor for LLM Inference)</h3><p>Imagine there’s a warehouse for all AI answers. Every time someone sends a prompt to a chatbot, an order appears at this warehouse.</p><h4>One Warehouse Doing Everything</h4><p>It’s 9:00 AM. Hundreds of people send long, complicated prompts at once:</p><ul><li>“Summarize this 10-page document and compare it to that report.”</li><li>“Help me refactor this code.”</li><li>“Plan a three-day trip with constraints.”</li></ul><p>In our <strong>old-school warehouse</strong>, each worker:</p><ul><li>Reads an order.</li><li>Walks the aisles to grab all the items.</li><li>Packs them into boxes.</li><li>Jumps into a truck and drives across town to deliver them personally.</li></ul><p>Now add <strong>chatty customers</strong> who keep tweaking orders:</p><ul><li>“Actually, add socks.”</li><li>“Swap the blue shirt for black.”</li><li>“Send me one more of those.”</li></ul><p>The same worker keeps driving back and forth to the same house with tiny packages, while other customers wait for their first box. During a <strong>holiday sale</strong>, it gets even worse: new orders pour in, old orders need follow-ups, and workers are constantly context-switching between aisles and trucks. Everything slows down.</p><p>This is what a lot of <strong>monolithic LLM serving setups</strong> can feel like at scale: every node (individual server) handles the entire lifecycle of a request — from “read the whole prompt” to “stream out every token” — without distinguishing between the heavy initial work and the lighter, repetitive work that comes after.</p><figure><img alt="Two warehouse scenes: one worker doing every task versus separate pickers and couriers" src="https://cdn-images-1.medium.com/max/1024/1*0cDoqlhIMfeziyVYi-7AbA.png" /><figcaption>Monolithic LLM serving: one worker does it all. Disaggregated inference: pickers and couriers specialize.</figcaption></figure><h4>Splitting the Team — Pickers and Couriers</h4><p>A more modern warehouse looks different. Here, we have two specialized teams:</p><p><strong>Pickers (inside the warehouse)</strong></p><ul><li>Read incoming orders.</li><li>Walk the aisles once, efficiently.</li><li>Pull everything that might be needed for the order into a <strong>staged pallet</strong> with the customer’s name on it.</li></ul><p><strong>Couriers (outside the warehouse)</strong></p><ul><li>Take items from that pallet.</li><li>Deliver them to customers in <strong>small batches</strong>.</li><li>Make many quick runs, instead of one huge trip.</li></ul><p>Revisit our scenarios:</p><ul><li><strong>Morning spike in new orders</strong>: scale up pickers to batch orders and fill pallets; couriers deliver as pallets are ready.</li><li><strong>Chatty customers</strong>: once a pallet exists, most work is courier work. There is no need to re-walk the aisles for every tiny change.</li><li><strong>Holiday rush</strong>: scale pickers and couriers independently. More pickers for new orders, more couriers for ongoing deliveries.</li></ul><p>This separation is the heart of disaggregated inference: treat the “bulk thinking” phase and the “streaming replies” phase as different jobs, and give them different resources.</p><h3>Translating the Warehouse: Prefill vs Decode and the LLM Scratchpad (KV Cache)</h3><p>Now let’s map that story onto how large language models actually run.</p><h4>Prefill — The Bulk Pick Run (The “First Pass” in LLM Inference)</h4><p>When an LLM first receives your prompt, it does a <strong>heavy pass over the entire input</strong>:</p><ul><li>It reads all the pieces of your message (and possibly previous messages).</li><li>It runs the full stack of internal computations over them.</li><li>It builds up an internal representation of “what’s going on” in this conversation so far.</li></ul><p>This is the <strong>prefill phase</strong>. In warehouse terms, this is the pickers reading the order, walking the aisles, and pulling everything that might be relevant into one place.</p><p>From a systems view, this phase is heavy work: it does a lot of numerical calculation, it has to keep a lot of information in memory at once, and it often makes sense to handle many requests together to use the hardware efficiently.</p><h4>The KV Cache — Your Labeled Pallet</h4><p>As the model processes your input, it doesn’t just think and forget. At many steps along the way, it stores a compact memory of what it has seen so far. This memory is often called a <strong>KV cache</strong> in systems papers, but you can think of it simply as the model’s running scratchpad.</p><p>You can also think of this scratchpad as your <strong>labeled pallet in the warehouse</strong>:</p><ul><li>It holds the memory of your prompt and anything generated so far.</li><li>It lives in very fast memory on the machines running the model so it can be consulted quickly.</li><li>It’s keyed to your session, so the system knows which pallet belongs to whom.</li></ul><p>Once that pallet exists, the system doesn’t need to re-walk the aisles for every follow-up step. It can work from the staged items.</p><h4>Decode — Many Small Deliveries (The Streaming Phase of LLM Inference)</h4><p>After prefill, the model enters the <strong>decode phase</strong>: generating your answer token by token.</p><p>Each decode step:</p><ul><li>Looks back at the scratchpad (your pallet) to see everything said so far.</li><li>Computes the next token (or a small group of tokens).</li><li><strong>Appends</strong> the new information back into the scratchpad so future steps can see it.</li><li>Streams that token to your device.</li></ul><p>Over time, that scratchpad grows with the length of the conversation, and for large models it can easily dominate memory usage. Many practical systems end up trading off how long they keep that history versus how many conversations they can serve at once.</p><p>Decode uses less raw computation per step than prefill, but you have to repeat those steps many times. This is the part you feel as fast or slow, and its speed depends on how quickly the system can reuse and extend that scratchpad memory.</p><p>In warehouse terms, this is the couriers taking small sets of items from the pallet, dropping them off, and coming back for the next batch.</p><h3>What Disaggregated LLM Inference Changes in Practice</h3><p>With that mapping in place, we can define disaggregated inference more precisely.</p><figure><img alt="Side-by-side diagrams showing monolithic LLM nodes doing both prefill and decode versus separate prefill and decode pools connected by a KV cache." src="https://cdn-images-1.medium.com/max/1024/1*LUScHiflv79NIkiTTSoNmQ.png" /><figcaption>Monolithic serving: every node does everything. Disaggregated serving: separate prefill and decode pools with shared session memory.</figcaption></figure><h4>Separate Fleets for Prefill and Decode</h4><p>In a disaggregated design, you run prefill and decode on <strong>different pools of machines</strong>:</p><p>A <strong>prefill pool</strong>:</p><ul><li>Runs the heavy initial passes over prompts.</li><li>Builds the initial scratchpad for each session.</li><li>Is optimized for throughput via large batches (doing big chunks of work efficiently, even if each requests waits a bit before starting).</li></ul><p>A <strong>decode pool</strong>:</p><ul><li>Picks up sessions that already have a scratchpad.</li><li>Repeatedly generates tokens, reading and extending that memory.</li><li>Is optimized for per-step latency and concurrency (keeping many ongoing conversations moving forward at once, token by token).</li></ul><p>A router in front decides:</p><ul><li>New request?<br> → Send it to the prefill pool.<br> → Get back a session ID (a unique conversation identifier) and the location of that session’s scratchpad.</li><li>Continuing request?<br> → Send it (and its session ID) to the decode pool.<br> → Ensure it lands where the scratchpad is accessible.</li></ul><p>A common pattern in modern LLM stacks is to do something like this: distinct prefill workers and decode workers, sometimes with different machine types and scaling rules.</p><h4>Scaling Each Side Independently</h4><p>This separation lets you scale based on what the workload actually looks like:</p><ul><li>If you see a spike in new conversations, scale the prefill pool.</li><li>If you see many long-lived, chatty sessions, scale the decode pool.</li></ul><p>Instead of treating every node as if it must handle the worst-case for both phases, you let each pool be good at its specific job.</p><h4>Better UX Without Changing the Model</h4><p>An important point: disaggregation doesn’t require a new model architecture.</p><p>You can often:</p><ul><li>Serve the <strong>same model weights</strong>.</li><li>On different hardware pools.</li><li>With different scheduling logic.</li></ul><p>In practice, the two pools may still be configured differently — for example, different ways of splitting the model across devices or different batch sizes — but they’re serving the same underlying model.</p><p>From the user’s perspective, the differences show up as:</p><ul><li>Shorter time-to-first-token, because prefill can be tuned and batched separately.</li><li>Smoother streaming, because decode is no longer competing with heavy prefill work on the same machine.</li><li>Fewer stalls when the system is under load, since the workload assigned to each worker is consistent.</li></ul><blockquote><strong><em>Sidebar: For engineers</em></strong><em><br> In disaggregated setups, you’re not throwing away other tricks for splitting work across machines; you’re adding another layer on top. Both the prefill side and the decode side can still use whatever model-splitting strategy you prefer internally.</em></blockquote><blockquote><em>Prefill machines are tuned for big, heavy jobs that benefit from processing many requests at once. Decode machines are tuned for lots of tiny, back-and-forth steps that lean heavily on that scratchpad memory. One of the main design choices is where that memory lives: kept close to the machines using it for speed, or shared more widely across the network for flexibility, at the cost of a bit more overhead.</em></blockquote><h3>The Tradeoffs Hiding in the Warehouse Aisles</h3><p>All of this sounds great, but there is no free lunch. (Or free shipping.)</p><h4>More Moving Parts, More Ways to Misplace a Pallet</h4><p>When you split the system, you add new components:</p><ul><li>A router that tracks which session is where.</li><li>Autoscalers (systems that automatically add or remove servers based on load) for scaling prefill and decode pools.</li><li>Some way of tracking where each conversation’s scratchpad memory lives.</li></ul><p>That means more states to manage:</p><ul><li>Session IDs.</li><li>Scratchpad locations.</li><li>Ownership over active sessions.</li></ul><p>If something goes wrong — say a decode machine crashes — the system needs to know where the scratchpad is, whether it can resume streaming from another machine, or whether it needs to restart the answer entirely.</p><h4>Network Costs — Moving Heavy Bins Around</h4><p>Remember: the scratchpad is like a heavy pallet. Depending on context length and model size, it can be <em>big</em>.</p><p><strong>In some designs, the machines that handle prefill and decode are tightly paired</strong>. For those, the scratchpad memory never leaves that small group of machines. This minimizes network traffic but limits flexibility.</p><p><strong>In others, there’s a shared memory service that holds this scratchpad.</strong> The prefill side writes the initial notes there; the decode side reads and updates them over the network.</p><p>That second approach is more flexible. You can move conversations around or recover more easily if a decode machine fails.</p><p>However, there’s a tradeoff. Every time the model consults its scratchpad, it may have to cross the network. Under heavy traffic, the network itself can become the limiting factor. Rare but painful slow responses can be caused by delays looking up that shared memory.</p><p>This matters because the streaming phase is often limited as much by memory and data movement as by raw math. If you put the scratchpad “one network hop away,” <strong>you’re likely to shift pressure from the compute servers onto the network</strong>.</p><h3>When Monolithic LLM Serving Is Still Better</h3><p>For small systems, disaggregation can be overkill.</p><p>If you:</p><ul><li>Run a single, small model.</li><li>Have modest traffic.</li><li>Are nowhere near maxing out your hardware.</li></ul><p>Then a monolithic setup, where each node handles both prefill and decode, may be simpler and perfectly effective. You’ll still care about all the tricks to maximize performance, such as batching, quantization (storing numbers in fewer bits to save memory and cost), and good scaling practices. At the same time, you can avoid the extra complexity of multiple pools and scratchpad routing.</p><p>Disaggregated inference tends to pay off when:</p><ul><li>You’re pushing hardware limits.</li><li>You have a mix of short and long sessions.</li><li>Latency and cost are both under real pressure.</li></ul><p>One common tipping point is when you see decode time and scratchpad (KV cache) memory dominating your dashboards, even though you’ve already done the obvious things like batching and quantization in a monolithic setup.</p><figure><img alt="Simple chart showing monolithic serving is fine at low scale while disaggregated inference becomes useful at higher scale and workload complexity" src="https://cdn-images-1.medium.com/max/859/1*QTFtEY-EksToLZBSn2XfgA.png" /><figcaption>Disaggregation is often useful with larger models and higher traffic.</figcaption></figure><blockquote><strong><em>Sidebar: For engineers (again)</em></strong><em><br> Disaggregated inference also changes how things break and how you notice. A slow answer might be stuck in the first pass, in the streaming phase, waiting on that KV cache, or bouncing around the front door of the system.</em></blockquote><blockquote><em>It becomes more </em><strong><em>important to be able to follow a single conversation through the system</em></strong><em>: which machines handled the first pass, which machines are handling streaming, and where its memory lives. You also need basic locality rules so that most decode steps run near the KV cache instead of bouncing between machines. Without that, you can end up with good average metrics but terrible outliers that are hard to root-cause. And you have to choose clear rules for when to throw away that memory: forget a conversation too early, and you may not be able to resume it cleanly.</em></blockquote><h3>So What? Choosing the Right LLM Inference Architecture for Your Product</h3><p>Even if you never touch low-level infrastructure, this architectural choice affects your roadmap.</p><h4>For Product Teams and PMs</h4><p>A few questions you can ask your infrastructure or ML systems teams:</p><ul><li>“Do we know how much time we spend in the ‘first pass’ (prefill phase) over a prompt versus generating the answer (decode phase)?”</li><li>“Under peak load, what tends to go wrong first: starting new conversations, or keeping existing ones responsive?”</li><li>“Are we scaling our hardware based on new sessions, active sessions, or both?”</li></ul><p>The goal isn’t to dictate implementation details. It’s to align the system with the user experience you care about:</p><ul><li>Fast first response for interactive tools.</li><li>Predictable performance under spikes (launches, holidays, news events).</li><li>Sustainable costs as usage grows.</li></ul><p>Disaggregated inference is one of the levers teams can pull to get there.</p><h4>For Engineers and Builders</h4><p>Signals that it might be time to consider disaggregation:</p><ul><li>Decode time dominates total latency, especially for chatty workloads.</li><li>You’re constantly adding machines, but they’re spending a lot of time doing small decode steps instead of the heavy work they’re good at.</li><li>You see recurring issues with slow outliers or dropped sessions under load.</li></ul><p>Early steps might be as simple as:</p><ul><li>Instrumenting your system to separately measure prefill and decode times.</li><li>Experimenting with separate prefill and decode worker types in a small environment.</li><li>Being deliberate about KV cache placement and routing rules, rather than just whatever node got the request last time.</li></ul><p>Meanwhile, if your system is still small and simple, it’s okay to file disaggregated inference away for later. The complexity tax is real.</p><h3>Where This Is Going</h3><p>We’re still at the beginning of figuring out “the right way” to serve large language models. Model architectures will keep evolving, but serving architectures will quietly decide who can offer fast, affordable, trustworthy AI experiences.</p><p>Disaggregated inference is one of the important patterns:</p><ul><li>It acknowledges that not all inference work is the same.</li><li>It takes seriously the difference between a heavy first pass and a long tail of incremental steps.</li><li>It opens the door to hardware specialization.</li></ul><p>From there, you can imagine even richer designs:</p><ul><li>Smarter schedulers that learn when and where to place the KV cache.</li><li>Hybrid systems where a central “warehouse” coordinates with edge “mini-warehouses” on devices closer to users.</li><li>Multi-tier memory for model context that balances speed and capacity across different layers of the system.</li></ul><p>The next time a chatbot feels instant, it might not be because the model is magical. It might be because somewhere, an AI warehouse is running a very well-organized operation: pickers, couriers, pallets, and all.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72c175d53d59" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science-collective/why-chatbots-feel-fast-ai-inference-72c175d53d59">Inside the AI Warehouse: How Modern Systems Keep Chatbots Fast</a> was originally published in <a href="https://medium.com/data-science-collective">Data Science Collective</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Embracing the Joy of Missing Out]]></title>
            <link>https://medium.com/know-thyself-heal-thyself/embracing-the-joy-of-missing-out-9a0c0eb5f418?source=rss-e20dc259cf29------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a0c0eb5f418</guid>
            <category><![CDATA[mental-health]]></category>
            <category><![CDATA[life]]></category>
            <category><![CDATA[life-lessons]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[self-improvement]]></category>
            <dc:creator><![CDATA[David Oy]]></dc:creator>
            <pubDate>Fri, 25 Aug 2023 06:37:50 GMT</pubDate>
            <atom:updated>2023-08-25T06:37:50.399Z</atom:updated>
            <content:encoded><![CDATA[<h4>Reclaim Your Life by Accepting That You Will Miss Out</h4><p>Since I started my software career, I have constantly felt behind. How do my colleagues find time to learn about new technologies, work on side projects, and work through their tasks at a breakneck speed? How do they do this while traveling, having a partner, being a parent, and keeping up a social life?</p><p>Coined by Anil Dash in a blog post in 2012, the joy of missing out (JOMO) is a play on the popular fear of missing out (FOMO). I skimmed that article in preparation for writing this one, albeit I have not read much of Anil’s content nor Tanya Dalton’s 2019 book by the same name. Yet, these thoughts are inspired by Oliver Burkeman’s <em>Four Thousand Weeks.</em></p><p>What I keep seeing in career coaching communities on Slack, Reddit, and everywhere else is this common belief that you should be doing more. I hear this from teammates as well. This constant overwhelm whereby you want to give 100% to your job, 100% to your kids, 100% to your spouse, 100% to your fitness, and so on.</p><p>As you probably already calculated, that is <strong>mathematically impossible</strong>. We have <strong>finite time</strong>. The number of things we can do with that time, especially when considering all the combinations of said things over the next year of our life, <strong>approaches infinity</strong>. So <em>we are going to fail to do everything</em>. And that is okay.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_C5gncVyTsCEOfIw" /><figcaption>Photo by <a href="https://unsplash.com/@fredmarriage?utm_source=medium&amp;utm_medium=referral">freddie marriage</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Take a deep breath. With that knowledge, you are freed, unshackled. You are choosing to read this article right now. What does that mean? It means you are not choosing to do a whole host of other things. I want to make <strong>these minutes worth it for you</strong>, because I know you could be checking your email (you’re thinking about, right?) or spending time with loved ones.</p><p>Every time you choose to do something, you are choosing not to do something else. With that knowledge, prioritize. Be conscious of what you’re saying no to, and say it happily. No can be your default response. Why? You might have room for 2, maybe 3, things at a time in your life. That’s good. Make them things that matter.</p><p>I recently got off most social media. I stopped responding to every email and professional invite that came my way. That time was reclaimed. I now miss out on all of the updates of lives I could be living and events I could be going to from Facebook. I’m okay with that. I’m harder to reach, and that’s a good thing.</p><p>I have also accepted that the list of things that I expected myself to maintain is unreasonable. Sure, journaling, meditating, lifting weights, doing cardio, planning your day, reading, doing side projects, starting technical projects, maintaining several close friendships, volunteering, blogging, and so on are great for your life. Can I do all of them? No. Is that a failure? No. I now pick what I want to do, knowing I am choosing to do it.</p><p>It’s not a perfect system, but it’s much better than being under the illusion that I <em>should </em>be able to do it all and that anything is failure. If I thought I could do it all, I would fail to prioritize.</p><p>So, perhaps this article is really about prioritization. But, honestly, I want to lean in to finding the joy of missing out. Then, how much sweeter are the things you choose to do? By accepting that you are missing out on everything else by choosing to do what you are doing right now, you can spend your time enjoying it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rfukJLKz7zhulyj9" /><figcaption>Photo by <a href="https://unsplash.com/@marijkerrie?utm_source=medium&amp;utm_medium=referral">Marije Woudsma</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a0c0eb5f418" width="1" height="1" alt=""><hr><p><a href="https://medium.com/know-thyself-heal-thyself/embracing-the-joy-of-missing-out-9a0c0eb5f418">Embracing the Joy of Missing Out</a> was originally published in <a href="https://medium.com/know-thyself-heal-thyself">Know Thyself, Heal Thyself</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Promise of Analog AI]]></title>
            <link>https://medium.com/data-science/the-promise-of-analog-ai-e3a8c0daf146?source=rss-e20dc259cf29------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3a8c0daf146</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[David Oy]]></dc:creator>
            <pubDate>Tue, 29 Mar 2022 17:18:06 GMT</pubDate>
            <atom:updated>2022-03-29T17:18:06.469Z</atom:updated>
            <content:encoded><![CDATA[<h4>Why Analog AI is About to be in Everything from Alexa to Your iPhone</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Z7I7i9Z2qHCVSNnV" /><figcaption>Photo by <a href="https://unsplash.com/@loewe?utm_source=medium&amp;utm_medium=referral">Loewe Technology</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Neural networks keep getting larger and more energy-intensive. As a result, the future of AI depends on making AI run more efficiently and on smaller devices.</p><p>That’s why it’s <strong>alarming that progress is slowing on making AI more efficient</strong>.</p><p>The most resource-intensive aspect of AI is data transfer. <em>Transferring data often takes more time and power</em> than actually computing with it. To tackle this, popular approaches today include reducing the distance that data needs to travel and the data size. There is a limit to how small we can make chips, so minimizing distance can only do so much. Similarly, reducing data precision works to a point but then starts to hurt performance.</p><p>We’ve gone from 32- and 64-bit floating-point numbers to <a href="https://semiengineering.com/artificial-intelligence-chips-must-get-the-floating-point-math-right/">dedicated AI chips with 8-bit data</a>. The speedups were dramatic, but lower precision will affect accuracy. Other approaches are being explored, but the <strong>limits of digital are starting to be hit</strong>.</p><p>Decades ago, digital computers trumped analog computers due to the need for precision. Just like reducing data precision from 32-bits to 8-bits did not impact accuracy in learning, we are finding that <em>precision is less important for AI</em>. It’s time for the comeback of analog. Researchers and industry are racing to meet the challenge, with <strong>IBM recently announcing </strong><a href="https://aihw-composer.draco.res.ibm.com/"><strong>100x performance</strong></a><strong> and </strong><a href="https://spectrum.ieee.org/analog-ai"><strong>100x efficiency </strong></a><strong>via analog AI. How’s this possible?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*N1y15put0NxtN2l-" /><figcaption>Photo by <a href="https://unsplash.com/@christianem?utm_source=medium&amp;utm_medium=referral">Christian Englmeier</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3><strong>The Von Neumann Bottleneck</strong></h3><p>In computing, the von Neumann bottleneck describes the phenomenon that <strong>system throughput is limited by the relative speed of data processing versus movement</strong>. <em>If we could store and process the data in the same place, we would eliminate data movement, removing this bottleneck.</em></p><p>With analog AI, data is stored and processed in the same place. Using non-volatile memory devices, analog can store data without power for <a href="https://analog-ai-demo.mybluemix.net/">up to 10 years</a>.</p><p>At the same time, the data needs fewer transistors than digital circuitry. In <strong>digital machines, you have 1s and 0s</strong>. To represent a number in the range -128 to 127, you’d need 8 bits. To add two numbers you’d need <em>approximately 200 transistors</em>.</p><p>Unlike digital, analog is not binary. It can represent a whole range of numbers based on the conductance or resistance (<em>measure of electrical current</em>). Normally, digital has a cut-off threshold for 0s and 1s, but analog uses the actual value. As a result, <strong>you can represent many numbers in one transistor</strong>, as long as you’re okay with the variability that results naturally from the transistor’s physical properties and randomness. This is problematic in traditional computing but workable in deep learning.</p><h3><strong>How Does Analog AI Process Data?</strong></h3><p>In neural networks, the <em>most common operator is multiply-accumulate</em>. You multiply sets of numbers and then sum them up, as used in matrix multiplication that’s the backbone of deep learning. If you store the inputs as arrays, you can actually do this in one swoop by utilizing physical engineering laws (<a href="https://en.wikipedia.org/wiki/Ohm%27s_law">Ohm’s Law</a> to multiply, <a href="https://en.wikipedia.org/wiki/Kirchhoff%27s_circuit_laws">Kirchoff’s Law </a>to sum) on a full matrix in parallel.</p><p>This is the crux of analog AI. <strong>If it was that easy</strong>, analog AI would already be used. <em>Why aren’t we using analog AI yet?</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cR_uoUL-OyW8L8Ds" /><figcaption>Photo by <a href="https://unsplash.com/@othentikisra?utm_source=medium&amp;utm_medium=referral">israel palacio</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>The Problems of Variability</h3><p>Conductance can vary based on everything from the manufacturing of the chip to environmental factors. The variation can add up and throw neural networks off.</p><p>Early approaches used analog and digital together, with digital-to-analog and analog-to-digital convertors between layers. However, this needs to be limited, as conversion is slower and more energy-intensive than staying analog. It can create its own bottleneck.</p><p>Analog is also not ideal for high-precision applications, where every bit matters. Ditto for applications where explainability is important: <em>if you want to understand why your neural network made a certain prediction, introducing variability makes explaining it more challenging.</em> Your network isn’t deterministic. Given the same data, variability may lead the network to a different prediction next time.</p><p>That’s why analog AI is best-suited now for AI on the edge devices, like your phone and Google Home. Your <strong>battery would last much longer, </strong>your<strong> energy bill would go down, </strong>and you can even get a <strong>smaller device</strong> (<em>fewer transistors</em>).</p><p>The barriers to wider adoption are being worked on by researchers. <strong>What’s next?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cjVw3-ocGLA_Hdid" /><figcaption>Photo by <a href="https://unsplash.com/@nicolescapturedmoments?utm_source=medium&amp;utm_medium=referral">Nicole Avagliano</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>The Future</h3><p>Right now, analog AI works successfully for multiply-accumulate operations. For other operations, it is still ideal to provide their own circuitry, as <em>programming nonvolatile memory devices takes longer and results in faster wear and tear than traditional devices</em>.</p><p>Inference does not typically require reprogramming these devices, since weights rarely change. <strong>For training, however, they would require constant reconfiguration</strong>.</p><p>In addition, analog’s variability results in a mismatch between error in forward propagation (<em>inference</em>) and backpropogation (<em>calculating error during training</em>). <em>This can cause issues during training</em>. That leads to a need for separate circuits for backpropogation, likely digital. However, researchers are already <strong>coming up with ways to train on the same analog AI neural networks </strong>so that they are <strong>end-to-end</strong>. For example, a team from the University of Montreal and Rain Neurophormics <a href="https://arxiv.org/abs/2006.01981">came up with equilibrium propagation</a> to use in end-to-end chips.</p><h3>The Takeaway</h3><p>As ways to make neural networks faster and more energy-efficient achieve diminishing returns, <strong>analog will likely make a comeback</strong>. Neural networks have lower precision needs than traditional computing, making analog possible.</p><p>With the ability to produce <em>networks that are many times faster, smaller, and more energy-efficient</em>, analog AI is becoming a hot research area and one that has enormous commercial potential. Expect to see analog circuitry in your smartwatch, phone, and home assistants soon!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3a8c0daf146" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/the-promise-of-analog-ai-e3a8c0daf146">The Promise of Analog AI</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making Deep Learning Climate-Friendly]]></title>
            <link>https://medium.com/data-science/making-deep-learning-climate-friendly-74ed4f2404e2?source=rss-e20dc259cf29------2</link>
            <guid isPermaLink="false">https://medium.com/p/74ed4f2404e2</guid>
            <category><![CDATA[energy]]></category>
            <category><![CDATA[climate-change]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[tech]]></category>
            <dc:creator><![CDATA[David Oy]]></dc:creator>
            <pubDate>Thu, 17 Mar 2022 21:33:55 GMT</pubDate>
            <atom:updated>2022-03-17T21:33:55.085Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to Tackle the Carbon Footprint of AI</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2KrUPGztVtNxb75l" /><figcaption>Photo by <a href="https://unsplash.com/@instagramfotografin?utm_source=medium&amp;utm_medium=referral">Peggy Anke</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Deep learning is bringing many benefits to the world: solving the 50-year-old protein folding problem, detecting cancer, and improving the power grid. While there is so much that deep learning is powering, we also need to consider the costs.</p><p>In the quest for more accurate and generalizable models, there has been an explosion in network size and thereby power consumption. It seems like every year model sizes skyrocket. In 2020, GPT-3 was released with <strong>175 billion </strong>parameters and a $4.6M theoretical training cost with the lowest-priced GPU cloud on the market.</p><p>Less than a year later, Google released Switch Transformer with over a <strong>trillion</strong> parameters. OpenAI found that the compute required for best-in-class large models doubles <a href="https://openai.com/blog/ai-and-compute/">every 3.4 months (300,000x in six years</a>). With the exponential increase in parameters, there’s an <strong>exponential increase in energy</strong>.</p><p>How are AI researchers and engineers <em>tackling this issue</em>?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nOpVdc15a7C_m0NH" /><figcaption>Photo by <a href="https://unsplash.com/@dylandgillis?utm_source=medium&amp;utm_medium=referral">Dylan Gillis</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3><strong>Neural Architectures</strong></h3><p>Common wisdom dictates that larger models provide better results. Yet, that is not always the case. Google Research just released a <a href="https://arxiv.org/abs/2110.02095?utm_campaign=The%20Batch&amp;utm_medium=email&amp;_hsmi=203440838&amp;_hsenc=p2ANqtz-8qegFif9haSvA8KwypHHya-kyDgcMp7_qkYf-6icESppyp55Ih7vmMg4uWFhFU-hSj3bAnxZIrhUE8Q14hvqi0VPHg6g&amp;utm_content=203440838&amp;utm_source=hs_email">meta-analysis </a>showing how <strong>higher pre-training accuracy reaches a saturation point</strong>. As the model accuracy increases, its ability to be fine-tuned to solve specific tasks <em>(i.e. transfer learning) </em>does not increase as quickly. At some point, <strong>accuracy can even decrease</strong>.</p><p>When you start questioning if larger models are always the answer, the opportunity opens to explore improving current architectures. More effort is being placed on architecture selection, with tools like <a href="https://tinyml.mit.edu/projects/spvnas/papers/spvnas_eccv.pdf"><strong>evolutionary algorithms </strong>being used to select the best neural architecture</a> for a task, resulting in many times less computation needed.</p><p>Another area gaining interest is the <strong>Lottery Ticket Hypothesis</strong>, where a dense subnetwork (“lottery ticket”) of the neural network can be trained to achieve similar performance as the entire network. Previously, this could only be done after training the full network, but I discuss in detail <a href="https://towardsdatascience.com/demystifying-the-lottery-ticket-hypothesis-in-deep-learning-158570b62674">here how these lottery tickets are being found earlier</a>.</p><p>These approaches challenge the notion that bigger is better. At the same time, they skip the cost of training large models to only then prune large parts of the model. Instead, they skip straight to an optimal architecture to make training models cheaper, faster, and more energy-efficient.</p><h3><strong>Data Movement</strong></h3><p>While training large models consumes a high amount of energy, the bulk goes towards inference (<a href="https://www.forbes.com/sites/moorinsights/2019/05/09/google-cloud-doubles-down-on-nvidia-gpus-for-inference/#244ad92a6792">80–90%</a>). Ideally, a model like ResNet50 is trained once, then used many times across applications. As a result, much effort goes into the inference stage. The biggest area here is data transfer. Reducing the size of our networks helps, but after that, the data must be pushed through no matter what. There are software and hardware approaches to this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8CCHC_GUewk34ryv" /><figcaption>Photo by <a href="https://unsplash.com/@aoddeh?utm_source=medium&amp;utm_medium=referral">Ahmad Odeh</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>Software</em></p><p>On the software side, <strong>datatype selection</strong> is key. While higher precision datatypes may be necessary for some applications, they may not improve model performance in others. Less precise datatypes require less data to be transferred, say a 16-bit floating-point versus a 32-bit floating-point number. Different companies are creating different datatypes that further reduce the data size and processing requirements, such as MSFP by Microsoft.</p><p>Models that are run often can also leverage <strong>batching.</strong> Sending requests in batches is often more efficient than sending a single request or data packet.</p><p><em>Hardware</em></p><p>On the hardware side, ensuring the data is close together is important. Shared memory between your deep learning server and client is more efficient than sending it back and forth. Doing edge machine learning on your iPhone is more efficient (and safer!) than sending that data over to Apple’s data center one state over. The closer together your data is, the less transfer needs to occur.</p><p>There are also specialized chips for different deep learning applications, like <a href="https://ieeexplore.ieee.org/document/8686088">Eyeriss</a>, which maximizes data reuse via a reconfigurable on-chip network.</p><p>Compression is also commonly used to minimize the data transferred, since it can require fewer resources to compress data rather than send it outright. This is particularly true of sparse networks, where many tricks are used to take advantage of the sparsity. Sparsity is also a common motivation for pruning, as <strong>0-valued entries can often be ignored in storage and computation</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5cHsx6amZH4tiILf" /><figcaption>Photo by <a href="https://unsplash.com/@clintadair?utm_source=medium&amp;utm_medium=referral">Clint Adair</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3><strong>Data Storage</strong></h3><p>Beyond data movement, data storage is another rich hardware area for energy savings. As deep learning draws inspiration from the brain, researchers look at the brain’s energy efficiency. The brain is up to <a href="https://www.purdue.edu/newsroom/releases/2019/Q4/expert-how-to-make-deep-learning-as-energy-efficient-as-the-brain.html">1000x as efficient</a> as deep learning. Unlike our <em>digital </em>computer world of 1s and 0s, the brain’s synapses look more like <em>analog </em>systems. As the brain learns and forgets, the signals get weaker and stronger. Using this more <strong>continuous analog spectrum</strong>, researchers have <a href="https://www.nature.com/articles/s41467-020-16866-6">created systems closer to the energy efficiency of the brain</a>.</p><p>In a similar fashion, other forms of computing are being explored. For example, storing photons instead of electrons and representing data in multiple states at once (<em>quantum computing</em>). These may be more efficient ways of storing data.</p><h3>Closing Thoughts</h3><p>Deep learning has done so much good for the world and it has the potential to do even more. With the growth in usage of AI, making it more efficient becomes critical. Researchers are looking at neural architecture and size as a key area. At the same time, they are exploring ways of reducing the cost of data storage and data transfer, <strong>impacting most technology</strong> including <em>the device you are reading this on</em>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74ed4f2404e2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/making-deep-learning-climate-friendly-74ed4f2404e2">Making Deep Learning Climate-Friendly</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying the Lottery Ticket Hypothesis in Deep Learning]]></title>
            <link>https://medium.com/data-science/demystifying-the-lottery-ticket-hypothesis-in-deep-learning-158570b62674?source=rss-e20dc259cf29------2</link>
            <guid isPermaLink="false">https://medium.com/p/158570b62674</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[David Oy]]></dc:creator>
            <pubDate>Thu, 03 Mar 2022 09:25:32 GMT</pubDate>
            <atom:updated>2022-03-03T09:25:32.389Z</atom:updated>
            <content:encoded><![CDATA[<h4>Why lottery tickets are the next big thing in training neural networks</h4><p>Training neural networks is expensive. OpenAI’s GPT-3 has been calculated to have a <a href="https://lambdalabs.com/blog/demystifying-gpt-3/">training cost of $4.6M</a> using the lowest-cost cloud GPU on the market. It’s no wonder that <a href="https://arxiv.org/abs/1803.03635">Frankle and Carbin’s 2019 Lottery Ticket Hypothesis</a> started a gold rush in research, with attention from top academic minds and tech giants like Facebook and Microsoft. In the paper, they prove the existence of <strong>winning (lottery) tickets</strong>: subnetworks of a neural network that can be <em>trained to produce performance as good as the original network</em>, with a much smaller size. In the post, I’ll tackle how this works, why it is revolutionary, and the state of research.</p><h3>Why Lottery Tickets?</h3><p>Traditional wisdom says that neural networks are best pruned after training, not at the start. By pruning weights, neurons, or other components, the resulting neural network is <strong>smaller, faster, and consumes fewer resources</strong> during inference. When done right, the accuracy is unaffected while the network size can shrink manifold.</p><p>By flipping traditional wisdom on its head, we can consider <strong><em>whether we could have pruned the network before training</em></strong> and achieved the same result. In other words, <em>was the information from the pruned components necessary for the network to learn, even if not to represent its learning?</em></p><p>The Lottery Ticket Hypothesis focuses on pruning weights and offers empirical evidence that certain pruned subnetworks could be trained from the start to achieve similar performance to the entire network. How? Iterative Magnitude Pruning.</p><h3><strong>Iterative Magnitude Pruning</strong></h3><p>When a task like this was tried historically, the pruned networks weights would be reinitialized randomly and the performance would drop off quickly.</p><p>The key difference here is that the weights were returned to their <strong>original</strong> initialization. When trained, the results matched the original performance in the same training time, at high levels of pruning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yGm5OxVhop2ZYUFI" /><figcaption>Photo by <a href="https://unsplash.com/@tegethoff?utm_source=medium&amp;utm_medium=referral">Mark Tegethoff</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This suggests that these lottery tickets exist, as an intersection of a specific subnetwork and initial weights. They are “winning the lottery,” so to say, as the match of that architecture and those weights perform as well as the entire network. <strong>Does this hold for bigger models?</strong></p><p>For bigger models, this does not hold true with the same approach. When looking at sensitivity to noise, Frankle and Carbin duplicated the pruned networks and trained them on data ordered differently. IMP succeeds where <strong>linear mode connectivity</strong> exists, a very rare phenomenon where multiple networks converge to the same local minima. For small networks, this happens naturally. For large networks, it does not. So what to do?</p><p>Starting with a smaller learning rate results in IMP working for large models, as sensitivity to initial noise from the data is lessened. The learning rate can be increased over time. The other finding is that rewinding our pruned neural network’s weights to their values at a later training iteration rather than the first iteration works as well. For example, the weights at the 10th iteration in a 1000 iteration training.</p><p>These results have held steady across architectures as different as transformers, LSTMs, CNNs, and reinforcement learning architectures.</p><p>While this paper <strong>proved the existence of these lottery tickets</strong>, it does <strong>not yet provide a way to identify them</strong>. Hence, the gold rush in finding their properties and whether they can be identified before training. They’re also inspiring work in heuristics for pruning early, since our current heuristics are focused on pruning after training.</p><h3>Current Research</h3><p><a href="https://arxiv.org/abs/1906.02773">One Ticket to Win Them All</a> (2019) shows that <strong>lottery tickets encode information that is invariant to datatype and optimizers</strong>. They are able to successfully transfer lottery tickets between networks trained on different datatypes (e.g. VGG to ImageNet), finding success.</p><p>A key indicator was the relative size of the training data for the networks. <em>If the lottery ticket source was trained on a larger dataset than the destination network, it performed better</em>; otherwise, similarly or worse.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jVBVTOTQ3AjRZGFF" /><figcaption>Photo by <a href="https://unsplash.com/@moritz_photography?utm_source=medium&amp;utm_medium=referral">Moritz Kindler</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><a href="https://arxiv.org/abs/1909.11957">Drawing Early-Bird Tickets</a> (2019): This paper aims to prove that lottery tickets can be found early in training. Each training iteration, they compute a pruning mask. If the mask in the last iteration and this one have a mask distance <em>(using Hamming distance)</em> below a certain threshold, the network stops to prune.</p><p><a href="https://arxiv.org/abs/2006.05467">Pruning Neural Networks Without Any Data by Iteratively Conserving Synaptic Flow</a> (2020): This paper focuses on calculating pruning at initialization <em>with no data</em>. It outperforms existing state-of-the-art pruning pruning algorithms at initialization. The technique focuses on maximizing <strong>critical compression</strong>, <em>the maximum pruning that can occur without impacting performance. </em>To do so, the authors aim to prevent entire layers from being pruned. The network does this by positively scoring keeping layers and reevaluating the score every time the network prunes.</p><h3>Closing Thoughts</h3><p>The existence of small subnetworks in neural architectures that can be trained to perform as well as the entire neural network is opening a world of possibilities for efficient training. In the process, researchers are learning a lot about how neural networks learn and what is necessary for learning. And who knows? One day soon we may be able to prune our networks <strong><em>before </em></strong>training, saving time, compute, and energy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9_NWVjR3bcaefsNq" /><figcaption>Photo by <a href="https://unsplash.com/@emilianovittoriosi?utm_source=medium&amp;utm_medium=referral">Emiliano Vittoriosi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=158570b62674" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/demystifying-the-lottery-ticket-hypothesis-in-deep-learning-158570b62674">Demystifying the Lottery Ticket Hypothesis in Deep Learning</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Two Ways to Immediately Improve Your Python Code]]></title>
            <link>https://blog.devgenius.io/two-ways-to-immediately-improve-your-python-code-a249b0250c22?source=rss-e20dc259cf29------2</link>
            <guid isPermaLink="false">https://medium.com/p/a249b0250c22</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[David Oy]]></dc:creator>
            <pubDate>Tue, 15 Feb 2022 10:58:21 GMT</pubDate>
            <atom:updated>2022-02-15T10:58:21.149Z</atom:updated>
            <content:encoded><![CDATA[<h3>Two of the Most Common Mistakes Even Top Developers Make</h3><p>With all the talks of AI, have you ever thought about how good ol’ technology can help develop you as a software engineer? Applying software analysis tools to your code can seem tricky, yet it’s getting easier.</p><p>I <a href="https://blog.devgenius.io/your-github-code-could-be-better-c77583e94e79">applied LGTM </a>to a few public codebases to identify common mistakes.</p><p>See the two below to find ways to improve your code immediately.</p><h3>Precise Asserts</h3><p>For testing, Python has a full range of assets, such as assertIn, assertGreater, and assertIsNotNone. As developers, it’s common to stick to assertTrue or assertFalse. However, these assertions will not provide descriptive messages. Which would be easier for you to understand?</p><pre>AssertionError: False is not true : Not found.<br>// Or...<br>AssertionError: &#39;message&#39; not found in &#39;Custom string&#39; : Not found.</pre><figure><img alt="Python message" src="https://cdn-images-1.medium.com/max/1024/0*7QsgyKDhP4H8Ussn" /><figcaption>Photo by <a href="https://unsplash.com/@epicantus?utm_source=medium&amp;utm_medium=referral">Daria Nepriakhina</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Of course, you can add custom messages to provide more information, but it’s helpful when the in-built function does it for you already.</p><p>So when you are writing tests, you may want to think carefully any time you are using assertTrue or assertFalse. Is there a more precise assert that will save you a headache debugging later?</p><h3>Focused Imports</h3><p>Look at the typical Python program and you’ll find <strong>lots of imports</strong>. We add to this list often, yet <em>how often do we remove from it</em>? We might remove that last NumPy usage, yet did we remove the import?</p><figure><img alt="Importing Python packages" src="https://cdn-images-1.medium.com/max/1024/0*24jQJGo_6a1kcZx-" /><figcaption>Photo by <a href="https://unsplash.com/@rosebox?utm_source=medium&amp;utm_medium=referral">RoseBox رز باکس</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If we want to avoid our programs being bloated, it makes sense to consider when imports can be removed when we are updating our code. This may be a function better suited to a static analyzer, as even the most diligent engineer is likely to miss some unused imports. That said, keeping our eye on it can reduce the size of our programs.</p><p>Similarly, importing only what we need is crucial. Lots of Python programs will import everything (“from &lt;module&gt; import *”). Especially if the module doesn’t define “__all__”, our global namespace can be polluted. The result is lots of unused variables, functions, and more. Plus, potential naming collisions! This is good to avoid.</p><h3>Bonuses: Default Arguments, Variable Definitions</h3><p>For those who read to the end, here are a couple of extra bonuses:</p><p><strong>Never Mutate Default Arguments! </strong>Default arguments are evaluated when the function is defined… only once. Say we have the below program:</p><pre>def example(inputs=[]):<br>    inputs.append(&quot;ran_once&quot;)<br>    return inputs</pre><p>The first time it runs, it’ll return [“ran_once”]. The second time, [“ran_once”, “ran_once”]. And so on. Unless this is the behavior you want<em>, and it rarely is</em>, here’s a better way to write the function:</p><pre>def example(inputs=None): </pre><pre>inputs.append(&quot;ran_once&quot;)<br>    if inputs is None:<br>      inputs = []<br>    inputs.append(&quot;ran_once&quot;)<br>    return inputs</pre><p><strong>Variable Definitions. </strong>It is incredibly common that variables are redefined before they are used or never used. I suspect this happens during code changes. This may be something to keep an eye on when updating code, but it’s also something a static analyzer can help with.</p><p>At the same time, programs often save the return value of a function when it will not be used. For example, you want to call a function to start a service, yet you never check the return value. In that case, not saving the return value is less confusing for folks reading your code and reduces memory usage.</p><p>You’ve made it to the end! Bonuses and all. Kudos to you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*h7QtRjc2uhRuGyFP" /><figcaption>Photo by <a href="https://unsplash.com/@wflwong?utm_source=medium&amp;utm_medium=referral">Warren Wong</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a249b0250c22" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/two-ways-to-immediately-improve-your-python-code-a249b0250c22">Two Ways to Immediately Improve Your Python Code</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>